Skip to main content

userspace_build/memory/stack/
build.rs

1use crate::target::os::syscall;
2
3use super::Error;
4
5use super::auxiliary::atype::constants::{
6    AT_BASE, AT_BASE_PLATFORM, AT_ENTRY, AT_EXECFN, AT_NULL, AT_PHDR, AT_PHENT, AT_PHNUM,
7    AT_PLATFORM, AT_RANDOM, AT_SYSINFO_EHDR,
8};
9
10const REQUIRED_AUXILIARY_KEYS: [usize; 7] = [
11    AT_PHDR, AT_PHENT, AT_PHNUM, AT_BASE, AT_ENTRY, AT_EXECFN, AT_RANDOM,
12];
13
14unsafe fn count_null_terminated(pointer: *const usize, limit: usize) -> Option<usize> {
15    for index in 0..limit {
16        if unsafe { *pointer.add(index) } == 0 {
17            return Some(index);
18        }
19    }
20    None
21}
22
23unsafe fn c_string_size(pointer: *const u8, limit: usize) -> Option<usize> {
24    if pointer.is_null() {
25        return None;
26    }
27
28    for index in 0..limit {
29        if unsafe { *pointer.add(index) } == 0 {
30            return index.checked_add(1);
31        }
32    }
33    None
34}
35
36unsafe fn copy_c_string(source: *const u8, destination: *mut u8, limit: usize) -> Option<usize> {
37    let size = unsafe { c_string_size(source, limit) }?;
38    unsafe {
39        core::ptr::copy_nonoverlapping(source, destination, size);
40    }
41    Some(size)
42}
43
44fn update_auxiliary(
45    key: usize,
46    value: &mut usize,
47    entry: u64,
48    phdr: u64,
49    phent: usize,
50    phnum: usize,
51    interpreter_base: usize,
52    execfn: usize,
53) {
54    match key {
55        AT_PHDR => *value = phdr as usize,
56        AT_PHENT => *value = phent,
57        AT_PHNUM => *value = phnum,
58        AT_BASE => *value = interpreter_base,
59        AT_ENTRY => *value = entry as usize,
60        AT_EXECFN => *value = execfn,
61        _ => {}
62    }
63}
64
65fn has_auxiliary_key(auxiliary: *const usize, entry_count: usize, key: usize) -> bool {
66    for index in 0..entry_count {
67        if unsafe { *auxiliary.add(index.saturating_mul(2)) } == key {
68            return true;
69        }
70    }
71    false
72}
73
74fn fill_random(destination: *mut u8) -> bool {
75    match syscall::getrandom(destination, 16, 0) {
76        Ok(crate::Ok::Target(crate::target::Ok::Os(crate::target::os::Ok::Syscall(
77            crate::target::os::syscall::Ok::GetRandom(syscall::getrandom::Ok::Default(count)),
78        )))) if count == 16 => true,
79        _ => false,
80    }
81}
82
83pub fn build_initial_stack(
84    initial_stack: crate::target::arch::PointerType,
85    path: &str,
86    _path_pointer: *const u8,
87    entry: u64,
88    phdr: u64,
89    phent: usize,
90    phnum: usize,
91    interpreter_base: usize,
92) -> Result<crate::target::arch::PointerType, Error> {
93    let original = initial_stack as *const usize;
94    let original_argc = unsafe { *original };
95    if original_argc > 4096 {
96        return Err(Error::StackConstructionFailed);
97    }
98
99    let old_argv = unsafe { original.add(1) };
100    let old_envp = unsafe { old_argv.add(original_argc + 1) };
101    let env_count =
102        unsafe { count_null_terminated(old_envp, 4096) }.ok_or(Error::StackConstructionFailed)?;
103    let old_auxv = unsafe { old_envp.add(env_count + 1) };
104    let mut aux_count = 0usize;
105    let mut found_aux_null = false;
106    while aux_count < 1024 {
107        let key = unsafe { *old_auxv.add(aux_count * 2) };
108        aux_count += 1;
109        if key == AT_NULL {
110            found_aux_null = true;
111            break;
112        }
113    }
114    if !found_aux_null {
115        return Err(Error::StackConstructionFailed);
116    }
117
118    let source_aux_count = aux_count.saturating_sub(1);
119    let mut missing_aux_count = 0usize;
120    for key in REQUIRED_AUXILIARY_KEYS {
121        if !has_auxiliary_key(old_auxv, source_aux_count, key) {
122            missing_aux_count = missing_aux_count
123                .checked_add(1)
124                .ok_or(Error::StackConstructionFailed)?;
125        }
126    }
127    let output_aux_count = source_aux_count
128        .checked_add(missing_aux_count)
129        .and_then(|value| value.checked_add(1))
130        .ok_or(Error::StackConstructionFailed)?;
131
132    let new_argc = if original_argc >= 2 {
133        original_argc - 1
134    } else {
135        1
136    };
137
138    let words = 1usize
139        .checked_add(new_argc + 1)
140        .and_then(|value| value.checked_add(env_count + 1))
141        .and_then(|value| value.checked_add(output_aux_count.checked_mul(2)?))
142        .ok_or(Error::StackConstructionFailed)?;
143    let word_bytes = words
144        .checked_mul(core::mem::size_of::<usize>())
145        .ok_or(Error::StackConstructionFailed)?;
146
147    let mut data_bytes = path
148        .as_bytes()
149        .len()
150        .checked_add(1)
151        .ok_or(Error::StackConstructionFailed)?;
152
153    for index in 1..new_argc {
154        let source = unsafe { *old_argv.add(index + 1) as *const u8 };
155        let size =
156            unsafe { c_string_size(source, super::SIZE) }.ok_or(Error::StackConstructionFailed)?;
157        data_bytes = data_bytes
158            .checked_add(size)
159            .ok_or(Error::StackConstructionFailed)?;
160    }
161
162    for index in 0..env_count {
163        let source = unsafe { *old_envp.add(index) as *const u8 };
164        let size =
165            unsafe { c_string_size(source, super::SIZE) }.ok_or(Error::StackConstructionFailed)?;
166        data_bytes = data_bytes
167            .checked_add(size)
168            .ok_or(Error::StackConstructionFailed)?;
169    }
170
171    for index in 0..source_aux_count {
172        let key = unsafe { *old_auxv.add(index * 2) };
173        let value = unsafe { *old_auxv.add(index * 2 + 1) };
174        let extra = match key {
175            AT_RANDOM => 16,
176            AT_PLATFORM | AT_BASE_PLATFORM if value != 0 => unsafe {
177                c_string_size(value as *const u8, super::SIZE)
178                    .ok_or(Error::StackConstructionFailed)?
179            },
180            _ => 0,
181        };
182        data_bytes = data_bytes
183            .checked_add(extra)
184            .ok_or(Error::StackConstructionFailed)?;
185    }
186    if !has_auxiliary_key(old_auxv, source_aux_count, AT_RANDOM) {
187        data_bytes = data_bytes
188            .checked_add(16)
189            .ok_or(Error::StackConstructionFailed)?;
190    }
191
192    let required_bytes = word_bytes
193        .checked_add(15)
194        .and_then(|value| value.checked_add(data_bytes))
195        .ok_or(Error::StackConstructionFailed)?;
196    if required_bytes > super::SIZE {
197        return Err(Error::StackConstructionFailed);
198    }
199
200    let mapping_length = super::SIZE
201        .checked_add(crate::memory::page::SIZE)
202        .ok_or(Error::StackConstructionFailed)?;
203    let stack_address = match syscall::mmap(
204        core::ptr::null_mut(),
205        mapping_length,
206        (syscall::mmap::Prot::Read.to() as i32) | (syscall::mmap::Prot::Write.to() as i32),
207        (syscall::mmap::Flag::Private.to() as i32) | (syscall::mmap::Flag::Anonymous.to() as i32),
208        -1,
209        0,
210    ) {
211        Ok(crate::Ok::Target(crate::target::Ok::Os(crate::target::os::Ok::Syscall(
212            crate::target::os::syscall::Ok::MMap(syscall::mmap::Ok::Default(address)),
213        )))) if address != u64::MAX as usize => address,
214        _ => return Err(Error::StackConstructionFailed),
215    };
216
217    let unmap_stack = || {
218        let _ = syscall::munmap(stack_address as *mut u8, mapping_length);
219    };
220
221    match syscall::mprotect(
222        stack_address as *mut u8,
223        crate::memory::page::SIZE,
224        syscall::mmap::Prot::None.to() as i32,
225    ) {
226        Ok(crate::Ok::Target(crate::target::Ok::Os(crate::target::os::Ok::Syscall(
227            crate::target::os::syscall::Ok::MProtect(syscall::mprotect::Ok::Default(_)),
228        )))) => {}
229        _ => {
230            unmap_stack();
231            return Err(Error::StackConstructionFailed);
232        }
233    }
234
235    let stack_top = match stack_address.checked_add(mapping_length) {
236        Some(value) => value,
237        None => {
238            unmap_stack();
239            return Err(Error::StackConstructionFailed);
240        }
241    };
242    let stack_start = match stack_top.checked_sub(required_bytes) {
243        Some(value) => value & !15usize,
244        None => {
245            unmap_stack();
246            return Err(Error::StackConstructionFailed);
247        }
248    };
249    let usable_start = match stack_address.checked_add(crate::memory::page::SIZE) {
250        Some(value) => value,
251        None => {
252            unmap_stack();
253            return Err(Error::StackConstructionFailed);
254        }
255    };
256    if stack_start < usable_start {
257        unmap_stack();
258        return Err(Error::StackConstructionFailed);
259    }
260
261    let stack = stack_start as *mut usize;
262    let data_start = match stack_start
263        .checked_add(word_bytes)
264        .and_then(|value| value.checked_add(15))
265        .map(|value| value & !15usize)
266    {
267        Some(value) => value,
268        None => {
269            unmap_stack();
270            return Err(Error::StackConstructionFailed);
271        }
272    };
273    let data_end = match data_start.checked_add(data_bytes) {
274        Some(value) if value <= stack_top => value,
275        _ => {
276            unmap_stack();
277            return Err(Error::StackConstructionFailed);
278        }
279    };
280
281    unsafe {
282        *stack = new_argc;
283        let argv = stack.add(1);
284        let envp = argv.add(new_argc + 1);
285        let auxv = envp.add(env_count + 1);
286        let mut data_cursor = data_start as *mut u8;
287
288        let target_path_destination = data_cursor;
289        core::ptr::copy_nonoverlapping(
290            path.as_bytes().as_ptr(),
291            target_path_destination,
292            path.as_bytes().len(),
293        );
294        *target_path_destination.add(path.as_bytes().len()) = 0;
295        data_cursor = data_cursor.add(path.as_bytes().len() + 1);
296        *argv = target_path_destination as usize;
297
298        for index in 1..new_argc {
299            let source = *old_argv.add(index + 1) as *const u8;
300            let destination = data_cursor;
301            let Some(size) = copy_c_string(source, destination, super::SIZE) else {
302                unmap_stack();
303                return Err(Error::StackConstructionFailed);
304            };
305            *argv.add(index) = destination as usize;
306            data_cursor = data_cursor.add(size);
307        }
308        *argv.add(new_argc) = 0;
309
310        for index in 0..env_count {
311            let source = *old_envp.add(index) as *const u8;
312            let destination = data_cursor;
313            let Some(size) = copy_c_string(source, destination, super::SIZE) else {
314                unmap_stack();
315                return Err(Error::StackConstructionFailed);
316            };
317            *envp.add(index) = destination as usize;
318            data_cursor = data_cursor.add(size);
319        }
320        *envp.add(env_count) = 0;
321
322        let mut output_aux_index = 0usize;
323        for index in 0..source_aux_count {
324            let key = *old_auxv.add(index * 2);
325            let mut value = *old_auxv.add(index * 2 + 1);
326            update_auxiliary(
327                key,
328                &mut value,
329                entry,
330                phdr,
331                phent,
332                phnum,
333                interpreter_base,
334                target_path_destination as usize,
335            );
336
337            match key {
338                AT_RANDOM => {
339                    if !fill_random(data_cursor) {
340                        unmap_stack();
341                        return Err(Error::StackConstructionFailed);
342                    }
343                    value = data_cursor as usize;
344                    data_cursor = data_cursor.add(16);
345                }
346                AT_PLATFORM | AT_BASE_PLATFORM if value != 0 => {
347                    let source = value as *const u8;
348                    let destination = data_cursor;
349                    let Some(size) = copy_c_string(source, destination, super::SIZE) else {
350                        unmap_stack();
351                        return Err(Error::StackConstructionFailed);
352                    };
353                    value = destination as usize;
354                    data_cursor = data_cursor.add(size);
355                }
356                AT_SYSINFO_EHDR => {}
357                _ => {}
358            }
359
360            *auxv.add(output_aux_index * 2) = key;
361            *auxv.add(output_aux_index * 2 + 1) = value;
362            output_aux_index += 1;
363        }
364
365        for key in REQUIRED_AUXILIARY_KEYS {
366            if has_auxiliary_key(old_auxv, source_aux_count, key) {
367                continue;
368            }
369
370            let mut value = 0usize;
371            update_auxiliary(
372                key,
373                &mut value,
374                entry,
375                phdr,
376                phent,
377                phnum,
378                interpreter_base,
379                target_path_destination as usize,
380            );
381
382            if key == AT_RANDOM {
383                if !fill_random(data_cursor) {
384                    unmap_stack();
385                    return Err(Error::StackConstructionFailed);
386                }
387                value = data_cursor as usize;
388                data_cursor = data_cursor.add(16);
389            }
390
391            *auxv.add(output_aux_index * 2) = key;
392            *auxv.add(output_aux_index * 2 + 1) = value;
393            output_aux_index += 1;
394        }
395
396        *auxv.add(output_aux_index * 2) = AT_NULL;
397        *auxv.add(output_aux_index * 2 + 1) = 0;
398
399        debug_assert!((data_cursor as usize) <= data_end);
400    }
401
402    Ok(stack_start as crate::target::arch::PointerType)
403}