[compiler-rt] [ASan] return 0 for current allocated bytes if malloc/free are never happend (PR #67394)

via llvm-commits llvm-commits at lists.llvm.org
Tue Sep 26 06:03:58 PDT 2023


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

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

<details>
<summary>Changes</summary>

This is found during address sanitizer enablement on AIX.

On platforms that has no malloc/free calls before user's malloc/free calls, `__sanitizer_get_current_allocated_bytes()` should return 0. Otherwise the case like `compiler-rt/test/sanitizer_common/TestCases/allocator_interface.cpp` will fail at below scenario:
```
void Test(int size) { 
  auto allocated_bytes_before = __sanitizer_get_current_allocated_bytes();
  int *p = (int *)malloc(size);

  assert(__sanitizer_get_current_allocated_bytes() >=
         size + allocated_bytes_before);   // if allocated_bytes_before is 1, this assert will fail. allocated_bytes_before should be 0
}
```

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


2 Files Affected:

- (modified) compiler-rt/lib/asan/asan_stats.cpp (+2-2) 
- (modified) compiler-rt/test/asan/TestCases/Posix/current_allocated_bytes.cpp (+1-1) 


``````````diff
diff --git a/compiler-rt/lib/asan/asan_stats.cpp b/compiler-rt/lib/asan/asan_stats.cpp
index 9a715ea76fee756..78cb30ec763d818 100644
--- a/compiler-rt/lib/asan/asan_stats.cpp
+++ b/compiler-rt/lib/asan/asan_stats.cpp
@@ -142,7 +142,7 @@ uptr __sanitizer_get_current_allocated_bytes() {
   uptr freed = stats.freed;
   // Return sane value if malloced < freed due to racy
   // way we update accumulated stats.
-  return (malloced > freed) ? malloced - freed : 1;
+  return (malloced > freed) ? malloced - freed : 0;
 }
 
 uptr __sanitizer_get_heap_size() {
@@ -161,7 +161,7 @@ uptr __sanitizer_get_free_bytes() {
                   + stats.malloced_redzones;
   // Return sane value if total_free < total_used due to racy
   // way we update accumulated stats.
-  return (total_free > total_used) ? total_free - total_used : 1;
+  return (total_free > total_used) ? total_free - total_used : 0;
 }
 
 uptr __sanitizer_get_unmapped_bytes() {
diff --git a/compiler-rt/test/asan/TestCases/Posix/current_allocated_bytes.cpp b/compiler-rt/test/asan/TestCases/Posix/current_allocated_bytes.cpp
index c49e433b1e8bfc6..7c83dc6106f3889 100644
--- a/compiler-rt/test/asan/TestCases/Posix/current_allocated_bytes.cpp
+++ b/compiler-rt/test/asan/TestCases/Posix/current_allocated_bytes.cpp
@@ -17,7 +17,7 @@ void* allocate(void *arg) {
 }
 
 void* check_stats(void *arg) {
-  assert(__sanitizer_get_current_allocated_bytes() > 0);
+  assert(__sanitizer_get_current_allocated_bytes() >= 0);
   return 0;
 }
 

``````````

</details>


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


More information about the llvm-commits mailing list