[compiler-rt] [ASan][Darwin][GCD] Add interceptor for dispatch_apply (PR #149238)

Julian Lettner via llvm-commits llvm-commits at lists.llvm.org
Tue Jul 22 11:06:58 PDT 2025


================
@@ -0,0 +1,49 @@
+// Bugs caught within missing GCD dispatch blocks result in thread being reported as T-1
+// with an empty stack.
+// This tests that dispatch_apply blocks can capture valid thread number and stack.
+
+// RUN: %clang_asan -DDISPATCH_APPLY_F %s -o %t
+// RUN: not %run %t 2>&1 | FileCheck %s
+
+// RUN: %clang_asan %s -o %t
+// RUN: not %run %t 2>&1 | FileCheck %s
+
+#include <dispatch/dispatch.h>
+#include <stdlib.h>
+
+__attribute__((noinline)) void access_memory_frame(char *x) { *x = 0; }
+
+__attribute__((noinline)) void test_dispatch_apply() {
+  char *x = (char *)malloc(4);
+  dispatch_apply(8, dispatch_get_global_queue(0, 0), ^(size_t i) {
+    access_memory_frame(&x[i]);
+  });
+}
+
+typedef struct {
+  char *data;
+} Context;
+
+void da_func(void *ctx, size_t i) {
+  Context *c = (Context *)ctx;
+  access_memory_frame(&c->data[i]);
+}
+
+__attribute__((noinline)) void test_dispatch_apply_f() {
+  Context *ctx = (Context *)malloc(sizeof(Context));
+  ctx->data = (char *)malloc(4);
+  dispatch_apply_f(8, dispatch_get_global_queue(0, 0), ctx, da_func);
+}
+
+int main(int argc, const char *argv[]) {
+#if DISPATCH_APPLY_F
+  test_dispatch_apply_f();
+#else
+  test_dispatch_apply();
+#endif
----------------
yln wrote:

Nit: consider compiling the test only once and branching on a program argument.  We can also use an additional CHECK directive to ensure we are doing both sides.
(Not tested, please double-check it does the right thing)

```
if (strcmp(argv[1], "func") == 0) {
  fprintf(stderr, "Test dispatch_apply with function\n");
  // CHECK-FUNC: dispatch_apply with function
  test_dispatch_apply_f();
} else if (strcmp(argv[1], "block") == 0) {
  fprintf(stderr, "Test dispatch_apply with block\n");
  // CHECK-BLOCK: dispatch_apply with block
  test_dispatch_apply();
} else {
  abort();
}
```

Build & run:
```
// RUN: %clang_asan %s -o %t
// RUN: not %run %t func   2>&1 | FileCheck %s --check-prefixes=CHECK,CHECK-FUNC
// RUN: not %run %t block  2>&1 | FileCheck %s --check-prefixes=CHECK,CHECK-BLOCK
```


https://github.com/llvm/llvm-project/pull/149238


More information about the llvm-commits mailing list