Heap.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /*******************************************************************************
  2. * Copyright (c) 2009, 2020 IBM Corp.
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v2.0
  6. * and Eclipse Distribution License v1.0 which accompany this distribution.
  7. *
  8. * The Eclipse Public License is available at
  9. * https://www.eclipse.org/legal/epl-2.0/
  10. * and the Eclipse Distribution License is available at
  11. * http://www.eclipse.org/org/documents/edl-v10.php.
  12. *
  13. * Contributors:
  14. * Ian Craggs - initial API and implementation and/or initial documentation
  15. * Ian Craggs - use tree data structure instead of list
  16. * Ian Craggs - change roundup to Heap_roundup to avoid macro name clash on MacOSX
  17. *******************************************************************************/
  18. /**
  19. * @file
  20. * \brief functions to manage the heap with the goal of eliminating memory leaks
  21. *
  22. * For any module to use these functions transparently, simply include the Heap.h
  23. * header file. Malloc and free will be redefined, but will behave in exactly the same
  24. * way as normal, so no recoding is necessary.
  25. *
  26. * */
  27. #include "Tree.h"
  28. #include "Log.h"
  29. #include "StackTrace.h"
  30. #include "Thread.h"
  31. #if defined(HEAP_UNIT_TESTS)
  32. char* Broker_recordFFDC(char* symptoms);
  33. #endif /* HEAP_UNIT_TESTS */
  34. #include <stdlib.h>
  35. #include <string.h>
  36. #include <stdio.h>
  37. #include <stddef.h>
  38. #include "Heap.h"
  39. #if !defined(NO_HEAP_TRACKING)
  40. #undef malloc
  41. #undef realloc
  42. #undef free
  43. #if defined(_WIN32) || defined(_WIN64)
  44. mutex_type heap_mutex;
  45. #else
  46. static pthread_mutex_t heap_mutex_store = PTHREAD_MUTEX_INITIALIZER;
  47. static mutex_type heap_mutex = &heap_mutex_store;
  48. #endif
  49. static heap_info state = {0, 0}; /**< global heap state information */
  50. typedef double eyecatcherType;
  51. static eyecatcherType eyecatcher = (eyecatcherType)0x8888888888888888;
  52. /*#define HEAP_STACK 1 */
  53. /**
  54. * Each item on the heap is recorded with this structure.
  55. */
  56. typedef struct
  57. {
  58. char* file; /**< the name of the source file where the storage was allocated */
  59. int line; /**< the line no in the source file where it was allocated */
  60. void* ptr; /**< pointer to the allocated storage */
  61. size_t size; /**< size of the allocated storage */
  62. #if defined(HEAP_STACK)
  63. char* stack;
  64. #endif
  65. } storageElement;
  66. static Tree heap; /**< Tree that holds the allocation records */
  67. static const char *errmsg = "Memory allocation error";
  68. static size_t Heap_roundup(size_t size);
  69. static int ptrCompare(void* a, void* b, int value);
  70. /*static void Heap_check(char* string, void* ptr);*/
  71. static void checkEyecatchers(char* file, int line, void* p, size_t size);
  72. static int Internal_heap_unlink(char* file, int line, void* p);
  73. static void HeapScan(enum LOG_LEVELS log_level);
  74. /**
  75. * Round allocation size up to a multiple of the size of an int. Apart from possibly reducing fragmentation,
  76. * on the old v3 gcc compilers I was hitting some weird behaviour, which might have been errors in
  77. * sizeof() used on structures and related to packing. In any case, this fixes that too.
  78. * @param size the size actually needed
  79. * @return the rounded up size
  80. */
  81. static size_t Heap_roundup(size_t size)
  82. {
  83. static int multsize = 4*sizeof(int);
  84. if (size % multsize != 0)
  85. size += multsize - (size % multsize);
  86. return size;
  87. }
  88. /**
  89. * List callback function for comparing storage elements
  90. * @param a pointer to the current content in the tree (storageElement*)
  91. * @param b pointer to the memory to free
  92. * @return boolean indicating whether a and b are equal
  93. */
  94. static int ptrCompare(void* a, void* b, int value)
  95. {
  96. a = ((storageElement*)a)->ptr;
  97. if (value)
  98. b = ((storageElement*)b)->ptr;
  99. return (a > b) ? -1 : (a == b) ? 0 : 1;
  100. }
  101. /*
  102. static void Heap_check(char* string, void* ptr)
  103. {
  104. Node* curnode = NULL;
  105. storageElement* prev, *s = NULL;
  106. printf("Heap_check start %p\n", ptr);
  107. while ((curnode = TreeNextElement(&heap, curnode)) != NULL)
  108. {
  109. prev = s;
  110. s = (storageElement*)(curnode->content);
  111. if (prev)
  112. {
  113. if (ptrCompare(s, prev, 1) != -1)
  114. {
  115. printf("%s: heap order error %d %p %p\n", string, ptrCompare(s, prev, 1), prev->ptr, s->ptr);
  116. exit(99);
  117. }
  118. else
  119. printf("%s: heap order good %d %p %p\n", string, ptrCompare(s, prev, 1), prev->ptr, s->ptr);
  120. }
  121. }
  122. }*/
  123. /**
  124. * Allocates a block of memory. A direct replacement for malloc, but keeps track of items
  125. * allocated in a list, so that free can check that a item is being freed correctly and that
  126. * we can check that all memory is freed at shutdown.
  127. * @param file use the __FILE__ macro to indicate which file this item was allocated in
  128. * @param line use the __LINE__ macro to indicate which line this item was allocated at
  129. * @param size the size of the item to be allocated
  130. * @return pointer to the allocated item, or NULL if there was an error
  131. */
  132. void* mymalloc(char* file, int line, size_t size)
  133. {
  134. storageElement* s = NULL;
  135. size_t space = sizeof(storageElement);
  136. size_t filenamelen = strlen(file)+1;
  137. void* rc = NULL;
  138. Thread_lock_mutex(heap_mutex);
  139. size = Heap_roundup(size);
  140. if ((s = malloc(sizeof(storageElement))) == NULL)
  141. {
  142. Log(LOG_ERROR, 13, errmsg);
  143. goto exit;
  144. }
  145. memset(s, 0, sizeof(storageElement));
  146. s->size = size; /* size without eyecatchers */
  147. if ((s->file = malloc(filenamelen)) == NULL)
  148. {
  149. Log(LOG_ERROR, 13, errmsg);
  150. free(s);
  151. goto exit;
  152. }
  153. memset(s->file, 0, sizeof(filenamelen));
  154. space += filenamelen;
  155. strcpy(s->file, file);
  156. #if defined(HEAP_STACK)
  157. #define STACK_LEN 300
  158. if ((s->stack = malloc(STACK_LEN)) == NULL)
  159. {
  160. Log(LOG_ERROR, 13, errmsg);
  161. free(s->file);
  162. free(s);
  163. goto exit;
  164. }
  165. memset(s->stack, 0, sizeof(filenamelen));
  166. StackTrace_get(Thread_getid(), s->stack, STACK_LEN);
  167. #endif
  168. s->line = line;
  169. /* Add space for eyecatcher at each end */
  170. if ((s->ptr = malloc(size + 2*sizeof(eyecatcherType))) == NULL)
  171. {
  172. Log(LOG_ERROR, 13, errmsg);
  173. free(s->file);
  174. free(s);
  175. goto exit;
  176. }
  177. memset(s->ptr, 0, size + 2*sizeof(eyecatcherType));
  178. space += size + 2*sizeof(eyecatcherType);
  179. *(eyecatcherType*)(s->ptr) = eyecatcher; /* start eyecatcher */
  180. *(eyecatcherType*)(((char*)(s->ptr)) + (sizeof(eyecatcherType) + size)) = eyecatcher; /* end eyecatcher */
  181. Log(TRACE_MAX, -1, "Allocating %d bytes in heap at file %s line %d ptr %p\n", (int)size, file, line, s->ptr);
  182. TreeAdd(&heap, s, space);
  183. state.current_size += size;
  184. if (state.current_size > state.max_size)
  185. state.max_size = state.current_size;
  186. rc = ((eyecatcherType*)(s->ptr)) + 1; /* skip start eyecatcher */
  187. exit:
  188. Thread_unlock_mutex(heap_mutex);
  189. return rc;
  190. }
  191. static void checkEyecatchers(char* file, int line, void* p, size_t size)
  192. {
  193. eyecatcherType *sp = (eyecatcherType*)p;
  194. char *cp = (char*)p;
  195. eyecatcherType us;
  196. static const char *msg = "Invalid %s eyecatcher %d in heap item at file %s line %d";
  197. if ((us = *--sp) != eyecatcher)
  198. Log(LOG_ERROR, 13, msg, "start", us, file, line);
  199. cp += size;
  200. if ((us = *(eyecatcherType*)cp) != eyecatcher)
  201. Log(LOG_ERROR, 13, msg, "end", us, file, line);
  202. }
  203. /**
  204. * Remove an item from the recorded heap without actually freeing it.
  205. * Use sparingly!
  206. * @param file use the __FILE__ macro to indicate which file this item was allocated in
  207. * @param line use the __LINE__ macro to indicate which line this item was allocated at
  208. * @param p pointer to the item to be removed
  209. */
  210. static int Internal_heap_unlink(char* file, int line, void* p)
  211. {
  212. Node* e = NULL;
  213. int rc = 0;
  214. e = TreeFind(&heap, ((eyecatcherType*)p)-1);
  215. if (e == NULL)
  216. Log(LOG_ERROR, 13, "Failed to remove heap item at file %s line %d", file, line);
  217. else
  218. {
  219. storageElement* s = (storageElement*)(e->content);
  220. Log(TRACE_MAX, -1, "Freeing %d bytes in heap at file %s line %d, heap use now %d bytes\n",
  221. (int)s->size, file, line, (int)state.current_size);
  222. checkEyecatchers(file, line, p, s->size);
  223. /* free(s->ptr); */
  224. free(s->file);
  225. state.current_size -= s->size;
  226. TreeRemoveNodeIndex(&heap, e, 0);
  227. free(s);
  228. rc = 1;
  229. }
  230. return rc;
  231. }
  232. /**
  233. * Frees a block of memory. A direct replacement for free, but checks that a item is in
  234. * the allocates list first.
  235. * @param file use the __FILE__ macro to indicate which file this item was allocated in
  236. * @param line use the __LINE__ macro to indicate which line this item was allocated at
  237. * @param p pointer to the item to be freed
  238. */
  239. void myfree(char* file, int line, void* p)
  240. {
  241. if (p) /* it is legal und usual to call free(NULL) */
  242. {
  243. Thread_lock_mutex(heap_mutex);
  244. if (Internal_heap_unlink(file, line, p))
  245. free(((eyecatcherType*)p)-1);
  246. Thread_unlock_mutex(heap_mutex);
  247. }
  248. else
  249. {
  250. Log(LOG_ERROR, -1, "Call of free(NULL) in %s,%d",file,line);
  251. }
  252. }
  253. /**
  254. * Remove an item from the recorded heap without actually freeing it.
  255. * Use sparingly!
  256. * @param file use the __FILE__ macro to indicate which file this item was allocated in
  257. * @param line use the __LINE__ macro to indicate which line this item was allocated at
  258. * @param p pointer to the item to be removed
  259. */
  260. void Heap_unlink(char* file, int line, void* p)
  261. {
  262. Thread_lock_mutex(heap_mutex);
  263. Internal_heap_unlink(file, line, p);
  264. Thread_unlock_mutex(heap_mutex);
  265. }
  266. /**
  267. * Reallocates a block of memory. A direct replacement for realloc, but keeps track of items
  268. * allocated in a list, so that free can check that a item is being freed correctly and that
  269. * we can check that all memory is freed at shutdown.
  270. * We have to remove the item from the tree, as the memory is in order and so it needs to
  271. * be reinserted in the correct place.
  272. * @param file use the __FILE__ macro to indicate which file this item was reallocated in
  273. * @param line use the __LINE__ macro to indicate which line this item was reallocated at
  274. * @param p pointer to the item to be reallocated
  275. * @param size the new size of the item
  276. * @return pointer to the allocated item, or NULL if there was an error
  277. */
  278. void *myrealloc(char* file, int line, void* p, size_t size)
  279. {
  280. void* rc = NULL;
  281. storageElement* s = NULL;
  282. Thread_lock_mutex(heap_mutex);
  283. s = TreeRemoveKey(&heap, ((eyecatcherType*)p)-1);
  284. if (s == NULL)
  285. Log(LOG_ERROR, 13, "Failed to reallocate heap item at file %s line %d", file, line);
  286. else
  287. {
  288. size_t space = sizeof(storageElement);
  289. size_t filenamelen = strlen(file)+1;
  290. checkEyecatchers(file, line, p, s->size);
  291. size = Heap_roundup(size);
  292. state.current_size += size - s->size;
  293. if (state.current_size > state.max_size)
  294. state.max_size = state.current_size;
  295. if ((s->ptr = realloc(s->ptr, size + 2*sizeof(eyecatcherType))) == NULL)
  296. {
  297. Log(LOG_ERROR, 13, errmsg);
  298. goto exit;
  299. }
  300. space += size + 2*sizeof(eyecatcherType) - s->size;
  301. *(eyecatcherType*)(s->ptr) = eyecatcher; /* start eyecatcher */
  302. *(eyecatcherType*)(((char*)(s->ptr)) + (sizeof(eyecatcherType) + size)) = eyecatcher; /* end eyecatcher */
  303. s->size = size;
  304. space -= strlen(s->file);
  305. s->file = realloc(s->file, filenamelen);
  306. space += filenamelen;
  307. strcpy(s->file, file);
  308. s->line = line;
  309. rc = s->ptr;
  310. TreeAdd(&heap, s, space);
  311. }
  312. exit:
  313. Thread_unlock_mutex(heap_mutex);
  314. return (rc == NULL) ? NULL : ((eyecatcherType*)(rc)) + 1; /* skip start eyecatcher */
  315. }
  316. /**
  317. * Utility to find an item in the heap. Lets you know if the heap already contains
  318. * the memory location in question.
  319. * @param p pointer to a memory location
  320. * @return pointer to the storage element if found, or NULL
  321. */
  322. void* Heap_findItem(void* p)
  323. {
  324. Node* e = NULL;
  325. Thread_lock_mutex(heap_mutex);
  326. e = TreeFind(&heap, ((eyecatcherType*)p)-1);
  327. Thread_unlock_mutex(heap_mutex);
  328. return (e == NULL) ? NULL : e->content;
  329. }
  330. /**
  331. * Scans the heap and reports any items currently allocated.
  332. * To be used at shutdown if any heap items have not been freed.
  333. */
  334. static void HeapScan(enum LOG_LEVELS log_level)
  335. {
  336. Node* current = NULL;
  337. Thread_lock_mutex(heap_mutex);
  338. Log(log_level, -1, "Heap scan start, total %d bytes", (int)state.current_size);
  339. while ((current = TreeNextElement(&heap, current)) != NULL)
  340. {
  341. storageElement* s = (storageElement*)(current->content);
  342. Log(log_level, -1, "Heap element size %d, line %d, file %s, ptr %p", (int)s->size, s->line, s->file, s->ptr);
  343. Log(log_level, -1, " Content %.*s", (10 > current->size) ? (int)s->size : 10, (char*)(((eyecatcherType*)s->ptr) + 1));
  344. #if defined(HEAP_STACK)
  345. Log(log_level, -1, " Stack:\n%s", s->stack);
  346. #endif
  347. }
  348. Log(log_level, -1, "Heap scan end");
  349. Thread_unlock_mutex(heap_mutex);
  350. }
  351. /**
  352. * Heap initialization.
  353. */
  354. int Heap_initialize(void)
  355. {
  356. TreeInitializeNoMalloc(&heap, ptrCompare);
  357. heap.heap_tracking = 0; /* no recursive heap tracking! */
  358. return 0;
  359. }
  360. /**
  361. * Heap termination.
  362. */
  363. void Heap_terminate(void)
  364. {
  365. Log(TRACE_MIN, -1, "Maximum heap use was %d bytes", (int)state.max_size);
  366. if (state.current_size > 20) /* One log list is freed after this function is called */
  367. {
  368. Log(LOG_ERROR, -1, "Some memory not freed at shutdown, possible memory leak");
  369. HeapScan(LOG_ERROR);
  370. }
  371. }
  372. /**
  373. * Access to heap state
  374. * @return pointer to the heap state structure
  375. */
  376. heap_info* Heap_get_info(void)
  377. {
  378. return &state;
  379. }
  380. /**
  381. * Dump a string from the heap so that it can be displayed conveniently
  382. * @param file file handle to dump the heap contents to
  383. * @param str the string to dump, could be NULL
  384. */
  385. int HeapDumpString(FILE* file, char* str)
  386. {
  387. int rc = 0;
  388. size_t len = str ? strlen(str) + 1 : 0; /* include the trailing null */
  389. if (fwrite(&(str), sizeof(char*), 1, file) != 1)
  390. rc = -1;
  391. else if (fwrite(&(len), sizeof(int), 1 ,file) != 1)
  392. rc = -1;
  393. else if (len > 0 && fwrite(str, len, 1, file) != 1)
  394. rc = -1;
  395. return rc;
  396. }
  397. /**
  398. * Dump the state of the heap
  399. * @param file file handle to dump the heap contents to
  400. */
  401. int HeapDump(FILE* file)
  402. {
  403. int rc = 0;
  404. Node* current = NULL;
  405. while (rc == 0 && (current = TreeNextElement(&heap, current)))
  406. {
  407. storageElement* s = (storageElement*)(current->content);
  408. if (fwrite(&(s->ptr), sizeof(s->ptr), 1, file) != 1)
  409. rc = -1;
  410. else if (fwrite(&(current->size), sizeof(current->size), 1, file) != 1)
  411. rc = -1;
  412. else if (fwrite(s->ptr, current->size, 1, file) != 1)
  413. rc = -1;
  414. }
  415. return rc;
  416. }
  417. #endif
  418. #if defined(HEAP_UNIT_TESTS)
  419. void Log(enum LOG_LEVELS log_level, int msgno, char* format, ...)
  420. {
  421. printf("Log %s", format);
  422. }
  423. char* Broker_recordFFDC(char* symptoms)
  424. {
  425. printf("recordFFDC");
  426. return "";
  427. }
  428. #define malloc(x) mymalloc(__FILE__, __LINE__, x)
  429. #define realloc(a, b) myrealloc(__FILE__, __LINE__, a, b)
  430. #define free(x) myfree(__FILE__, __LINE__, x)
  431. int main(int argc, char *argv[])
  432. {
  433. char* h = NULL;
  434. Heap_initialize();
  435. h = malloc(12);
  436. free(h);
  437. printf("freed h\n");
  438. h = malloc(12);
  439. h = realloc(h, 14);
  440. h = realloc(h, 25);
  441. h = realloc(h, 255);
  442. h = realloc(h, 2225);
  443. h = realloc(h, 22225);
  444. printf("freeing h\n");
  445. free(h);
  446. Heap_terminate();
  447. printf("Finishing\n");
  448. return 0;
  449. }
  450. #endif /* HEAP_UNIT_TESTS */
  451. /* Local Variables: */
  452. /* indent-tabs-mode: t */
  453. /* c-basic-offset: 8 */
  454. /* End: */