@@ -284,10 +284,10 @@ pub mod guard {
284
284
ret
285
285
}
286
286
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 ( ) ?;
291
291
292
292
// Ensure stackaddr is page aligned! A parent process might
293
293
// have reset RLIMIT_STACK to be non-page aligned. The
@@ -296,10 +296,17 @@ pub mod guard {
296
296
// page-aligned, calculate the fix such that stackaddr <
297
297
// new_page_aligned_stackaddr < stackaddr + stacksize
298
298
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 ( ) ?;
303
310
304
311
if cfg ! ( target_os = "linux" ) {
305
312
// Linux doesn't allocate the whole stack right away, and
@@ -338,14 +345,7 @@ pub mod guard {
338
345
339
346
pub unsafe fn deinit ( ) {
340
347
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 ( ) {
349
349
// Undo the guard page mapping.
350
350
if munmap ( stackaddr, PAGE_SIZE ) != 0 {
351
351
panic ! ( "unable to deallocate the guard page" ) ;
0 commit comments