[libc-commits] [PATCH] D150846: [libc] Add a functioning realloc for hermetic tests.

Siva Chandra via Phabricator via libc-commits libc-commits at lists.llvm.org
Wed May 17 23:55:10 PDT 2023


sivachandra created this revision.
sivachandra added a reviewer: jhuber6.
Herald added subscribers: libc-commits, ecnelises, tschuett.
Herald added projects: libc-project, All.
sivachandra requested review of this revision.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D150846

Files:
  libc/test/UnitTest/HermeticTestUtils.cpp
  libc/test/src/__support/CPP/CMakeLists.txt


Index: libc/test/src/__support/CPP/CMakeLists.txt
===================================================================
--- libc/test/src/__support/CPP/CMakeLists.txt
+++ libc/test/src/__support/CPP/CMakeLists.txt
@@ -101,8 +101,6 @@
 
 add_libc_test(
   string_test
-  # This test relies on 'realloc' which is not implemented for hermetic tests.
-  UNIT_TEST_ONLY
   SUITE
     libc-cpp-utils-tests
   SRCS
Index: libc/test/UnitTest/HermeticTestUtils.cpp
===================================================================
--- libc/test/UnitTest/HermeticTestUtils.cpp
+++ libc/test/UnitTest/HermeticTestUtils.cpp
@@ -74,9 +74,20 @@
 
 void free(void *) {}
 
-void *realloc(void *ptr, size_t s) {
-  free(ptr);
-  return malloc(s);
+void *realloc(void *mem, size_t s) {
+  if (mem == nullptr)
+    return malloc(s);
+  uint8_t *newmem = reinterpret_cast<uint8_t *>(malloc(s));
+  if (newmem == nullptr)
+    return nullptr;
+  uint8_t *oldmem = reinterpret_cast<uint8_t *>(mem);
+  // We use a simple for loop to copy the data over.
+  // If |s| is less the previous alloc size, the copy works as expected.
+  // If |s| is greater than the previous alloc size, then garbage is copied
+  // over to the additional part in the new memory block.
+  for (size_t i = 0; i < s; ++i)
+    newmem[i] = oldmem[i];
+  return newmem;
 }
 
 // The unit test framework uses pure virtual functions. Since hermetic tests


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D150846.523281.patch
Type: text/x-patch
Size: 1404 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libc-commits/attachments/20230518/3850596e/attachment.bin>


More information about the libc-commits mailing list