@@ -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