OpenCilk / opencilk-project

Monorepo for the OpenCilk compiler. Forked from llvm/llvm-project and based on Tapir/LLVM.
Other
89 stars 29 forks source link

Cilksan reporting race condition with malloc/realloc/free #218

Closed bababuck closed 7 months ago

bababuck commented 9 months ago

Describe the bug

Cilksan is reporting a race condition for when I free memory allocated by malloc. I have a small working example. My malloc/realloc/free manual specifies safe for multithreading:

> man malloc
ATTRIBUTES
       For an explanation of the terms used in this section, see attributes(7).

       ┌─────────────────────┬───────────────┬─────────┐
       │Interface            │ Attribute     │ Value   │
       ├─────────────────────┼───────────────┼─────────┤
       │malloc(), free(),    │ Thread safety │ MT-Safe │
       │calloc(), realloc()  │               │         │
       └─────────────────────┴───────────────┴─────────┘

Maybe it has to do with reuse of addresses by malloc after free. I could also be wrong and this is a race condition, but I don't see how.

Expected behavior

No race conditions detected.

OpenCilk version

clang version 14.0.6 (https://github.com/OpenCilk/opencilk-project fc90ded2b090672f84c58d12d8d85cd999eb6c1a)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /software/OpenCilk/20.04/2.0.0//bin

Steps to reproduce (include relevant output)

cilksan.c

/**
 * Simple replicated case of CILKSAN wrongly reported memory race.
 */

#include <stdlib.h>
#include <cilk/cilk.h>

void test(int *arr, int count) {
  if (count == 0) {
    free(arr);
    return ;
  }

  cilk_scope {
    for (int i = 0; i < 15; ++i) {
      int *new_arr = malloc(10 * sizeof(int));
      new_arr = realloc(new_arr, 10 * sizeof(int));
      cilk_spawn test(new_arr, count - 1);
    }
  }
  return ;
}

int main(int argc, char *argv[]) {
  test(NULL, 1);
}
clang -std=gnu11 -Wall -fopencilk -fsanitize=cilk -DCILKSAN=1 -O3 -DNDEBUG -march=znver2  -o cilksan.exe cilksan.c
./cilksan.exe
Running Cilksan race detector.
Race detected on location 11d8b900
*     Free 4846c9 test cilksan.c
+     Call 484b40 test cilksan.c
+    Spawn 4847ba test cilksan.c
|*    Free 4846c9 test cilksan.c
|+    Call 484b40 test cilksan.c
|+   Spawn 4847ba test cilksan.c
\| Common calling context
 +    Call 484967 main cilksan.c

Cilksan detected 1 distinct races.
Cilksan suppressed 12 duplicate race reports.
neboat commented 9 months ago

Thanks for the report. I replicated the issue on my end, and I'll look into it.

neboat commented 9 months ago

This is indeed a bug. There's now a PR with a fix for it here: https://github.com/OpenCilk/productivity-tools/pull/41

neboat commented 7 months ago

This bug has been fixed in the latest release.