1 /* Copyright (c) 2012-2019. 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"
8 #include "xbt/mmalloc.h"
18 XBT_LOG_NEW_DEFAULT_CATEGORY(test,"this test");
20 constexpr int BUFFSIZE = 204800;
21 constexpr int TESTSIZE = 100;
23 #define size_of_block(i) (((i % 50)+1)* 100)
25 static void check_block(const unsigned char* p, unsigned char b, int n)
27 for (int i = 0; i < n; i++)
29 xbt_die("value mismatch: %p[%d] = %#hhx, expected %#hhx", p, i, p[i], b);
32 int main(int argc, char**argv)
34 xbt_mheap_t heapA = nullptr;
35 void *pointers[TESTSIZE];
38 XBT_INFO("Allocating a new heap");
39 unsigned long mask = ~((unsigned long)xbt_pagesize - 1);
40 void *addr = (void*)(((unsigned long)sbrk(0) + BUFFSIZE) & mask);
41 heapA = xbt_mheap_new(-1, addr);
43 perror("attach 1 failed");
44 fprintf(stderr, "bye\n");
48 XBT_INFO("HeapA allocated");
52 for (i = 0; i < TESTSIZE; i++) {
53 size = size_of_block(i);
54 pointers[i] = mmalloc(heapA, size);
55 XBT_INFO("%d bytes allocated with offset %zx", size, (size_t)((char*)pointers[i] - (char*)heapA));
57 XBT_INFO("All blocks were correctly allocated. Free every second block");
58 for (i = 0; i < TESTSIZE; i+=2) {
59 mfree(heapA, pointers[i]);
61 XBT_INFO("Memset every second block to zero (yeah, they are not currently allocated :)");
62 for (i = 0; i < TESTSIZE; i+=2) {
63 size = size_of_block(i);
64 memset(pointers[i],0, size);
66 XBT_INFO("Re-allocate every second block");
67 for (i = 0; i < TESTSIZE; i+=2) {
68 size = size_of_block(i);
69 pointers[i] = mmalloc(heapA, size);
72 XBT_INFO("free all blocks (each one twice, to check that double free are correctly catched)");
73 for (i = 0; i < TESTSIZE; i++) {
75 mfree(heapA, pointers[i]);
77 mfree(heapA, pointers[i]);
78 } catch (const xbt_ex&) {
82 xbt_die("FAIL: A double-free went undetected (for size:%d)",size_of_block(i));
85 XBT_INFO("free again all blocks (to really check that double free are correctly catched)");
86 for (i = 0; i < TESTSIZE; i++) {
89 mfree(heapA, pointers[i]);
90 } catch (const xbt_ex&) {
94 xbt_die("FAIL: A double-free went undetected (for size:%d)",size_of_block(i));
97 XBT_INFO("Let's try different codepaths for mrealloc");
98 for (i = 0; i < TESTSIZE; i++) {
99 const std::vector<std::pair<int, unsigned char>> requests = {
100 {size_of_block(i) / 2, 0x77}, {size_of_block(i) * 2, 0xaa}, {1, 0xc0}, {0, 0}};
101 pointers[i] = nullptr;
102 for (unsigned k = 0; k < requests.size(); ++k) {
103 size = requests[k].first;
104 pointers[i] = mrealloc(heapA, pointers[i], size);
106 check_block(static_cast<unsigned char*>(pointers[i]), requests[k - 1].second,
107 std::min(size, requests[k - 1].first));
109 memset(pointers[i], requests[k].second, size);
113 XBT_INFO("Damnit, I cannot break mmalloc this time. That's SO disappointing.");