1 /* Copyright (c) 2012-2023. The SimGrid Team. All rights reserved. */
3 /* This program is free software; you can redistribute it and/or modify it
4 * under the terms of the license (GNU LGPL) which comes with this package. */
6 #include "simgrid/Exception.hpp"
7 #include "simgrid/engine.h"
8 #include "src/xbt/mmalloc/mmalloc.h"
21 XBT_LOG_NEW_DEFAULT_CATEGORY(test,"this test");
23 constexpr int BUFFSIZE = 204800;
24 constexpr int TESTSIZE = 100;
26 #define size_of_block(i) ((((i) % 50) + 1) * 100)
28 static void check_block(const unsigned char* p, unsigned char b, int n)
30 for (int i = 0; i < n; i++)
31 xbt_assert(p[i] == b, "value mismatch: %p[%d] = %#hhx, expected %#hhx", p, i, p[i], b);
34 int main(int argc, char**argv)
36 xbt_mheap_t heapA = nullptr;
37 std::array<void*, TESTSIZE> pointers;
38 simgrid_init(&argc, argv);
40 XBT_INFO("Allocating a new heap");
41 unsigned long mask = ~((unsigned long)xbt_pagesize - 1);
42 auto* addr = reinterpret_cast<void*>(((unsigned long)sbrk(0) + BUFFSIZE) & mask);
43 heapA = xbt_mheap_new(addr, 0);
44 if (heapA == nullptr) {
45 perror("attach 1 failed");
46 fprintf(stderr, "bye\n");
50 XBT_INFO("HeapA allocated");
54 for (i = 0; i < TESTSIZE; i++) {
55 size = size_of_block(i);
56 pointers[i] = mmalloc(heapA, size);
57 XBT_INFO("%d bytes allocated with offset %zx", size, (size_t)((char*)pointers[i] - (char*)heapA));
59 XBT_INFO("All blocks were correctly allocated. Free every second block");
60 for (i = 0; i < TESTSIZE; i+=2) {
61 mfree(heapA, pointers[i]);
63 XBT_INFO("Memset every second block to zero (yeah, they are not currently allocated :)");
64 for (i = 0; i < TESTSIZE; i+=2) {
65 size = size_of_block(i);
66 memset(pointers[i],0, size);
68 XBT_INFO("Re-allocate every second block");
69 for (i = 0; i < TESTSIZE; i+=2) {
70 size = size_of_block(i);
71 pointers[i] = mmalloc(heapA, size);
74 XBT_INFO("free all blocks");
75 for (i = 0; i < TESTSIZE; i++)
76 mfree(heapA, pointers[i]);
78 XBT_INFO("Let's try different codepaths for mrealloc");
79 for (i = 0; i < TESTSIZE; i++) {
80 const std::vector<std::pair<int, unsigned char>> requests = {
81 {size_of_block(i) / 2, 0x77}, {size_of_block(i) * 2, 0xaa}, {1, 0xc0}, {0, 0}};
82 pointers[i] = nullptr;
83 for (unsigned k = 0; k < requests.size(); ++k) {
84 size = requests[k].first;
85 pointers[i] = mrealloc(heapA, pointers[i], size);
87 check_block(static_cast<unsigned char*>(pointers[i]), requests[k - 1].second,
88 std::min(size, requests[k - 1].first));
90 memset(pointers[i], requests[k].second, size);
94 XBT_INFO("Damnit, I cannot break mmalloc this time. That's SO disappointing.");