Skip to content

Conversation

ndrewh
Copy link
Contributor

@ndrewh ndrewh commented Sep 15, 2025

Some sanitizers use mach_vm_region_recurse on macOS to find a sufficiently large gap to allocate shadow memory. Some sandboxes do not allow this.

When we get KERN_DENIED, we suggest to the user that it may have been blocked by the sandbox.

For error codes other than KERN_INVALID_ADDRESS and KERN_DENIED, we make sure to log a message and not use the address.

rdar://160625998

Some sanitizers use mach_vm_region_recurse on macOS to find a sufficiently
large gap to allocate shadow memory. Some sandboxes do not allow this.

When we get KERN_DENIED, we suggest to the user that it may have been
blocked by the sandbox.

For error codes other than KERN_INVALID_ADDRESS and KERN_DENIED,
we make sure to log a message and not use the address.

rdar://145860383
Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Member

llvmbot commented Sep 15, 2025

@llvm/pr-subscribers-compiler-rt-sanitizer

Author: Andrew Haberlandt (ndrewh)

Changes

Some sanitizers use mach_vm_region_recurse on macOS to find a sufficiently large gap to allocate shadow memory. Some sandboxes do not allow this.

When we get KERN_DENIED, we suggest to the user that it may have been blocked by the sandbox.

For error codes other than KERN_INVALID_ADDRESS and KERN_DENIED, we make sure to log a message and not use the address.

rdar://145860383


Full diff: https://github.com/llvm/llvm-project/pull/158670.diff

2 Files Affected:

  • (modified) compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp (+24-7)
  • (added) compiler-rt/test/asan/TestCases/Darwin/sandbox-vm-region-recurse.cpp (+34)
diff --git a/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp b/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp
index d4811ff4ed217..a3c0c18ec5760 100644
--- a/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp
+++ b/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp
@@ -1265,17 +1265,34 @@ uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
     kr = mach_vm_region_recurse(mach_task_self(), &address, &vmsize, &depth,
                                 (vm_region_info_t)&vminfo, &count);
 
-    // There are cases where going beyond the processes' max vm does
-    // not return KERN_INVALID_ADDRESS so we check for going beyond that
-    // max address as well.
-    if (kr == KERN_INVALID_ADDRESS || address > max_vm_address) {
+    if (kr == KERN_SUCCESS) {
+      // There are cases where going beyond the processes' max vm does
+      // not return KERN_INVALID_ADDRESS so we check for going beyond that
+      // max address as well.
+      if (address > max_vm_address) {
+        address = max_vm_address;
+        kr = -1;  // break after this iteration.
+      }
+
+      if (max_occupied_addr)
+        *max_occupied_addr = address + vmsize;
+    } else if (kr == KERN_INVALID_ADDRESS) {
       // No more regions beyond "address", consider the gap at the end of VM.
       address = max_vm_address;
-      vmsize = 0;
-      kr = -1;  // break after this iteration.
+
+      // We will break after this iteration anyway since kr != KERN_SUCCESS
+    } else if (kr == KERN_DENIED) {
+      Report("ERROR: Unable to find a memory range for dynamic shadow.\n");
+      Report("HINT: Ensure mach_vm_region_recurse is allowed under sandbox.\n");
+      Die();
     } else {
-      if (max_occupied_addr) *max_occupied_addr = address + vmsize;
+      Report("WARNING: mach_vm_region_recurse returned unexpected code %d\n",
+             kr);
+      DCHECK(false && "mach_vm_region_recurse returned unexpected code");
+      break;  // address is not valid unless KERN_SUCCESS, therefore we must not
+              // use it.
     }
+
     if (free_begin != address) {
       // We found a free region [free_begin..address-1].
       uptr gap_start = RoundUpTo((uptr)free_begin + left_padding, alignment);
diff --git a/compiler-rt/test/asan/TestCases/Darwin/sandbox-vm-region-recurse.cpp b/compiler-rt/test/asan/TestCases/Darwin/sandbox-vm-region-recurse.cpp
new file mode 100644
index 0000000000000..0044335cc1282
--- /dev/null
+++ b/compiler-rt/test/asan/TestCases/Darwin/sandbox-vm-region-recurse.cpp
@@ -0,0 +1,34 @@
+// Check that if mach_vm_region_recurse is disallowed by sandbox, we report a message saying so.
+
+// RUN: %clangxx_asan -O0 %s -o %t
+// RUN: not %run sandbox-exec -p '(version 1)(allow default)(deny syscall-mig (kernel-mig-routine mach_vm_region_recurse))' %t 2>&1 | FileCheck --check-prefix=CHECK-DENY %s
+// RUN: not %run %t 2>&1 | FileCheck --check-prefix=CHECK-ALLOW %s
+// RUN: %clangxx_asan -O3 %s -o %t
+// RUN: not %run sandbox-exec -p '(version 1)(allow default)(deny syscall-mig (kernel-mig-routine mach_vm_region_recurse))' %t 2>&1 | FileCheck --check-prefix=CHECK-DENY %s
+// RUN: not %run %t 2>&1 | FileCheck --check-prefix=CHECK-ALLOW %s
+
+// sandbox-exec isn't available on iOS
+// UNSUPPORTED: ios
+
+// x86_64 does not use ASAN_SHADOW_OFFSET_DYNAMIC
+// UNSUPPORTED: x86_64-darwin
+// UNSUPPORTED: x86_64h-darwin
+
+#include <stdlib.h>
+
+int main() {
+  char *x = (char *)malloc(10 * sizeof(char));
+  free(x);
+  return x[5];
+  // CHECK-ALLOW: {{.*ERROR: AddressSanitizer: heap-use-after-free on address}}
+  // CHECK-DENY-NOT: {{.*ERROR: AddressSanitizer: heap-use-after-free on address}}
+  // CHECK-ALLOW: {{READ of size 1 at 0x.* thread T0}}
+  // CHECK-ALLOW: {{    #0 0x.* in main}}
+  // CHECK-ALLOW: {{freed by thread T0 here:}}
+  // CHECK-ALLOW: {{    #0 0x.* in free}}
+  // CHECK-ALLOW: {{    #1 0x.* in main}}
+  // CHECK-ALLOW: {{previously allocated by thread T0 here:}}
+  // CHECK-ALLOW: {{    #0 0x.* in malloc}}
+  // CHECK-ALLOW: {{    #1 0x.* in main}}
+  // CHECK-DENY: {{.*HINT: Ensure mach_vm_region_recurse is allowed under sandbox}}
+}

@wrotki wrotki self-requested a review September 16, 2025 00:03
Copy link
Contributor

@DanBlackwell DanBlackwell left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One question, otherwise looks good; thanks!

kr = -1; // break after this iteration.

// We will break after this iteration anyway since kr != KERN_SUCCESS
} else if (kr == KERN_DENIED) {
Copy link
Contributor

@wrotki wrotki Sep 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would move this part up, to follow the 'early return/exit/Die' principle, otherwise I find it a bit harder to read (else as applied to what condition(s)? Once KERN_DENIED handling is out of the way, the following happy path logic has less variables (i.e. there's one less } else if () {

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I knew I saw it somewhere but only found it now, in Dan's comments to your other PR:

https://llvm.org/docs/CodingStandards.html#use-early-exits-and-continue-to-simplify-code

Copy link
Contributor Author

@ndrewh ndrewh Sep 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's see what @DanBlackwell thinks, but I sort of prefer it the way it is right now since all of the branches are kr == <something> (it's basically a switch: but we can't do that here easily because of the break...). IMO it would be worse to try to move both of the early exits above

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree this feels a little clunky, but the point about the else here being equivalent to the default case of a switch is why I think the current layout is fine. And there are enough comments here to understand why we're setting the different variables.

@wrotki wrotki requested review from thetruestblue and yln September 17, 2025 00:03
@ndrewh ndrewh requested a review from DanBlackwell September 17, 2025 00:42
Copy link
Contributor

@DanBlackwell DanBlackwell left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm happy with this now. I agree with @wrotki that the address walk feels 'tricky', but I think it's a tricky problem - I'm happy to stick with the current implementation, but let's wait for @wrotki final opinion.

@ndrewh ndrewh changed the title [sanitizer-common] Improve mach_vm_region_recurse error handling [sanitizer-common][Darwin] Improve mach_vm_region_recurse error handling Sep 17, 2025
@wrotki
Copy link
Contributor

wrotki commented Sep 17, 2025

Yeah OK, let's go with it. This function actually returns early in the happy case, and continues until exhausting all possibilities when it fails, so handling positive case on top is actually in line with 'early returns' principle.

Copy link
Contributor

@wrotki wrotki left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@wrotki wrotki merged commit 8fb02fa into llvm:main Sep 17, 2025
9 checks passed
Copy link

@ndrewh Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants