Heap.c 14 KB

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