ctb_formats_x86/
instruction_sets.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! X86 and X64 instruction set analyzer.
21
22// Approach to this is inspired by https://github.com/IrreducibleOSS/instruction-set-analyzer though this is an independent reimplementation (and doesn't support iterating directories).
23
24#[allow(
25    unused_imports,
26    clippy::wildcard_imports,
27    reason = "Standard workspace crate prelude"
28)]
29pub(crate) use ctb_utilities::*;
30
31use iced_x86::{Code, Decoder, DecoderOptions};
32use object::read::archive::ArchiveFile;
33use object::{
34    Architecture, File, FileKind, Object, ObjectSection, SectionKind,
35};
36use std::collections::BTreeSet;
37
38/// Extracts a sorted, deduplicated list of CPU instruction set names (e.g.
39/// `"SSE2"`, `"AVX"`, `"AVX2"`, `"AVX512F"`) found within the given object file
40/// or archive file data.
41///
42/// # Errors
43/// Returns an error if the input data is neither a valid object file nor a
44/// valid archive file.
45pub fn extract_instruction_sets(data: &[u8]) -> Result<Vec<String>> {
46    let mut features = BTreeSet::new();
47    process_data(data, &mut features)?;
48    Ok(features.into_iter().collect())
49}
50
51fn process_data(data: &[u8], features: &mut BTreeSet<String>) -> Result<()> {
52    let kind = FileKind::parse(data).context("Failed to parse file format")?;
53
54    if kind == FileKind::Archive {
55        let archive = ArchiveFile::parse(data)
56            .context("Failed to parse archive header")?;
57        for member in archive.members().flatten() {
58            if let Ok(member_data) = member.data(data) {
59                let _ = process_data(member_data, features);
60            }
61        }
62    } else {
63        let file = File::parse(data).context("Failed to parse object file")?;
64        let bitness = match file.architecture() {
65            Architecture::X86_64 | Architecture::X86_64_X32 => 64_u32,
66            Architecture::I386 => 32_u32,
67            _ => return Ok(()),
68        };
69
70        for section in file.sections() {
71            if section.kind() == SectionKind::Text {
72                if let Ok(section_data) = section.uncompressed_data() {
73                    let decoder = Decoder::new(
74                        bitness,
75                        &section_data,
76                        DecoderOptions::NONE,
77                    );
78                    for instr in decoder {
79                        if instr.code() != Code::INVALID {
80                            for cpuid in instr.cpuid_features() {
81                                features.insert(format!("{cpuid:?}"));
82                            }
83                        }
84                    }
85                }
86            }
87        }
88    }
89
90    Ok(())
91}
92
93#[cfg(test)]
94#[allow(
95    clippy::panic,
96    clippy::expect_used,
97    clippy::unwrap_used,
98    clippy::unwrap_in_result,
99    clippy::panic_in_result_fn,
100    clippy::indexing_slicing,
101    clippy::arithmetic_side_effects,
102    reason = "Standard repository test boilerplate"
103)]
104mod tests {
105    use super::*;
106
107    fn create_sample_elf() -> Vec<u8> {
108        let mut elf = Vec::new();
109        // --- ELF64 Header (64 bytes) ---
110        // e_ident
111        elf.extend_from_slice(&[
112            0x7f, b'E', b'L', b'F', 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
113        ]);
114        // e_type (1 = ET_REL)
115        elf.extend_from_slice(&[1, 0]);
116        // e_machine (62 = EM_X86_64)
117        elf.extend_from_slice(&[62, 0]);
118        // e_version (1)
119        elf.extend_from_slice(&[1, 0, 0, 0]);
120        // e_entry (0)
121        elf.extend_from_slice(&[0; 8]);
122        // e_phoff (0)
123        elf.extend_from_slice(&[0; 8]);
124        // e_shoff (97)
125        elf.extend_from_slice(&[97, 0, 0, 0, 0, 0, 0, 0]);
126        // e_flags (0)
127        elf.extend_from_slice(&[0, 0, 0, 0]);
128        // e_ehsize (64)
129        elf.extend_from_slice(&[64, 0]);
130        // e_phentsize (0)
131        elf.extend_from_slice(&[0, 0]);
132        // e_phnum (0)
133        elf.extend_from_slice(&[0, 0]);
134        // e_shentsize (64)
135        elf.extend_from_slice(&[64, 0]);
136        // e_shnum (3)
137        elf.extend_from_slice(&[3, 0]);
138        // e_shstrndx (2)
139        elf.extend_from_slice(&[2, 0]);
140
141        // --- Offset 64..80: .text section contents (16 bytes) ---
142        // addpd xmm0, xmm1 (SSE2)
143        elf.extend_from_slice(&[0x66, 0x0f, 0x58, 0xc1]);
144        // vaddpd xmm0, xmm1, xmm1 (AVX)
145        elf.extend_from_slice(&[0xc5, 0xf9, 0x58, 0xc1]);
146        // vpaddd ymm0, ymm1, ymm2 (AVX2)
147        elf.extend_from_slice(&[0xc5, 0xdd, 0xfe, 0xc2]);
148        // nop padding
149        elf.extend_from_slice(&[0x90, 0x90, 0x90, 0x90]);
150
151        // --- Offset 80..97: .shstrtab section contents (17 bytes) ---
152        elf.extend_from_slice(b"\0.text\0.shstrtab\0");
153
154        // --- Offset 97..289: Section Headers (3 * 64 bytes = 192 bytes) ---
155        // Section Header 0: NULL
156        elf.extend_from_slice(&[0; 64]);
157
158        // Section Header 1: .text
159        elf.extend_from_slice(&[1, 0, 0, 0]); // sh_name (offset 1 in shstrtab)
160        elf.extend_from_slice(&[1, 0, 0, 0]); // sh_type (SHT_PROGBITS = 1)
161        elf.extend_from_slice(&[6, 0, 0, 0, 0, 0, 0, 0]); // sh_flags (ALLOC|EXEC = 6)
162        elf.extend_from_slice(&[0; 8]); // sh_addr
163        elf.extend_from_slice(&[64, 0, 0, 0, 0, 0, 0, 0]); // sh_offset (64)
164        elf.extend_from_slice(&[16, 0, 0, 0, 0, 0, 0, 0]); // sh_size (16)
165        elf.extend_from_slice(&[0; 4]); // sh_link
166        elf.extend_from_slice(&[0; 4]); // sh_info
167        elf.extend_from_slice(&[1, 0, 0, 0, 0, 0, 0, 0]); // sh_addralign
168        elf.extend_from_slice(&[0; 8]); // sh_entsize
169
170        // Section Header 2: .shstrtab
171        elf.extend_from_slice(&[7, 0, 0, 0]); // sh_name (offset 7 in shstrtab)
172        elf.extend_from_slice(&[3, 0, 0, 0]); // sh_type (SHT_STRTAB = 3)
173        elf.extend_from_slice(&[0; 8]); // sh_flags
174        elf.extend_from_slice(&[0; 8]); // sh_addr
175        elf.extend_from_slice(&[80, 0, 0, 0, 0, 0, 0, 0]); // sh_offset (80)
176        elf.extend_from_slice(&[17, 0, 0, 0, 0, 0, 0, 0]); // sh_size (17)
177        elf.extend_from_slice(&[0; 4]); // sh_link
178        elf.extend_from_slice(&[0; 4]); // sh_info
179        elf.extend_from_slice(&[1, 0, 0, 0, 0, 0, 0, 0]); // sh_addralign
180        elf.extend_from_slice(&[0; 8]); // sh_entsize
181
182        elf
183    }
184
185    #[crate::ctb_test]
186    fn test_invalid_file_data() {
187        let invalid_data = b"not a valid binary or archive";
188        extract_instruction_sets(invalid_data).unwrap_err();
189    }
190
191    #[crate::ctb_test]
192    fn test_minimal_elf_x86_64() {
193        let elf_bytes = create_sample_elf();
194        let result = extract_instruction_sets(&elf_bytes).unwrap();
195        assert!(result.contains(&"SSE2".to_string()));
196        assert!(result.contains(&"AVX".to_string()));
197        assert!(result.contains(&"AVX2".to_string()));
198    }
199
200    #[crate::ctb_test]
201    fn test_archive_containing_elf() {
202        let elf_bytes = create_sample_elf();
203        let mut ar = Vec::new();
204        // Archive magic
205        ar.extend_from_slice(b"!<arch>\n");
206        // Member header (60 bytes)
207        ar.extend_from_slice(b"sample.o/       "); // name (16)
208        ar.extend_from_slice(b"0           "); // mtime (12)
209        ar.extend_from_slice(b"0     "); // uid (6)
210        ar.extend_from_slice(b"0     "); // gid (6)
211        ar.extend_from_slice(b"644     "); // mode (8)
212        let size_str = format!("{:<10}", elf_bytes.len());
213        ar.extend_from_slice(size_str.as_bytes()); // size (10)
214        ar.extend_from_slice(b"`\n"); // magic (2)
215        // Member contents
216        ar.extend_from_slice(&elf_bytes);
217
218        let result = extract_instruction_sets(&ar).unwrap();
219        assert!(result.contains(&"SSE2".to_string()));
220        assert!(result.contains(&"AVX".to_string()));
221        assert!(result.contains(&"AVX2".to_string()));
222    }
223}