scudo: Add a dump of primary allocation sizes to malloc_info output.

This will be useful for optimizing the size class map.

Differential Revision: https://reviews.llvm.org/D74098

GitOrigin-RevId: 9068766b9a523350060f0817c7f50df09de3a69c
diff --git a/tests/wrappers_c_test.cpp b/tests/wrappers_c_test.cpp
index 976ac4f..d4ba7d7 100644
--- a/tests/wrappers_c_test.cpp
+++ b/tests/wrappers_c_test.cpp
@@ -303,7 +303,11 @@
 #if !SCUDO_FUCHSIA
 
 TEST(ScudoWrappersCTest, MallocInfo) {
-  char Buffer[64];
+  // Use volatile so that the allocations don't get optimized away.
+  void *volatile P1 = malloc(1234);
+  void *volatile P2 = malloc(4321);
+
+  char Buffer[16384];
   FILE *F = fmemopen(Buffer, sizeof(Buffer), "w+");
   EXPECT_NE(F, nullptr);
   errno = 0;
@@ -311,6 +315,11 @@
   EXPECT_EQ(errno, 0);
   fclose(F);
   EXPECT_EQ(strncmp(Buffer, "<malloc version=\"scudo-", 23), 0);
+  EXPECT_NE(nullptr, strstr(Buffer, "<alloc size=\"1234\" count=\""));
+  EXPECT_NE(nullptr, strstr(Buffer, "<alloc size=\"4321\" count=\""));
+
+  free(P1);
+  free(P2);
 }
 
 TEST(ScudoWrappersCTest, Fork) {
diff --git a/wrappers_c.inc b/wrappers_c.inc
index 555f17d..5721b01 100644
--- a/wrappers_c.inc
+++ b/wrappers_c.inc
@@ -180,8 +180,23 @@
 }
 
 INTERFACE WEAK int SCUDO_PREFIX(malloc_info)(UNUSED int options, FILE *stream) {
-  fputs("<malloc version=\"scudo-1\">", stream);
-  fputs("</malloc>", stream);
+  const scudo::uptr max_size =
+      decltype(SCUDO_ALLOCATOR)::PrimaryT::SizeClassMap::MaxSize;
+  auto *sizes =
+      static_cast<scudo::uptr *>(calloc(max_size, sizeof(scudo::uptr)));
+  auto callback = [](uintptr_t, size_t size, void* arg) {
+    auto *sizes = reinterpret_cast<scudo::uptr *>(arg);
+    if (size < max_size)
+      sizes[size]++;
+  };
+  SCUDO_ALLOCATOR.iterateOverChunks(0, -1ul, callback, sizes);
+
+  fputs("<malloc version=\"scudo-1\">\n", stream);
+  for (scudo::uptr i = 0; i != max_size; ++i)
+    if (sizes[i])
+      fprintf(stream, "<alloc size=\"%lu\" count=\"%lu\"/>\n", i, sizes[i]);
+  fputs("</malloc>\n", stream);
+  free(sizes);
   return 0;
 }