@@ -284,10 +284,10 @@ pub mod guard {
284284 ret
285285 }
286286
287- pub unsafe fn init ( ) -> Option < Guard > {
288- PAGE_SIZE = os :: page_size ( ) ;
289-
290- let mut stackaddr = get_stack_start ( ) ?;
287+ // Precondition: PAGE_SIZE is initialized.
288+ unsafe fn get_stack_start_aligned ( ) -> Option < * mut libc :: c_void > {
289+ assert ! ( PAGE_SIZE != 0 ) ;
290+ let stackaddr = get_stack_start ( ) ?;
291291
292292 // Ensure stackaddr is page aligned! A parent process might
293293 // have reset RLIMIT_STACK to be non-page aligned. The
@@ -296,10 +296,17 @@ pub mod guard {
296296 // page-aligned, calculate the fix such that stackaddr <
297297 // new_page_aligned_stackaddr < stackaddr + stacksize
298298 let remainder = ( stackaddr as usize ) % PAGE_SIZE ;
299- if remainder != 0 {
300- stackaddr = ( ( stackaddr as usize ) + PAGE_SIZE - remainder)
301- as * mut libc:: c_void ;
302- }
299+ Some ( if remainder == 0 {
300+ stackaddr
301+ } else {
302+ ( ( stackaddr as usize ) + PAGE_SIZE - remainder) as * mut libc:: c_void
303+ } )
304+ }
305+
306+ pub unsafe fn init ( ) -> Option < Guard > {
307+ PAGE_SIZE = os:: page_size ( ) ;
308+
309+ let stackaddr = get_stack_start_aligned ( ) ?;
303310
304311 if cfg ! ( target_os = "linux" ) {
305312 // Linux doesn't allocate the whole stack right away, and
@@ -338,14 +345,7 @@ pub mod guard {
338345
339346 pub unsafe fn deinit ( ) {
340347 if !cfg ! ( target_os = "linux" ) {
341- if let Some ( mut stackaddr) = get_stack_start ( ) {
342- // Ensure address is aligned. Same as above.
343- let remainder = ( stackaddr as usize ) % PAGE_SIZE ;
344- if remainder != 0 {
345- stackaddr = ( ( stackaddr as usize ) + PAGE_SIZE - remainder)
346- as * mut libc:: c_void ;
347- }
348-
348+ if let Some ( stackaddr) = get_stack_start_aligned ( ) {
349349 // Undo the guard page mapping.
350350 if munmap ( stackaddr, PAGE_SIZE ) != 0 {
351351 panic ! ( "unable to deallocate the guard page" ) ;
0 commit comments