linux_print_layout/linux_print_layout.rs
1/*
2MIT License
3
4Copyright (c) 2025 Philipp Schuster
5
6Permission is hereby granted, free of charge, to any person obtaining a copy
7of this software and associated documentation files (the "Software"), to deal
8in the Software without restriction, including without limitation the rights
9to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10copies of the Software, and to permit persons to whom the Software is
11furnished to do so, subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all
14copies or substantial portions of the Software.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22SOFTWARE.
23*/
24#![no_main]
25
26use linux_libc_auxv::StackLayoutRef;
27use std::slice;
28
29/// Example that parses the layout and prints it. Only runs on Linux.
30#[unsafe(no_mangle)]
31fn main(argc: isize, argv: *const *const u8) -> isize {
32 let buffer = unsafe {
33 // 100 KiB, reasonably big.
34 // On my Linux machine, the structure needs 23 KiB
35 slice::from_raw_parts(argv.cast::<u8>(), 0x19000)
36 };
37
38 let parsed = StackLayoutRef::new(buffer, Some(argc as usize));
39
40 println!("There are {} arguments.", parsed.argc());
41 println!(" argv (raw)");
42 for (i, arg) in parsed.argv_raw_iter().enumerate() {
43 println!(" [{i}] @ {arg:?}");
44 }
45 println!(" argv");
46 // SAFETY: The pointers are valid in the address space of this process.
47 for (i, arg) in unsafe { parsed.argv_iter() }.enumerate() {
48 println!(" [{i}] {arg:?}");
49 }
50
51 println!("There are {} environment variables.", parsed.envc());
52 println!(" envv (raw)");
53 for (i, env) in parsed.envv_raw_iter().enumerate() {
54 println!(" [{i}] {env:?}");
55 }
56 println!(" envv");
57 // SAFETY: The pointers are valid in the address space of this process.
58 for (i, env) in unsafe { parsed.envv_iter() }.enumerate() {
59 println!(" [{i}] {env:?}");
60 }
61
62 println!(
63 "There are {} auxiliary vector entries/AT variables.",
64 parsed.auxv_raw_iter().count()
65 );
66 println!(" aux");
67 // ptr iter is safe for other address spaces; the other only because here user_addr == write_addr
68 for aux in unsafe { parsed.auxv_iter() } {
69 if aux.key().value_in_data_area() {
70 println!(" {:?} => @ {:?}", aux.key(), aux);
71 } else {
72 println!(" {:?} => {:?}", aux.key(), aux);
73 }
74 }
75
76 0
77}