Skip to main content

vstd_extra/external/
xmas_elf.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Trusted specifications for xmas-elf 0.10.0's parsing and header access.
3use vstd::{prelude::*, std_specs::iter::IteratorSpec};
4use xmas_elf::{
5    ElfFile,
6    header::{Class, Header, HeaderPt1, HeaderPt2, HeaderPt2_, Machine_, Type_ as HeaderType},
7    program::{
8        Flags, ProgramHeader, ProgramHeader32, ProgramHeader64, SegmentData, TYPE_GNU_RELRO,
9        TYPE_HIOS, TYPE_HIPROC, TYPE_LOOS, TYPE_LOPROC, Type, Type_,
10    },
11};
12
13use super::slice::as_ptr_spec;
14
15verus! {
16
17#[verifier::external_type_specification]
18pub struct ExElfFile<'a>(ElfFile<'a>);
19
20#[verifier::external_type_specification]
21pub struct ExHeader<'a>(Header<'a>);
22
23// Its Class_, Data_, Version_, and OsAbi_ fields wrap private bytes.
24#[verifier::external_type_specification]
25#[verifier::external_body]
26pub struct ExHeaderPt1(HeaderPt1);
27
28#[verifier::external_type_specification]
29pub struct ExHeaderClass(Class);
30
31#[verifier::external_type_specification]
32pub struct ExHeaderPt2<'a>(HeaderPt2<'a>);
33
34#[verifier::external_type_specification]
35pub struct ExHeaderPt2Raw<P>(HeaderPt2_<P>);
36
37type ElfHeader32 = HeaderPt2_<u32>;
38
39type ElfHeader64 = HeaderPt2_<u64>;
40
41// Check the sizes and alignments used by the parsing predicates against Rust's layouts.
42global layout HeaderPt1 is size == 16, align == 1;
43
44global layout ElfHeader32 is size == 36, align == 4;
45
46global layout ElfHeader64 is size == 48, align == 8;
47
48global layout ProgramHeader32 is size == 32, align == 4;
49
50global layout ProgramHeader64 is size == 56, align == 8;
51
52#[verifier::external_type_specification]
53pub struct ExHeaderType(HeaderType);
54
55// Machine_ has a private u16 field; Verus requires an opaque proxy.
56#[verifier::external_type_specification]
57#[verifier::external_body]
58pub struct ExHeaderMachine(Machine_);
59
60/// The parser's normal return value, including its original error string.
61pub uninterp spec fn elf_parse_result<'a>(input: &'a [u8]) -> Result<ElfFile<'a>, &'static str>;
62
63/// <https://docs.rs/xmas-elf/0.10.0/src/xmas_elf/header.rs.html#9-52>
64pub open spec fn elf_parse_no_unwind(input: &[u8]) -> bool {
65    if input@.len() < 16 || input@[..4] != seq![0x7fu8, b'E', b'L', b'F'] {
66        true
67    } else {
68        let addr_pt2 = as_ptr_spec(input).addr() + 16;
69        match input@[4] {
70            1 => input@.len() < 52 || addr_pt2 % 4 == 0,
71            2 => input@.len() < 64 || addr_pt2 % 8 == 0,
72            _ => true,
73        }
74    }
75}
76
77/// The sequence yielded before ProgramIter first returns None.
78pub uninterp spec fn elf_program_headers<'a>(elf: &ElfFile<'a>) -> Seq<ProgramHeader<'a>>;
79
80/// The class getter's value; HeaderPt1's integer wrapper fields remain opaque.
81pub uninterp spec fn header_class(header: &HeaderPt1) -> Class;
82
83/// Empty tables or zero offsets/strides stop iteration without reading an entry.
84/// Otherwise every entry must fit in the input, hold the class-specific header,
85/// and be aligned. The end bound also excludes arithmetic overflow in any build
86/// profile. Program-header class comes from pt1, even for a manually built ElfFile.
87pub open spec fn elf_program_headers_readable(elf: &ElfFile<'_>) -> bool {
88    let (offset, entry_size, count) = match elf.header.pt2 {
89        HeaderPt2::Header32(h) => (h.ph_offset as u64, h.ph_entry_size, h.ph_count),
90        HeaderPt2::Header64(h) => (h.ph_offset, h.ph_entry_size, h.ph_count),
91    };
92    if count == 0 || offset == 0 || entry_size == 0 {
93        true
94    } else {
95        let (size, align): (int, int) = match elf.header.pt1.class() {
96            Class::ThirtyTwo => (32, 4),
97            Class::SixtyFour => (56, 8),
98            _ => (0, 0),
99        };
100        // parse_program_header casts ph_offset to usize before adding each index.
101        let start = if offset <= usize::MAX {
102            offset as int
103        } else {
104            (offset as int) % (usize::MAX + 1)
105        };
106        let end = start + count * entry_size;
107        &&& align > 0
108        &&& end <= usize::MAX
109        &&& end <= elf.input@.len()
110        &&& entry_size >= size
111        &&& (as_ptr_spec(elf.input).addr() + start) % align == 0
112        &&& (count == 1 || (entry_size as int) % align == 0)
113    }
114}
115
116#[verifier::when_used_as_spec(header_class)]
117pub assume_specification[ HeaderPt1::class ](header: &HeaderPt1) -> Class
118    returns
119        header_class(header),
120    opens_invariants none
121    no_unwind
122;
123
124/// The entry-point field, widened from either ELF header representation to u64.
125pub open spec fn header_entry_point(header: &HeaderPt2<'_>) -> u64 {
126    match *header {
127        HeaderPt2::Header32(h) => h.entry_point as u64,
128        HeaderPt2::Header64(h) => h.entry_point,
129    }
130}
131
132/// ElfFile::new delegates to parse_header and stores the original input slice on success.
133pub assume_specification<'a>[ ElfFile::<'a>::new ](input: &'a [u8]) -> (result: Result<
134    ElfFile<'a>,
135    &'static str,
136>)
137    ensures
138        result matches Ok(elf) ==> {
139            &&& elf.input == input
140            &&& as_ptr_spec(elf.input) == as_ptr_spec(input)
141        },
142    returns
143        elf_parse_result(input),
144    opens_invariants none
145    no_unwind when elf_parse_no_unwind(input)
146;
147
148/// The constructor returns ProgramIter at index zero. Its collect result follows
149/// the first-None sequence only when the program-table reads cannot panic.
150pub assume_specification<'a, 'b>[ ElfFile::<'a>::program_iter ](elf: &'b ElfFile<'a>) -> (iter:
151    impl Iterator<Item = ProgramHeader<'a>> + 'b)
152    ensures
153        elf_program_headers_readable(elf) ==> {
154            &&& IteratorSpec::obeys_prophetic_iter_laws(&iter)
155            &&& IteratorSpec::remaining(&iter) == elf_program_headers(elf)
156            &&& IteratorSpec::produces(&iter) == Seq::new(
157                elf_program_headers(elf).len(),
158                |i: int| true,
159            )
160            &&& IteratorSpec::decrease(&iter) == Some(elf_program_headers(elf).len())
161        },
162    opens_invariants none
163    no_unwind
164;
165
166#[verifier::when_used_as_spec(header_entry_point)]
167pub assume_specification<'a>[ HeaderPt2::<'a>::entry_point ](header: &HeaderPt2<'a>) -> u64
168    returns
169        header_entry_point(header),
170    opens_invariants none
171    no_unwind
172;
173
174#[verifier::external_type_specification]
175pub struct ExProgramHeader<'a>(ProgramHeader<'a>);
176
177#[verifier::external_type_specification]
178pub struct ExProgramHeader32(ProgramHeader32);
179
180#[verifier::external_type_specification]
181pub struct ExProgramHeader64(ProgramHeader64);
182
183#[verifier::external_type_specification]
184pub struct ExProgramFlags(Flags);
185
186// Type_ has a private u32 field; Verus requires an opaque proxy.
187#[verifier::external_type_specification]
188#[verifier::external_body]
189pub struct ExProgramType(Type_);
190
191#[verifier::external_type_specification]
192pub struct ExProgramTypeValue(Type);
193
194pub assume_specification[ <Type as core::cmp::PartialEq>::eq ](left: &Type, right: &Type) -> bool
195    returns
196        *left == *right,
197;
198
199#[verifier::external_type_specification]
200pub struct ExSegmentData<'a>(SegmentData<'a>);
201
202#[verifier::external_type_specification]
203#[verifier::external_body]
204#[verifier::reject_recursive_types(P)]
205pub struct ExDynamic<P>(xmas_elf::dynamic::Dynamic<P>) where
206    xmas_elf::dynamic::Tag_<P>: core::fmt::Debug,
207;
208
209#[verifier::external_type_specification]
210#[verifier::external_body]
211#[verifier::reject_recursive_types(P)]
212pub struct ExDynamicTag<P>(xmas_elf::dynamic::Tag_<P>);
213
214#[verifier::external_type_specification]
215#[verifier::external_body]
216pub struct ExNoteHeader(xmas_elf::sections::NoteHeader);
217
218/// The private u32 stored by Type_. Only its representation remains opaque;
219/// decoding below follows xmas-elf 0.10.0's Type_::as_type.
220pub uninterp spec fn program_type_raw(type_: Type_) -> u32;
221
222// Constants from program.rs; keep their trusted values at the external boundary.
223pub assume_specification[ xmas_elf::program::TYPE_LOOS ] -> u32
224    returns
225        0x60000000u32,
226;
227
228pub assume_specification[ xmas_elf::program::TYPE_HIOS ] -> u32
229    returns
230        0x6fffffffu32,
231;
232
233pub assume_specification[ xmas_elf::program::TYPE_LOPROC ] -> u32
234    returns
235        0x70000000u32,
236;
237
238pub assume_specification[ xmas_elf::program::TYPE_HIPROC ] -> u32
239    returns
240        0x7fffffffu32,
241;
242
243pub assume_specification[ xmas_elf::program::TYPE_GNU_RELRO ] -> u32
244    returns
245        0x6474e552u32,
246;
247
248/// GNU_RELRO takes precedence over the enclosing OS-specific range.
249pub open spec fn program_type_from_raw(raw: u32) -> Result<Type, &'static str> {
250    match raw {
251        0 => Ok(Type::Null),
252        1 => Ok(Type::Load),
253        2 => Ok(Type::Dynamic),
254        3 => Ok(Type::Interp),
255        4 => Ok(Type::Note),
256        5 => Ok(Type::ShLib),
257        6 => Ok(Type::Phdr),
258        7 => Ok(Type::Tls),
259        _ => if raw == TYPE_GNU_RELRO {
260            Ok(Type::GnuRelro)
261        } else if TYPE_LOOS <= raw <= TYPE_HIOS {
262            Ok(Type::OsSpecific(raw))
263        } else if TYPE_LOPROC <= raw <= TYPE_HIPROC {
264            Ok(Type::ProcessorSpecific(raw))
265        } else {
266            Err("Invalid type")
267        },
268    }
269}
270
271pub open spec fn program_type_result(type_: Type_) -> Result<Type, &'static str> {
272    program_type_from_raw(program_type_raw(type_))
273}
274
275// Derived Default initializes the private u32 to zero.
276pub assume_specification[ <Type_ as core::default::Default>::default ]() -> (ret: Type_)
277    ensures
278        program_type_raw(ret) == 0,
279;
280
281pub open spec fn program_header_type(header: &ProgramHeader<'_>) -> Result<Type, &'static str> {
282    match *header {
283        ProgramHeader::Ph32(h) => program_type_result(h.type_),
284        ProgramHeader::Ph64(h) => program_type_result(h.type_),
285    }
286}
287
288pub open spec fn program_header_file_size(header: &ProgramHeader<'_>) -> u64 {
289    match *header {
290        ProgramHeader::Ph32(h) => h.file_size as u64,
291        ProgramHeader::Ph64(h) => h.file_size,
292    }
293}
294
295pub open spec fn program_header_offset(header: &ProgramHeader<'_>) -> u64 {
296    match *header {
297        ProgramHeader::Ph32(h) => h.offset as u64,
298        ProgramHeader::Ph64(h) => h.offset,
299    }
300}
301
302/// raw_data adds the source fields before casting to usize. In ELF32 that
303/// addition is u32, even on a 64-bit host. Empty data bypasses the offset.
304pub open spec fn program_load_data_readable(header: &ProgramHeader<'_>, input: Seq<u8>) -> bool {
305    let offset = header.offset();
306    let size = header.file_size();
307    size == 0 || {
308        &&& match *header {
309            ProgramHeader::Ph32(_) => offset + size <= u32::MAX,
310            ProgramHeader::Ph64(_) => offset + size <= u64::MAX,
311        }
312        &&& offset + size <= usize::MAX
313        &&& offset + size <= input.len()
314    }
315}
316
317pub open spec fn program_load_bytes(header: &ProgramHeader<'_>, input: Seq<u8>) -> Seq<u8> {
318    let size = header.file_size();
319    if size == 0 {
320        Seq::empty()
321    } else {
322        input[header.offset()..header.offset() + size]
323    }
324}
325
326#[verifier::when_used_as_spec(program_header_type)]
327pub assume_specification<'a>[ ProgramHeader::<'a>::get_type ](header: &ProgramHeader<'a>) -> Result<
328    Type,
329    &'static str,
330>
331    returns
332        program_header_type(header),
333    opens_invariants none
334    no_unwind
335;
336
337#[verifier::when_used_as_spec(program_header_file_size)]
338pub assume_specification<'a>[ ProgramHeader::<'a>::file_size ](header: &ProgramHeader<'a>) -> u64
339    returns
340        program_header_file_size(header),
341    opens_invariants none
342    no_unwind
343;
344
345#[verifier::when_used_as_spec(program_header_offset)]
346pub assume_specification<'a>[ ProgramHeader::<'a>::offset ](header: &ProgramHeader<'a>) -> u64
347    returns
348        program_header_offset(header),
349    opens_invariants none
350    no_unwind
351;
352
353/// Audited only for Load: get_data delegates to raw_data and returns Undefined.
354/// Other segment types include dynamic/note parsing and receive no guarantees.
355pub assume_specification<'a>[ ProgramHeader::<'a>::get_data ](
356    header: &ProgramHeader<'a>,
357    elf: &ElfFile<'a>,
358) -> (ret: Result<SegmentData<'a>, &'static str>)
359    ensures
360        header.get_type() == Ok(Type::Load) && program_load_data_readable(header, elf.input@) ==> {
361            ret matches Ok(SegmentData::Undefined(bytes)) && bytes@ == program_load_bytes(
362                header,
363                elf.input@,
364            )
365        },
366    opens_invariants none
367    no_unwind when header.get_type() == Ok(Type::Load) && program_load_data_readable(
368    header,
369    elf.input@,
370)
371;
372
373/// The virtual address stored in either ELF program-header representation.
374pub open spec fn program_header_virtual_addr(header: &ProgramHeader<'_>) -> u64 {
375    match *header {
376        ProgramHeader::Ph32(h) => h.virtual_addr as u64,
377        ProgramHeader::Ph64(h) => h.virtual_addr,
378    }
379}
380
381/// The memory size stored in either ELF program-header representation.
382pub open spec fn program_header_mem_size(header: &ProgramHeader<'_>) -> u64 {
383    match *header {
384        ProgramHeader::Ph32(h) => h.mem_size as u64,
385        ProgramHeader::Ph64(h) => h.mem_size,
386    }
387}
388
389/// The flags field in either program-header representation.
390pub open spec fn program_header_flags(header: &ProgramHeader<'_>) -> Flags {
391    match *header {
392        ProgramHeader::Ph32(h) => h.flags,
393        ProgramHeader::Ph64(h) => h.flags,
394    }
395}
396
397#[verifier::when_used_as_spec(program_header_flags)]
398pub assume_specification<'a>[ ProgramHeader::<'a>::flags ](header: &ProgramHeader<'a>) -> Flags
399    returns
400        program_header_flags(header),
401    opens_invariants none
402    no_unwind
403;
404
405pub assume_specification[ Flags::is_execute ](flags: &Flags) -> bool
406    returns
407        flags.0 & 1 == 1,
408    opens_invariants none
409    no_unwind
410;
411
412pub assume_specification[ Flags::is_read ](flags: &Flags) -> bool
413    returns
414        flags.0 & 4 == 4,
415    opens_invariants none
416    no_unwind
417;
418
419pub assume_specification[ Flags::is_write ](flags: &Flags) -> bool
420    returns
421        flags.0 & 2 == 2,
422    opens_invariants none
423    no_unwind
424;
425
426/// Matches `getter!(virtual_addr, u64)` in xmas-elf 0.10.0's `program.rs`.
427#[verifier::when_used_as_spec(program_header_virtual_addr)]
428pub assume_specification<'a>[ ProgramHeader::<'a>::virtual_addr ](header: &ProgramHeader<'a>) -> u64
429    returns
430        program_header_virtual_addr(header),
431    opens_invariants none
432    no_unwind
433;
434
435/// Matches `getter!(mem_size, u64)` in xmas-elf 0.10.0's `program.rs`.
436#[verifier::when_used_as_spec(program_header_mem_size)]
437pub assume_specification<'a>[ ProgramHeader::<'a>::mem_size ](header: &ProgramHeader<'a>) -> u64
438    returns
439        program_header_mem_size(header),
440    opens_invariants none
441    no_unwind
442;
443
444} // verus!