Skip to content

Commit b319285

Browse files
authored
[fix] fix user stack alignment
[fix] fix user stack alignment
1 parent 94ff7ec commit b319285

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

src/info.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ impl<'a> ELFParser<'a> {
142142
/// * `pagesz` - The page size of the system
143143
///
144144
/// Details about auxiliary vectors are described in <https://articles.manugarg.com/aboutelfauxiliaryvectors.html>
145-
pub fn auxv_vector(&self, pagesz: usize) -> [AuxvEntry; 16] {
145+
pub fn auxv_vector(&self, pagesz: usize) -> [AuxvEntry; 17] {
146146
[
147147
AuxvEntry::new(AuxvType::PHDR, self.phdr()),
148148
AuxvEntry::new(AuxvType::PHENT, self.phent()),
@@ -160,6 +160,7 @@ impl<'a> ELFParser<'a> {
160160
AuxvEntry::new(AuxvType::EGID, 0),
161161
AuxvEntry::new(AuxvType::RANDOM, 0),
162162
AuxvEntry::new(AuxvType::EXECFN, 0),
163+
AuxvEntry::new(AuxvType::NULL, 0),
163164
]
164165
}
165166

src/user_stack.rs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,20 @@ fn init_stack(args: &[String], envs: &[String], auxv: &mut [AuxvEntry], sp: usiz
8585
stack.push(padding_null.as_bytes(), &mut data);
8686

8787
stack.push("\0".repeat(stack.get_sp() % 16).as_bytes(), &mut data);
88-
assert!(stack.get_sp() % 16 == 0);
88+
89+
// Align stack to 16 bytes by padding if needed.
90+
// We will push following 8-byte items into stack:
91+
// - auxv (each entry is 2 * usize, so item count = auxv.len() * 2)
92+
// - envp (len + 1 for NULL terminator)
93+
// - argv (len + 1 for NULL terminator)
94+
// - argc (1 item)
95+
// Total items = auxv.len() * 2 + (envs.len() + 1) + (args.len() + 1) + 1
96+
// = auxv.len() * 2 + envs.len() + args.len() + 3
97+
// If odd, the stack top will not be aligned to 16 bytes unless we add 8-byte padding
98+
if (envs.len() + args.len() + 3) & 1 != 0 {
99+
stack.push(padding_null.as_bytes(), &mut data);
100+
}
101+
89102
// Push auxiliary vectors
90103
for auxv_entry in auxv.iter_mut() {
91104
if auxv_entry.get_type() == AuxvType::RANDOM {
@@ -112,6 +125,7 @@ fn init_stack(args: &[String], envs: &[String], auxv: &mut [AuxvEntry], sp: usiz
112125
stack.push_usize_slice(argv_slice.as_slice(), &mut data);
113126
// Push argc
114127
stack.push_usize_slice(&[args.len()], &mut data);
128+
assert!(stack.get_sp() % 16 == 0);
115129
data
116130
}
117131

0 commit comments

Comments
 (0)