Skip to main content

eggpack_core/
floor.rs

1//! Compatibility-floor verification status and bounded ELF version-requirement inspection.
2//!
3//! The compatibility floor is producer policy. This module owns the finite
4//! status model that says what was actually done with a declared floor, and
5//! the bounded reader that computes the highest `GLIBC_x.y` symbol version a
6//! produced ELF requires.
7//!
8//! Two rules bound everything here:
9//!
10//! - native execution is never floor proof (ADR-0005 ยง9), so the status is
11//!   computed from the produced bytes or from the toolchain binding, never
12//!   from a smoke run;
13//! - the inspection is read-only, bounded at every table and offset, and
14//!   fails closed: an unreadable, malformed, truncated, or over-large
15//!   candidate is never `Verified`.
16
17use crate::{BuildStrategy, CompatibilityFloor, TargetPolicy};
18use serde::{Deserialize, Serialize};
19use std::fs::File;
20use std::io::{Read, Seek, SeekFrom};
21use std::path::Path;
22
23/// Why a declared compatibility floor could not be independently verified.
24///
25/// The reason set is closed: it is a bounded enumeration, never a free-form
26/// string, so a recorded status always says exactly why a declared floor is
27/// not independently confirmed.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum FloorUnverifiedReason {
31    /// The floor is declared and awaits independent inspection of the produced bytes.
32    ///
33    /// This is the plan-time disposition of a declared floor that the build
34    /// toolchain cannot bind: the bytes have not been inspected yet.
35    PendingInspection,
36    /// The candidate is not an ELF image, or its bytes could not be read.
37    UnreadableCandidate,
38    /// The candidate is a truncated, malformed, or over-large ELF image.
39    MalformedCandidate,
40    /// The inspected candidate declares no glibc symbol version requirement.
41    ///
42    /// Such a candidate is compatible with any declared floor, but it does not
43    /// *confirm* a floor, so it is recorded specifically rather than as a
44    /// generic pass.
45    NoVersionRequirement,
46    /// The candidate carries a glibc version requirement that is not a plain
47    /// numeric version, so it cannot be compared against the declared floor.
48    UnrecognizedVersionRequirement,
49    /// The declared floor kind has no independent byte-level verification.
50    ///
51    /// A macOS deployment floor would be read from the Mach-O `minos` field,
52    /// which this milestone does not implement.
53    FloorKindNotVerifiable,
54}
55
56/// The verification status of a declared compatibility floor.
57///
58/// This is the **single** producer-side floor status model. It is finite and
59/// closed: it is neither a free-form string nor an `Option<bool>`, and every
60/// variant maps to one concrete observation about the produced bytes or about
61/// the toolchain that produced them.
62///
63/// | Status | Concrete observation |
64/// |---|---|
65/// | `NotDeclared` | the target declares `CompatibilityFloor::None` |
66/// | `ToolchainBound` | the floor was bound into the build toolchain by the cargo-zigbuild triple rewrite, and the toolchain is trusted to honour it |
67/// | `Verified` | the produced bytes were independently inspected and their highest required `GLIBC_x.y` version is not newer than the declared floor |
68/// | `Unverified(reason)` | a floor was declared and the produced bytes did not confirm it, for the bounded reason given |
69/// | `NotSatisfied` | the produced bytes were independently inspected and require a newer runtime than the declared floor |
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "snake_case")]
72pub enum FloorVerificationStatus {
73    /// The target declares `CompatibilityFloor::None`.
74    NotDeclared,
75    /// The floor was bound into the build toolchain and the toolchain is
76    /// trusted to honour it.
77    ToolchainBound,
78    /// The produced bytes were independently inspected and satisfy the declared floor.
79    Verified,
80    /// A floor was declared but could not be independently verified.
81    Unverified(FloorUnverifiedReason),
82    /// The produced bytes contradict the declared floor: they require a newer
83    /// runtime than the floor declares.
84    ///
85    /// This is never reported as `Unverified`: a declared floor that the bytes
86    /// disprove is false, so it fails the qualification for that target.
87    NotSatisfied,
88}
89
90impl Default for FloorVerificationStatus {
91    /// A document that omits the status is read as `NotDeclared`.
92    ///
93    /// The omission is then refused for any target that declares a floor, so
94    /// a missing status fails closed instead of defaulting to a claim.
95    fn default() -> Self {
96        FloorVerificationStatus::NotDeclared
97    }
98}
99
100/// The floor verification status a plan states for its declared floor.
101///
102/// The status is a pure function of the policy, so it is deterministic and
103/// cannot be chosen by a caller: a plan either states the status its policy
104/// implies or it is rejected.
105pub fn planned_floor_status(policy: &TargetPolicy) -> FloorVerificationStatus {
106    match policy.floor {
107        CompatibilityFloor::None => FloorVerificationStatus::NotDeclared,
108        CompatibilityFloor::Glibc { .. } => match policy.strategy {
109            // The cargo-zigbuild triple rewrite binds the floor into the
110            // toolchain; the toolchain is trusted to honour it.
111            BuildStrategy::CargoZigbuild => FloorVerificationStatus::ToolchainBound,
112            // A native build cannot bind the floor into the toolchain, so the
113            // floor is only ever confirmed by inspecting the produced bytes.
114            BuildStrategy::NativeCargo => {
115                FloorVerificationStatus::Unverified(FloorUnverifiedReason::PendingInspection)
116            }
117        },
118        // A macOS deployment floor is read from the Mach-O `minos` field,
119        // which this milestone does not implement.
120        CompatibilityFloor::Macos { .. } => {
121            FloorVerificationStatus::Unverified(FloorUnverifiedReason::FloorKindNotVerifiable)
122        }
123    }
124}
125
126/// Whether a floor verification status is admissible for a declared floor and
127/// build strategy.
128///
129/// This is the cross-check that keeps a status from claiming more than the
130/// declaration allows: a target without a declared floor can only be
131/// `NotDeclared`, a toolchain-bound floor can only be `ToolchainBound`, and
132/// only an independently inspected floor can be `Verified` or `NotSatisfied`.
133pub fn floor_status_admissible(
134    floor: &CompatibilityFloor,
135    strategy: BuildStrategy,
136    status: FloorVerificationStatus,
137) -> bool {
138    match (floor, strategy) {
139        (CompatibilityFloor::None, _) => status == FloorVerificationStatus::NotDeclared,
140        (CompatibilityFloor::Glibc { .. }, BuildStrategy::CargoZigbuild) => {
141            status == FloorVerificationStatus::ToolchainBound
142        }
143        (CompatibilityFloor::Glibc { .. }, BuildStrategy::NativeCargo) => matches!(
144            status,
145            FloorVerificationStatus::Verified
146                | FloorVerificationStatus::Unverified(_)
147                | FloorVerificationStatus::NotSatisfied
148        ),
149        (CompatibilityFloor::Macos { .. }, _) => {
150            matches!(status, FloorVerificationStatus::Unverified(_))
151        }
152    }
153}
154
155/// The largest ELF header window read from one candidate.
156const MAX_ELF_HEADER: usize = 64;
157/// The largest number of ELF program headers read from one candidate.
158const MAX_ELF_PROGRAM_HEADERS: usize = 256;
159/// The largest number of dynamic entries read from one candidate.
160const MAX_ELF_DYNAMIC_ENTRIES: usize = 1024;
161/// The largest number of version-requirement entries read from one candidate.
162const MAX_ELF_VERSION_REQUIREMENTS: usize = 256;
163/// The largest number of auxiliary version entries read for one requirement.
164const MAX_ELF_VERSION_AUXILIARIES: usize = 256;
165/// The largest version name read from the dynamic string table.
166const MAX_ELF_VERSION_NAME: usize = 64;
167
168/// The `PT_LOAD` program header type.
169const PT_LOAD: u32 = 1;
170/// The `PT_DYNAMIC` program header type.
171const PT_DYNAMIC: u32 = 2;
172/// The dynamic tag that terminates the dynamic table.
173const DT_NULL: u64 = 0;
174/// The dynamic tag holding the address of the dynamic string table.
175const DT_STRTAB: u64 = 5;
176/// The dynamic tag holding the address of the version-requirement table.
177const DT_VERNEED: u64 = 0x6ffffffe;
178/// The dynamic tag holding the number of version-requirement entries.
179const DT_VERNEEDNUM: u64 = 0x6fffffff;
180
181/// Why the version-requirement reader could not determine a requirement.
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183enum FloorReadError {
184    /// The candidate is not an ELF image.
185    NotAnElf,
186    /// The candidate bytes could not be read.
187    Unreadable,
188    /// The candidate is truncated or structurally malformed.
189    Malformed,
190    /// The candidate exceeds a declared parsing bound.
191    BoundExceeded,
192}
193
194/// A glibc symbol version requirement, compared component by component.
195///
196/// The patch component is zero for a two-component version: `GLIBC_2.17` is
197/// `2.17.0`, and `GLIBC_2.2.5` is `2.2.5`, which is newer than `2.2.0` and
198/// older than `2.17.0`.
199#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
200struct GlibcVersion {
201    /// Major version.
202    major: u16,
203    /// Minor version.
204    minor: u16,
205    /// Patch version.
206    patch: u16,
207}
208
209/// The parsed ELF header fields this reader needs.
210struct ElfHeader {
211    /// Whether the image is a 64-bit ELF.
212    class64: bool,
213    /// Whether the image stores integers little-endian.
214    little_endian: bool,
215    /// File offset of the program header table.
216    program_header_offset: u64,
217    /// Size of one program header entry.
218    program_header_size: u16,
219    /// Number of program header entries.
220    program_header_count: u16,
221}
222
223/// One program header segment.
224struct ProgramSegment {
225    /// Segment type.
226    kind: u32,
227    /// File offset of the segment.
228    offset: u64,
229    /// Virtual address of the segment.
230    vaddr: u64,
231    /// Number of file-backed bytes in the segment.
232    filesz: u64,
233}
234
235/// Read exactly `buffer.len()` bytes at `offset`.
236///
237/// Every read in this module is exact-length and every offset is checked
238/// against the file length before the read happens.
239fn read_exact_at(file: &mut File, offset: u64, buffer: &mut [u8]) -> Result<(), FloorReadError> {
240    file.seek(SeekFrom::Start(offset))
241        .map_err(|_| FloorReadError::Unreadable)?;
242    match file.read_exact(buffer) {
243        Ok(()) => Ok(()),
244        Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => {
245            Err(FloorReadError::Malformed)
246        }
247        Err(_) => Err(FloorReadError::Unreadable),
248    }
249}
250
251/// Read a `u16` from a fixed-width buffer.
252fn u16_at(bytes: &[u8], offset: usize, little_endian: bool) -> u16 {
253    let raw = [bytes[offset], bytes[offset + 1]];
254    if little_endian {
255        u16::from_le_bytes(raw)
256    } else {
257        u16::from_be_bytes(raw)
258    }
259}
260
261/// Read a `u32` from a fixed-width buffer.
262fn u32_at(bytes: &[u8], offset: usize, little_endian: bool) -> u32 {
263    let raw = [
264        bytes[offset],
265        bytes[offset + 1],
266        bytes[offset + 2],
267        bytes[offset + 3],
268    ];
269    if little_endian {
270        u32::from_le_bytes(raw)
271    } else {
272        u32::from_be_bytes(raw)
273    }
274}
275
276/// Read a `u64` from a fixed-width buffer.
277fn u64_at(bytes: &[u8], offset: usize, little_endian: bool) -> u64 {
278    let mut raw = [0u8; 8];
279    raw.copy_from_slice(&bytes[offset..offset + 8]);
280    if little_endian {
281        u64::from_le_bytes(raw)
282    } else {
283        u64::from_be_bytes(raw)
284    }
285}
286
287/// Parse the ELF header of one candidate.
288fn parse_elf_header(file: &mut File, length: u64) -> Result<ElfHeader, FloorReadError> {
289    let mut header = [0u8; MAX_ELF_HEADER];
290    let wanted = length.min(MAX_ELF_HEADER as u64) as usize;
291    file.read_exact(&mut header[..wanted])
292        .map_err(|_| FloorReadError::Malformed)?;
293    if wanted < 6 {
294        return Err(FloorReadError::Malformed);
295    }
296    if &header[..4] != b"\x7fELF" {
297        return Err(FloorReadError::NotAnElf);
298    }
299    let class64 = match header[4] {
300        1 => false,
301        2 => true,
302        _ => return Err(FloorReadError::Malformed),
303    };
304    let little_endian = match header[5] {
305        1 => true,
306        2 => false,
307        _ => return Err(FloorReadError::Malformed),
308    };
309    // The header must be complete for the class it claims.
310    let minimum = if class64 { 64 } else { 52 };
311    if length < minimum as u64 || wanted < minimum {
312        return Err(FloorReadError::Malformed);
313    }
314    let (program_header_offset, program_header_size, program_header_count) = if class64 {
315        (
316            u64_at(&header, 32, little_endian),
317            u16_at(&header, 54, little_endian),
318            u16_at(&header, 56, little_endian),
319        )
320    } else {
321        (
322            u32_at(&header, 28, little_endian) as u64,
323            u16_at(&header, 42, little_endian),
324            u16_at(&header, 44, little_endian),
325        )
326    };
327    Ok(ElfHeader {
328        class64,
329        little_endian,
330        program_header_offset,
331        program_header_size,
332        program_header_count,
333    })
334}
335
336/// Read the bounded program header table of one candidate.
337fn read_program_segments(
338    file: &mut File,
339    header: &ElfHeader,
340    length: u64,
341) -> Result<Vec<ProgramSegment>, FloorReadError> {
342    if header.program_header_count == 0 {
343        return Ok(Vec::new());
344    }
345    // `0xffff` marks the extended numbering scheme, which this reader does not
346    // implement; the real count lives in the section header table.
347    if header.program_header_count == 0xffff {
348        return Err(FloorReadError::Malformed);
349    }
350    if header.program_header_count as usize > MAX_ELF_PROGRAM_HEADERS {
351        return Err(FloorReadError::BoundExceeded);
352    }
353    let expected_size = if header.class64 { 56 } else { 32 };
354    if header.program_header_size != expected_size {
355        return Err(FloorReadError::Malformed);
356    }
357    let count = header.program_header_count as u64;
358    let table_end = count
359        .checked_mul(header.program_header_size as u64)
360        .and_then(|bytes| header.program_header_offset.checked_add(bytes))
361        .ok_or(FloorReadError::Malformed)?;
362    if table_end > length {
363        return Err(FloorReadError::Malformed);
364    }
365    let mut segments = Vec::with_capacity(count as usize);
366    for index in 0..count {
367        let offset = header.program_header_offset + index * header.program_header_size as u64;
368        let mut buffer = [0u8; 56];
369        read_exact_at(file, offset, &mut buffer[..expected_size as usize])?;
370        let segment = if header.class64 {
371            ProgramSegment {
372                kind: u32_at(&buffer, 0, header.little_endian),
373                offset: u64_at(&buffer, 8, header.little_endian),
374                vaddr: u64_at(&buffer, 16, header.little_endian),
375                filesz: u64_at(&buffer, 32, header.little_endian),
376            }
377        } else {
378            ProgramSegment {
379                kind: u32_at(&buffer, 0, header.little_endian),
380                offset: u32_at(&buffer, 4, header.little_endian) as u64,
381                vaddr: u32_at(&buffer, 8, header.little_endian) as u64,
382                filesz: u32_at(&buffer, 16, header.little_endian) as u64,
383            }
384        };
385        segments.push(segment);
386    }
387    Ok(segments)
388}
389
390/// Read the bounded dynamic table of one candidate.
391///
392/// Returns the `(tag, value)` pairs in table order, stopping at the
393/// terminating `DT_NULL` entry.
394fn read_dynamic_entries(
395    file: &mut File,
396    header: &ElfHeader,
397    dynamic: &ProgramSegment,
398    length: u64,
399) -> Result<Vec<(u64, u64)>, FloorReadError> {
400    let entry_size = if header.class64 { 16 } else { 8 };
401    let count = dynamic.filesz / entry_size as u64;
402    if count > MAX_ELF_DYNAMIC_ENTRIES as u64 {
403        return Err(FloorReadError::BoundExceeded);
404    }
405    let table_bytes = count * entry_size as u64;
406    let table_end = dynamic
407        .offset
408        .checked_add(table_bytes)
409        .ok_or(FloorReadError::Malformed)?;
410    if table_end > length {
411        return Err(FloorReadError::Malformed);
412    }
413    let mut buffer = vec![0u8; table_bytes as usize];
414    read_exact_at(file, dynamic.offset, &mut buffer)?;
415    let mut entries = Vec::new();
416    for index in 0..count as usize {
417        let base = index * entry_size;
418        let (tag, value) = if header.class64 {
419            (
420                u64_at(&buffer, base, header.little_endian),
421                u64_at(&buffer, base + 8, header.little_endian),
422            )
423        } else {
424            (
425                u32_at(&buffer, base, header.little_endian) as u64,
426                u32_at(&buffer, base + 4, header.little_endian) as u64,
427            )
428        };
429        if tag == DT_NULL {
430            break;
431        }
432        entries.push((tag, value));
433    }
434    Ok(entries)
435}
436
437/// Map a virtual address to a file offset through the loadable segments.
438fn map_vaddr(segments: &[ProgramSegment], vaddr: u64) -> Result<u64, FloorReadError> {
439    for segment in segments.iter().filter(|segment| segment.kind == PT_LOAD) {
440        let end = segment
441            .vaddr
442            .checked_add(segment.filesz)
443            .ok_or(FloorReadError::Malformed)?;
444        if vaddr >= segment.vaddr && vaddr < end {
445            // The segment offset comes from the ELF program header and is not
446            // bounded against the file length here, so the translation back
447            // into the file is overflow-checked like every other offset
448            // computation in this module.
449            return segment
450                .offset
451                .checked_add(vaddr - segment.vaddr)
452                .ok_or(FloorReadError::Malformed);
453        }
454    }
455    Err(FloorReadError::Malformed)
456}
457
458/// Read one bounded version name from the dynamic string table.
459fn read_version_name(
460    file: &mut File,
461    strtab_offset: u64,
462    name_offset: u64,
463    length: u64,
464) -> Result<String, FloorReadError> {
465    let start = strtab_offset
466        .checked_add(name_offset)
467        .ok_or(FloorReadError::Malformed)?;
468    if start >= length {
469        return Err(FloorReadError::Malformed);
470    }
471    // The name is read within the file, never past its end, and never for
472    // more than the declared name bound.
473    let available = (length - start).min(MAX_ELF_VERSION_NAME as u64) as usize;
474    let mut buffer = [0u8; MAX_ELF_VERSION_NAME];
475    read_exact_at(file, start, &mut buffer[..available])?;
476    let end = buffer[..available]
477        .iter()
478        .position(|byte| *byte == 0)
479        .ok_or(FloorReadError::Malformed)?;
480    Ok(String::from_utf8_lossy(&buffer[..end]).into_owned())
481}
482
483/// How one symbol version name classifies against a glibc floor.
484#[derive(Debug, Clone, Copy, PartialEq, Eq)]
485enum GlibcVersionName {
486    /// Not a glibc requirement at all: the name carries no `GLIBC_` prefix.
487    NotGlibc,
488    /// A numeric glibc version requirement, comparable against a floor.
489    Numeric(GlibcVersion),
490    /// A `GLIBC_`-prefixed name that is not a plain numeric version.
491    ///
492    /// `GLIBC_PRIVATE` and `GLIBC_ABI_DT_RELR` are real and common. Such a
493    /// name cannot be compared against a declared floor, but it does not
494    /// invalidate the *other* requirements in the same image, so it is
495    /// reported rather than treated as a reason to abandon the scan.
496    Unrecognized,
497}
498
499/// Parse a symbol version name into a glibc version requirement.
500///
501/// A name that does not start with `GLIBC_` is not a glibc requirement. A
502/// `GLIBC_` name that is not a plain numeric version cannot be compared
503/// against a declared floor, so it is classified as
504/// [`GlibcVersionName::Unrecognized`] rather than ignored โ€” and, critically,
505/// rather than aborting the scan and discarding every other requirement the
506/// image carries.
507fn parse_glibc_version(name: &str) -> GlibcVersionName {
508    let Some(rest) = name.strip_prefix("GLIBC_") else {
509        return GlibcVersionName::NotGlibc;
510    };
511    let parts: Vec<&str> = rest.split('.').collect();
512    if parts.len() < 2 || parts.len() > 3 {
513        return GlibcVersionName::Unrecognized;
514    }
515    let mut numbers = [0u16; 3];
516    for (index, part) in parts.iter().enumerate() {
517        if part.is_empty() || part.len() > 5 || !part.bytes().all(|byte| byte.is_ascii_digit()) {
518            return GlibcVersionName::Unrecognized;
519        }
520        let Ok(number) = part.parse::<u16>() else {
521            return GlibcVersionName::Unrecognized;
522        };
523        numbers[index] = number;
524    }
525    GlibcVersionName::Numeric(GlibcVersion {
526        major: numbers[0],
527        minor: numbers[1],
528        patch: numbers[2],
529    })
530}
531
532/// The glibc version requirements observed in one ELF candidate.
533#[derive(Debug, Clone, Copy, PartialEq, Eq)]
534struct GlibcRequirements {
535    /// The highest numeric version requirement observed, if any.
536    highest: Option<GlibcVersion>,
537    /// Whether a `GLIBC_`-prefixed name was observed that is not a plain
538    /// numeric version.
539    ///
540    /// Such a name cannot be compared against a declared floor, so the floor
541    /// cannot be *verified* from this image. It does not contradict the floor
542    /// either, and it must not suppress the numeric requirements observed
543    /// alongside it.
544    unrecognized: bool,
545}
546
547/// Read the glibc version requirements of one ELF candidate.
548///
549/// The scan visits **every** requirement in the image. A `GLIBC_`-prefixed
550/// name that is not a plain numeric version is recorded as unrecognized and
551/// the scan continues, because abandoning it at the first such name would
552/// discard every other requirement the image carries โ€” including one that
553/// contradicts the declared floor.
554fn read_glibc_requirement(path: &Path) -> Result<GlibcRequirements, FloorReadError> {
555    let mut file = File::open(path).map_err(|_| FloorReadError::Unreadable)?;
556    let length = file
557        .metadata()
558        .map_err(|_| FloorReadError::Unreadable)?
559        .len();
560    let header = parse_elf_header(&mut file, length)?;
561    let segments = read_program_segments(&mut file, &header, length)?;
562    let Some(dynamic) = segments.iter().find(|segment| segment.kind == PT_DYNAMIC) else {
563        return Ok(GlibcRequirements {
564            highest: None,
565            unrecognized: false,
566        });
567    };
568    let entries = read_dynamic_entries(&mut file, &header, dynamic, length)?;
569    let find = |tag: u64| {
570        entries
571            .iter()
572            .find(|(entry, _)| *entry == tag)
573            .map(|(_, value)| *value)
574    };
575    let Some(verneed_vaddr) = find(DT_VERNEED) else {
576        return Ok(GlibcRequirements {
577            highest: None,
578            unrecognized: false,
579        });
580    };
581    let strtab_vaddr = find(DT_STRTAB).ok_or(FloorReadError::Malformed)?;
582    let requirement_count = find(DT_VERNEEDNUM);
583    if requirement_count.is_some_and(|count| count > MAX_ELF_VERSION_REQUIREMENTS as u64) {
584        return Err(FloorReadError::BoundExceeded);
585    }
586    let strtab_offset = map_vaddr(&segments, strtab_vaddr)?;
587    let verneed_offset = map_vaddr(&segments, verneed_vaddr)?;
588    if verneed_offset >= length {
589        return Err(FloorReadError::Malformed);
590    }
591
592    let mut highest: Option<GlibcVersion> = None;
593    let mut unrecognized = false;
594    let mut requirement_offset = verneed_offset;
595    let mut requirements = 0usize;
596    loop {
597        if requirements >= MAX_ELF_VERSION_REQUIREMENTS {
598            return Err(FloorReadError::BoundExceeded);
599        }
600        let mut requirement = [0u8; 16];
601        read_exact_at(&mut file, requirement_offset, &mut requirement)?;
602        let auxiliary_count = u16_at(&requirement, 2, header.little_endian);
603        let auxiliary_offset = u32_at(&requirement, 8, header.little_endian) as u64;
604        let next_requirement = u32_at(&requirement, 12, header.little_endian) as u64;
605        let mut auxiliary_offset = requirement_offset
606            .checked_add(auxiliary_offset)
607            .ok_or(FloorReadError::Malformed)?;
608        for index in 0..auxiliary_count as usize {
609            if index >= MAX_ELF_VERSION_AUXILIARIES {
610                return Err(FloorReadError::BoundExceeded);
611            }
612            let mut auxiliary = [0u8; 16];
613            read_exact_at(&mut file, auxiliary_offset, &mut auxiliary)?;
614            let name_offset = u32_at(&auxiliary, 8, header.little_endian) as u64;
615            let next_auxiliary = u32_at(&auxiliary, 12, header.little_endian) as u64;
616            let name = read_version_name(&mut file, strtab_offset, name_offset, length)?;
617            // Every requirement is visited. An unrecognized name is recorded
618            // and the scan continues, so a requirement observed alongside it
619            // still reaches the comparison.
620            match parse_glibc_version(&name) {
621                GlibcVersionName::Numeric(version) => {
622                    if highest.is_none_or(|current| version > current) {
623                        highest = Some(version);
624                    }
625                }
626                GlibcVersionName::Unrecognized => unrecognized = true,
627                GlibcVersionName::NotGlibc => {}
628            }
629            if next_auxiliary == 0 {
630                break;
631            }
632            auxiliary_offset = auxiliary_offset
633                .checked_add(next_auxiliary)
634                .ok_or(FloorReadError::Malformed)?;
635        }
636        if next_requirement == 0 {
637            break;
638        }
639        requirement_offset = requirement_offset
640            .checked_add(next_requirement)
641            .ok_or(FloorReadError::Malformed)?;
642        requirements += 1;
643    }
644    Ok(GlibcRequirements {
645        highest,
646        unrecognized,
647    })
648}
649
650/// Inspect one candidate's bytes and compute its floor verification status.
651///
652/// The inspection is read-only and holds no lock: two concurrent inspections
653/// of the same candidate observe the same bytes or report a changed-file
654/// error, and each observation is self-consistent.
655pub(crate) fn inspect_candidate_floor(
656    path: &Path,
657    floor: &CompatibilityFloor,
658    strategy: BuildStrategy,
659) -> FloorVerificationStatus {
660    match floor {
661        CompatibilityFloor::None => FloorVerificationStatus::NotDeclared,
662        CompatibilityFloor::Macos { .. } => {
663            FloorVerificationStatus::Unverified(FloorUnverifiedReason::FloorKindNotVerifiable)
664        }
665        CompatibilityFloor::Glibc { major, minor } => match strategy {
666            BuildStrategy::CargoZigbuild => FloorVerificationStatus::ToolchainBound,
667            BuildStrategy::NativeCargo => {
668                let declared = GlibcVersion {
669                    major: *major,
670                    minor: *minor,
671                    patch: 0,
672                };
673                match read_glibc_requirement(path) {
674                    // The comparison direction is the point: a binary that
675                    // requires a *newer* glibc than declared does not satisfy
676                    // the declared floor.
677                    //
678                    // A contradiction is decided **first** and is not
679                    // downgraded by an unrecognized name observed alongside
680                    // it: a declared floor that the bytes contradict is a
681                    // hard failure, never an unverified status.
682                    Ok(requirements) => {
683                        if let Some(required) = requirements.highest {
684                            if required > declared {
685                                FloorVerificationStatus::NotSatisfied
686                            } else if requirements.unrecognized {
687                                // The numeric requirements are compatible with
688                                // the declared floor, but one requirement could
689                                // not be compared, so the floor is not proven.
690                                FloorVerificationStatus::Unverified(
691                                    FloorUnverifiedReason::UnrecognizedVersionRequirement,
692                                )
693                            } else {
694                                FloorVerificationStatus::Verified
695                            }
696                        } else if requirements.unrecognized {
697                            FloorVerificationStatus::Unverified(
698                                FloorUnverifiedReason::UnrecognizedVersionRequirement,
699                            )
700                        } else {
701                            FloorVerificationStatus::Unverified(
702                                FloorUnverifiedReason::NoVersionRequirement,
703                            )
704                        }
705                    }
706                    Err(FloorReadError::NotAnElf | FloorReadError::Unreadable) => {
707                        FloorVerificationStatus::Unverified(
708                            FloorUnverifiedReason::UnreadableCandidate,
709                        )
710                    }
711                    Err(FloorReadError::Malformed | FloorReadError::BoundExceeded) => {
712                        FloorVerificationStatus::Unverified(
713                            FloorUnverifiedReason::MalformedCandidate,
714                        )
715                    }
716                }
717            }
718        },
719    }
720}
721
722/// The severity of an unverified reason, used to combine candidate results.
723fn reason_rank(reason: FloorUnverifiedReason) -> u8 {
724    match reason {
725        FloorUnverifiedReason::UnreadableCandidate => 5,
726        FloorUnverifiedReason::MalformedCandidate => 4,
727        FloorUnverifiedReason::UnrecognizedVersionRequirement => 3,
728        FloorUnverifiedReason::NoVersionRequirement => 2,
729        FloorUnverifiedReason::FloorKindNotVerifiable => 1,
730        FloorUnverifiedReason::PendingInspection => 0,
731    }
732}
733
734/// The severity of a floor status, used to combine candidate results.
735fn status_rank(status: FloorVerificationStatus) -> (u8, u8) {
736    match status {
737        FloorVerificationStatus::NotSatisfied => (5, 0),
738        FloorVerificationStatus::Unverified(reason) => (4, reason_rank(reason)),
739        FloorVerificationStatus::Verified => (3, 0),
740        FloorVerificationStatus::ToolchainBound => (2, 0),
741        FloorVerificationStatus::NotDeclared => (1, 0),
742    }
743}
744
745/// Combine the per-candidate floor statuses of one target into one status.
746///
747/// The combination is deterministic and conservative: a contradiction
748/// dominates, an unverified reason dominates a positive claim, and the most
749/// severe reason wins among unverified candidates.
750pub(crate) fn aggregate_floor_status(
751    statuses: &[FloorVerificationStatus],
752) -> FloorVerificationStatus {
753    let mut combined: Option<FloorVerificationStatus> = None;
754    for status in statuses {
755        combined = Some(match combined {
756            None => *status,
757            Some(current) => {
758                if status_rank(*status) > status_rank(current) {
759                    *status
760                } else {
761                    current
762                }
763            }
764        });
765    }
766    combined.unwrap_or(FloorVerificationStatus::Unverified(
767        FloorUnverifiedReason::UnreadableCandidate,
768    ))
769}
770
771#[cfg(test)]
772pub(crate) mod test_support {
773    use super::{DT_NULL, DT_STRTAB, DT_VERNEED, DT_VERNEEDNUM};
774
775    /// Builds minimal ELF images that carry symbol version requirements.
776    ///
777    /// The image is deliberately small and hand-built: one `PT_LOAD` segment
778    /// that maps the whole file, one `PT_DYNAMIC` segment, a dynamic table,
779    /// a version-requirement table, and a string table.
780    pub(crate) struct ElfBuilder {
781        class64: bool,
782        little_endian: bool,
783        versions: Vec<String>,
784        program_header_count: Option<u16>,
785        dynamic_filesz: Option<u64>,
786        program_header_offset: Option<u64>,
787    }
788
789    impl ElfBuilder {
790        /// Start a new image for the given ELF class and byte order.
791        pub(crate) fn new(class64: bool, little_endian: bool) -> Self {
792            Self {
793                class64,
794                little_endian,
795                versions: Vec::new(),
796                program_header_count: None,
797                dynamic_filesz: None,
798                program_header_offset: None,
799            }
800        }
801
802        /// Set the version names carried by the version-requirement table.
803        pub(crate) fn versions(mut self, versions: &[&str]) -> Self {
804            self.versions = versions.iter().map(|value| (*value).to_owned()).collect();
805            self
806        }
807
808        /// Override the declared program header count.
809        pub(crate) fn program_header_count(mut self, count: u16) -> Self {
810            self.program_header_count = Some(count);
811            self
812        }
813
814        /// Override the declared size of the dynamic segment.
815        pub(crate) fn dynamic_filesz(mut self, filesz: u64) -> Self {
816            self.dynamic_filesz = Some(filesz);
817            self
818        }
819
820        /// Override the declared program header table offset.
821        pub(crate) fn program_header_offset(mut self, offset: u64) -> Self {
822            self.program_header_offset = Some(offset);
823            self
824        }
825
826        fn put_u16(&self, bytes: &mut [u8], offset: usize, value: u16) {
827            let raw = if self.little_endian {
828                value.to_le_bytes()
829            } else {
830                value.to_be_bytes()
831            };
832            bytes[offset..offset + 2].copy_from_slice(&raw);
833        }
834
835        fn put_u32(&self, bytes: &mut [u8], offset: usize, value: u32) {
836            let raw = if self.little_endian {
837                value.to_le_bytes()
838            } else {
839                value.to_be_bytes()
840            };
841            bytes[offset..offset + 4].copy_from_slice(&raw);
842        }
843
844        fn put_u64(&self, bytes: &mut [u8], offset: usize, value: u64) {
845            let raw = if self.little_endian {
846                value.to_le_bytes()
847            } else {
848                value.to_be_bytes()
849            };
850            bytes[offset..offset + 8].copy_from_slice(&raw);
851        }
852
853        /// Build the image bytes.
854        pub(crate) fn build(self) -> Vec<u8> {
855            let header_size = if self.class64 { 64 } else { 52 };
856            let program_header_size = if self.class64 { 56 } else { 32 };
857            let dynamic_entry_size = if self.class64 { 16 } else { 8 };
858            let dynamic_entries = if self.versions.is_empty() { 2 } else { 4 };
859
860            let mut bytes = vec![0u8; header_size];
861            bytes.resize(bytes.len() + 2 * program_header_size, 0);
862            let dynamic_offset = bytes.len() as u64;
863            bytes.resize(bytes.len() + dynamic_entries * dynamic_entry_size, 0);
864            let verneed_offset = bytes.len() as u64;
865            let verneed_size = if self.versions.is_empty() {
866                0
867            } else {
868                16 * (1 + self.versions.len())
869            };
870            bytes.resize(bytes.len() + verneed_size, 0);
871            let strtab_offset = bytes.len() as u64;
872
873            let mut string_table = Vec::new();
874            let mut name_offsets = Vec::new();
875            for version in &self.versions {
876                name_offsets.push(string_table.len() as u32);
877                string_table.extend_from_slice(version.as_bytes());
878                string_table.push(0);
879            }
880            bytes.extend_from_slice(&string_table);
881            let total = bytes.len() as u64;
882
883            // ELF identification.
884            bytes[..4].copy_from_slice(b"\x7fELF");
885            bytes[4] = if self.class64 { 2 } else { 1 };
886            bytes[5] = if self.little_endian { 1 } else { 2 };
887            bytes[6] = 1;
888            self.put_u16(&mut bytes, 16, 2); // e_type: ET_EXEC
889            self.put_u16(&mut bytes, 18, if self.class64 { 62 } else { 40 }); // e_machine
890            self.put_u32(&mut bytes, 20, 1); // e_version
891            let program_header_offset = self.program_header_offset.unwrap_or(header_size as u64);
892            if self.class64 {
893                self.put_u64(&mut bytes, 32, program_header_offset);
894                self.put_u16(&mut bytes, 52, header_size as u16);
895                self.put_u16(&mut bytes, 54, program_header_size as u16);
896                self.put_u16(&mut bytes, 56, self.program_header_count.unwrap_or(2));
897            } else {
898                self.put_u32(&mut bytes, 28, program_header_offset as u32);
899                self.put_u16(&mut bytes, 40, header_size as u16);
900                self.put_u16(&mut bytes, 42, program_header_size as u16);
901                self.put_u16(&mut bytes, 44, self.program_header_count.unwrap_or(2));
902            }
903
904            // Program headers: one loadable segment and one dynamic segment.
905            let first = header_size;
906            let second = header_size + program_header_size;
907            let put_segment = |bytes: &mut Vec<u8>,
908                               at: usize,
909                               kind: u32,
910                               offset: u64,
911                               vaddr: u64,
912                               filesz: u64| {
913                if self.class64 {
914                    self.put_u32(bytes, at, kind);
915                    self.put_u32(bytes, at + 4, 4);
916                    self.put_u64(bytes, at + 8, offset);
917                    self.put_u64(bytes, at + 16, vaddr);
918                    self.put_u64(bytes, at + 24, vaddr);
919                    self.put_u64(bytes, at + 32, filesz);
920                    self.put_u64(bytes, at + 40, filesz);
921                    self.put_u64(bytes, at + 48, 0x1000);
922                } else {
923                    self.put_u32(bytes, at, kind);
924                    self.put_u32(bytes, at + 4, offset as u32);
925                    self.put_u32(bytes, at + 8, vaddr as u32);
926                    self.put_u32(bytes, at + 12, vaddr as u32);
927                    self.put_u32(bytes, at + 16, filesz as u32);
928                    self.put_u32(bytes, at + 20, filesz as u32);
929                    self.put_u32(bytes, at + 24, 4);
930                    self.put_u32(bytes, at + 28, 0x1000);
931                }
932            };
933            put_segment(&mut bytes, first, 1, 0, 0, total);
934            let dynamic_size = (dynamic_entries * dynamic_entry_size) as u64;
935            put_segment(
936                &mut bytes,
937                second,
938                2,
939                dynamic_offset,
940                dynamic_offset,
941                self.dynamic_filesz.unwrap_or(dynamic_size),
942            );
943
944            // Dynamic table.
945            let dynamic_base = dynamic_offset as usize;
946            let put_dynamic = |bytes: &mut Vec<u8>, index: usize, tag: u64, value: u64| {
947                let at = dynamic_base + index * dynamic_entry_size;
948                if self.class64 {
949                    self.put_u64(bytes, at, tag);
950                    self.put_u64(bytes, at + 8, value);
951                } else {
952                    self.put_u32(bytes, at, tag as u32);
953                    self.put_u32(bytes, at + 4, value as u32);
954                }
955            };
956            put_dynamic(&mut bytes, 0, DT_STRTAB, strtab_offset);
957            if self.versions.is_empty() {
958                put_dynamic(&mut bytes, 1, DT_NULL, 0);
959            } else {
960                put_dynamic(&mut bytes, 1, DT_VERNEED, verneed_offset);
961                put_dynamic(&mut bytes, 2, DT_VERNEEDNUM, 1);
962                put_dynamic(&mut bytes, 3, DT_NULL, 0);
963            }
964
965            // Version-requirement table: one requirement with one auxiliary
966            // entry per version name.
967            if !self.versions.is_empty() {
968                let base = verneed_offset as usize;
969                self.put_u16(&mut bytes, base, 1); // vn_version
970                self.put_u16(&mut bytes, base + 2, self.versions.len() as u16); // vn_cnt
971                self.put_u32(&mut bytes, base + 4, 0); // vn_file
972                self.put_u32(&mut bytes, base + 8, 16); // vn_aux
973                self.put_u32(&mut bytes, base + 12, 0); // vn_next
974                for (index, name_offset) in name_offsets.iter().enumerate() {
975                    let at = base + 16 + index * 16;
976                    self.put_u32(&mut bytes, at, 0); // vna_hash
977                    self.put_u16(&mut bytes, at + 4, 0); // vna_flags
978                    self.put_u16(&mut bytes, at + 6, (index + 1) as u16); // vna_other
979                    self.put_u32(&mut bytes, at + 8, *name_offset); // vna_name
980                                                                    // The auxiliary entries form a chain: each one points at
981                                                                    // the next, and the last one ends the chain.
982                    self.put_u32(
983                        &mut bytes,
984                        at + 12,
985                        if index + 1 < self.versions.len() {
986                            16
987                        } else {
988                            0
989                        },
990                    ); // vna_next
991                }
992            }
993            bytes
994        }
995    }
996}
997
998#[cfg(test)]
999mod tests {
1000    use super::test_support::ElfBuilder;
1001    use super::*;
1002    use crate::{
1003        BuildStrategy, CompatibilityFloor, HostArch, HostOs, Qualification, SupportTier,
1004        TargetPolicy, ToolchainRequirement,
1005    };
1006
1007    fn policy(floor: CompatibilityFloor, strategy: BuildStrategy) -> TargetPolicy {
1008        TargetPolicy {
1009            target: "x86_64-unknown-linux-gnu".into(),
1010            strategy,
1011            host_os: HostOs::Linux,
1012            host_arch: HostArch::X86_64,
1013            qualification_host: None,
1014            toolchain: ToolchainRequirement {
1015                rust: "1.89.0".into(),
1016                cargo_zigbuild: None,
1017                zig: None,
1018            },
1019            floor,
1020            qualification: Qualification::Native,
1021            support: SupportTier::Required,
1022        }
1023    }
1024
1025    fn glibc(major: u16, minor: u16) -> CompatibilityFloor {
1026        CompatibilityFloor::Glibc { major, minor }
1027    }
1028
1029    fn write(bytes: &[u8]) -> std::path::PathBuf {
1030        let root = crate::test_temp_dir("floor");
1031        let path = root.join("candidate");
1032        std::fs::write(&path, bytes).unwrap();
1033        path
1034    }
1035
1036    fn status_for(bytes: &[u8], floor: CompatibilityFloor) -> FloorVerificationStatus {
1037        let path = write(bytes);
1038        let status = inspect_candidate_floor(&path, &floor, BuildStrategy::NativeCargo);
1039        std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
1040        status
1041    }
1042
1043    #[test]
1044    fn reader_reports_the_highest_required_glibc_version() {
1045        let image = ElfBuilder::new(true, true)
1046            .versions(&["GLIBC_2.17", "GLIBC_2.34", "GLIBC_2.2.5"])
1047            .build();
1048        let path = write(&image);
1049        let required = read_glibc_requirement(&path).unwrap();
1050        assert_eq!(
1051            required.highest,
1052            Some(GlibcVersion {
1053                major: 2,
1054                minor: 34,
1055                patch: 0
1056            })
1057        );
1058        assert!(!required.unrecognized);
1059        std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
1060    }
1061
1062    #[test]
1063    fn reader_reports_no_requirement_when_the_image_has_none() {
1064        // No version-requirement table at all.
1065        let image = ElfBuilder::new(true, true).build();
1066        let path = write(&image);
1067        let required = read_glibc_requirement(&path).unwrap();
1068        assert_eq!(required.highest, None);
1069        assert!(!required.unrecognized);
1070        std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
1071        // A version requirement that is not a glibc requirement.
1072        let image = ElfBuilder::new(true, true)
1073            .versions(&["CXXABI_1.3"])
1074            .build();
1075        let path = write(&image);
1076        let required = read_glibc_requirement(&path).unwrap();
1077        assert_eq!(required.highest, None);
1078        assert!(!required.unrecognized);
1079        std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
1080    }
1081
1082    #[test]
1083    fn reader_reads_32_bit_and_big_endian_images() {
1084        let image = ElfBuilder::new(false, true)
1085            .versions(&["GLIBC_2.17"])
1086            .build();
1087        let path = write(&image);
1088        assert_eq!(
1089            read_glibc_requirement(&path).unwrap().highest,
1090            Some(GlibcVersion {
1091                major: 2,
1092                minor: 17,
1093                patch: 0
1094            })
1095        );
1096        std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
1097
1098        let image = ElfBuilder::new(true, false)
1099            .versions(&["GLIBC_2.17"])
1100            .build();
1101        let path = write(&image);
1102        assert_eq!(
1103            read_glibc_requirement(&path).unwrap().highest,
1104            Some(GlibcVersion {
1105                major: 2,
1106                minor: 17,
1107                patch: 0
1108            })
1109        );
1110        std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
1111    }
1112
1113    #[test]
1114    fn reader_refuses_truncated_malformed_and_non_elf_inputs() {
1115        // Not an ELF image at all.
1116        let path = write(b"this is not an elf image");
1117        assert_eq!(read_glibc_requirement(&path), Err(FloorReadError::NotAnElf));
1118        std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
1119
1120        // A truncated dynamic table.
1121        let image = ElfBuilder::new(true, true)
1122            .versions(&["GLIBC_2.17"])
1123            .build();
1124        let path = write(&image[..image.len() - 8]);
1125        assert!(read_glibc_requirement(&path).is_err());
1126        std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
1127
1128        // Truncated program headers.
1129        let image = ElfBuilder::new(true, true)
1130            .versions(&["GLIBC_2.17"])
1131            .build();
1132        let path = write(&image[..80]);
1133        assert!(read_glibc_requirement(&path).is_err());
1134        std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
1135
1136        // A program header table offset beyond the file.
1137        let image = ElfBuilder::new(true, true)
1138            .versions(&["GLIBC_2.17"])
1139            .program_header_offset(1 << 30)
1140            .build();
1141        let path = write(&image);
1142        assert!(read_glibc_requirement(&path).is_err());
1143        std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
1144    }
1145
1146    #[test]
1147    fn reader_refuses_oversized_tables_instead_of_parsing_them() {
1148        let image = ElfBuilder::new(true, true)
1149            .versions(&["GLIBC_2.17"])
1150            .program_header_count(4096)
1151            .build();
1152        let path = write(&image);
1153        assert_eq!(
1154            read_glibc_requirement(&path),
1155            Err(FloorReadError::BoundExceeded)
1156        );
1157        std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
1158
1159        let image = ElfBuilder::new(true, true)
1160            .versions(&["GLIBC_2.17"])
1161            .dynamic_filesz(1 << 20)
1162            .build();
1163        let path = write(&image);
1164        assert_eq!(
1165            read_glibc_requirement(&path),
1166            Err(FloorReadError::BoundExceeded)
1167        );
1168        std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
1169    }
1170
1171    #[test]
1172    fn comparison_direction_requires_the_newest_version_to_fit_under_the_floor() {
1173        let newer = ElfBuilder::new(true, true)
1174            .versions(&["GLIBC_2.34"])
1175            .build();
1176        let equal = ElfBuilder::new(true, true)
1177            .versions(&["GLIBC_2.17"])
1178            .build();
1179        let older = ElfBuilder::new(true, true)
1180            .versions(&["GLIBC_2.2.5"])
1181            .build();
1182        assert_eq!(
1183            status_for(&newer, glibc(2, 17)),
1184            FloorVerificationStatus::NotSatisfied
1185        );
1186        assert_eq!(
1187            status_for(&equal, glibc(2, 17)),
1188            FloorVerificationStatus::Verified
1189        );
1190        assert_eq!(
1191            status_for(&older, glibc(2, 17)),
1192            FloorVerificationStatus::Verified
1193        );
1194        // A binary that requires an older glibc satisfies a newer floor.
1195        assert_eq!(
1196            status_for(&older, glibc(2, 34)),
1197            FloorVerificationStatus::Verified
1198        );
1199        // A patch component is a real requirement: 2.2.5 is newer than 2.2.
1200        assert_eq!(
1201            status_for(&older, glibc(2, 2)),
1202            FloorVerificationStatus::NotSatisfied
1203        );
1204    }
1205
1206    #[test]
1207    fn an_image_without_a_version_requirement_is_recorded_specifically() {
1208        let image = ElfBuilder::new(true, true).build();
1209        assert_eq!(
1210            status_for(&image, glibc(2, 17)),
1211            FloorVerificationStatus::Unverified(FloorUnverifiedReason::NoVersionRequirement)
1212        );
1213    }
1214
1215    #[test]
1216    fn a_malformed_candidate_is_never_verified() {
1217        assert_eq!(
1218            status_for(b"not an elf", glibc(2, 17)),
1219            FloorVerificationStatus::Unverified(FloorUnverifiedReason::UnreadableCandidate)
1220        );
1221        let image = ElfBuilder::new(true, true)
1222            .versions(&["GLIBC_2.17"])
1223            .build();
1224        assert_eq!(
1225            status_for(&image[..image.len() - 8], glibc(2, 17)),
1226            FloorVerificationStatus::Unverified(FloorUnverifiedReason::MalformedCandidate)
1227        );
1228    }
1229
1230    #[test]
1231    fn an_unrecognized_version_name_is_never_verified() {
1232        let image = ElfBuilder::new(true, true)
1233            .versions(&["GLIBC_ABI_DT_RELR"])
1234            .build();
1235        assert_eq!(
1236            status_for(&image, glibc(2, 17)),
1237            FloorVerificationStatus::Unverified(
1238                FloorUnverifiedReason::UnrecognizedVersionRequirement
1239            )
1240        );
1241    }
1242
1243    #[test]
1244    fn an_unrecognized_version_name_does_not_mask_a_contradicted_floor() {
1245        // `GLIBC_PRIVATE` and `GLIBC_ABI_DT_RELR` are real, common version
1246        // names. A binary that requires a glibc newer than the declared floor
1247        // must fail closed even when it also carries such a name: the
1248        // unrecognized name is recorded, but it must not discard the numeric
1249        // requirement observed alongside it.
1250        for extra in ["GLIBC_PRIVATE", "GLIBC_ABI_DT_RELR"] {
1251            let image = ElfBuilder::new(true, true)
1252                .versions(&["GLIBC_2.34", extra])
1253                .build();
1254            assert_eq!(
1255                status_for(&image, glibc(2, 17)),
1256                FloorVerificationStatus::NotSatisfied,
1257                "{extra} must not mask the contradicted floor"
1258            );
1259            // The same image against a floor it does satisfy is unverified,
1260            // not verified: one requirement could not be compared.
1261            assert_eq!(
1262                status_for(&image, glibc(2, 34)),
1263                FloorVerificationStatus::Unverified(
1264                    FloorUnverifiedReason::UnrecognizedVersionRequirement
1265                )
1266            );
1267        }
1268        // An unrecognized name alone is still unverified, never verified.
1269        let image = ElfBuilder::new(true, true)
1270            .versions(&["GLIBC_PRIVATE"])
1271            .build();
1272        assert_eq!(
1273            status_for(&image, glibc(2, 17)),
1274            FloorVerificationStatus::Unverified(
1275                FloorUnverifiedReason::UnrecognizedVersionRequirement
1276            )
1277        );
1278    }
1279
1280    #[test]
1281    fn an_unrecognized_version_name_does_not_hide_a_numeric_requirement() {
1282        // The reader visits every requirement, so a numeric requirement that
1283        // appears *after* an unrecognized one is still observed.
1284        let image = ElfBuilder::new(true, true)
1285            .versions(&["GLIBC_PRIVATE", "GLIBC_2.34"])
1286            .build();
1287        let path = write(&image);
1288        let required = read_glibc_requirement(&path).unwrap();
1289        assert_eq!(
1290            required.highest,
1291            Some(GlibcVersion {
1292                major: 2,
1293                minor: 34,
1294                patch: 0
1295            })
1296        );
1297        assert!(required.unrecognized);
1298        std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
1299    }
1300
1301    #[test]
1302    fn a_virtual_address_translation_cannot_overflow() {
1303        // A crafted `PT_LOAD` whose file offset is near the top of the `u64`
1304        // range must not overflow when the virtual address is translated
1305        // back into the file. The segment offset comes from the ELF program
1306        // header and is not bounded against the file length.
1307        let segments = vec![ProgramSegment {
1308            kind: PT_LOAD,
1309            offset: u64::MAX - 10,
1310            vaddr: 0,
1311            filesz: 1024,
1312        }];
1313        assert_eq!(map_vaddr(&segments, 20), Err(FloorReadError::Malformed));
1314    }
1315
1316    #[test]
1317    fn the_plan_status_is_derived_from_the_policy() {
1318        assert_eq!(
1319            planned_floor_status(&policy(
1320                CompatibilityFloor::None,
1321                BuildStrategy::NativeCargo
1322            )),
1323            FloorVerificationStatus::NotDeclared
1324        );
1325        assert_eq!(
1326            planned_floor_status(&policy(glibc(2, 17), BuildStrategy::CargoZigbuild)),
1327            FloorVerificationStatus::ToolchainBound
1328        );
1329        assert_eq!(
1330            planned_floor_status(&policy(glibc(2, 17), BuildStrategy::NativeCargo)),
1331            FloorVerificationStatus::Unverified(FloorUnverifiedReason::PendingInspection)
1332        );
1333        assert_eq!(
1334            planned_floor_status(&policy(
1335                CompatibilityFloor::Macos {
1336                    major: 13,
1337                    minor: 0
1338                },
1339                BuildStrategy::NativeCargo
1340            )),
1341            FloorVerificationStatus::Unverified(FloorUnverifiedReason::FloorKindNotVerifiable)
1342        );
1343    }
1344
1345    #[test]
1346    fn admissible_statuses_are_closed_per_declaration() {
1347        assert!(floor_status_admissible(
1348            &CompatibilityFloor::None,
1349            BuildStrategy::NativeCargo,
1350            FloorVerificationStatus::NotDeclared
1351        ));
1352        assert!(!floor_status_admissible(
1353            &CompatibilityFloor::None,
1354            BuildStrategy::NativeCargo,
1355            FloorVerificationStatus::Verified
1356        ));
1357        assert!(floor_status_admissible(
1358            &glibc(2, 17),
1359            BuildStrategy::CargoZigbuild,
1360            FloorVerificationStatus::ToolchainBound
1361        ));
1362        assert!(!floor_status_admissible(
1363            &glibc(2, 17),
1364            BuildStrategy::CargoZigbuild,
1365            FloorVerificationStatus::Verified
1366        ));
1367        assert!(floor_status_admissible(
1368            &glibc(2, 17),
1369            BuildStrategy::NativeCargo,
1370            FloorVerificationStatus::Verified
1371        ));
1372        assert!(floor_status_admissible(
1373            &glibc(2, 17),
1374            BuildStrategy::NativeCargo,
1375            FloorVerificationStatus::NotSatisfied
1376        ));
1377        assert!(!floor_status_admissible(
1378            &glibc(2, 17),
1379            BuildStrategy::NativeCargo,
1380            FloorVerificationStatus::ToolchainBound
1381        ));
1382    }
1383
1384    #[test]
1385    fn combined_statuses_keep_the_most_severe_result() {
1386        assert_eq!(
1387            aggregate_floor_status(&[
1388                FloorVerificationStatus::Verified,
1389                FloorVerificationStatus::NotSatisfied
1390            ]),
1391            FloorVerificationStatus::NotSatisfied
1392        );
1393        assert_eq!(
1394            aggregate_floor_status(&[
1395                FloorVerificationStatus::Verified,
1396                FloorVerificationStatus::Unverified(FloorUnverifiedReason::NoVersionRequirement)
1397            ]),
1398            FloorVerificationStatus::Unverified(FloorUnverifiedReason::NoVersionRequirement)
1399        );
1400        assert_eq!(
1401            aggregate_floor_status(&[
1402                FloorVerificationStatus::Unverified(FloorUnverifiedReason::NoVersionRequirement),
1403                FloorVerificationStatus::Unverified(FloorUnverifiedReason::UnreadableCandidate)
1404            ]),
1405            FloorVerificationStatus::Unverified(FloorUnverifiedReason::UnreadableCandidate)
1406        );
1407        assert_eq!(
1408            aggregate_floor_status(&[FloorVerificationStatus::Verified]),
1409            FloorVerificationStatus::Verified
1410        );
1411    }
1412}