Allocator.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #ifndef Allocator_H
  16. #define Allocator_H
  17. #include "util/Identity.h"
  18. #include "util/Gcc.h"
  19. #include "util/Linker.h"
  20. Linker_require("memory/Allocator.c");
  21. /**
  22. * A handle which is provided in response to calls to Allocator_onFree().
  23. * This handle is sutable for use with Allocator_notOnFree() to cancel a job.
  24. */
  25. struct Allocator_OnFreeJob;
  26. typedef int (* Allocator_OnFreeCallback)(struct Allocator_OnFreeJob* job);
  27. struct Allocator_OnFreeJob
  28. {
  29. /** Set by caller. */
  30. Allocator_OnFreeCallback callback;
  31. void* userData;
  32. };
  33. /**
  34. * If an onFree job needs to complete asynchronously, it should return this,
  35. * then when it is complete it must call job->complete(job) on the OnFreeJob
  36. * which was passed to it.
  37. */
  38. #define Allocator_ONFREE_ASYNC 10000
  39. /**
  40. * Allocator for structured memory management.
  41. * The objective of the allocator structure is to make manual memory management easier, specifically
  42. * to make making a mistake difficult.
  43. *
  44. * Every function which allocates memory, either to return a structure or to do processing which
  45. * cannot be done on the stack takes an allocator as a parameter.
  46. *
  47. * In traditional C, each call to malloc() must be traced to a corresponding free() call, a
  48. * laborious process which can be partially automated but inevitably leaves some memory leak
  49. * investigative work to the developer. Allocator attempts to move the memory freeing operations
  50. * close to the memory allocations thus making bugs easy to spot without searching over large
  51. * amounts of code.
  52. *
  53. * With Allocator, you might do the following:
  54. *
  55. * struct Allocator* child = Allocator_child(myAlloc); <-- myAlloc is the one provided to you
  56. * potentiallyLeakyFunction(child);
  57. * Allocator_free(child);
  58. *
  59. * Given this simple pattern, as long as potentiallyLeakyFunction() did not bypass the allocator
  60. * system using malloc() directly, we can prove that it is not the source of a memory leak.
  61. * As the real code is far more complex than this contrived example, there are a few rules which
  62. * have proven useful in preventing both memory leaks and dangling pointers.
  63. *
  64. * #1 Do not create new root allocators, create child allocators instead.
  65. * When you call MallocAllocator_new() or equivalent, you are creating a parentless allocator and
  66. * you must take responsibility for it's freeing when you are finished with it. In cjdns there is
  67. * only one call to a main allocator and all other allocators are spawned from it using
  68. * Allocator_child().
  69. * Exception: In certain code which interfaces with libuv, an alternate root allocator is necessary
  70. * because libuv teardown process is asynchronous and memory used by libuv must not be freed
  71. * until this is complete.
  72. *
  73. * #2 Free your allocators and not anyone else's.
  74. * With precious few exceptions, an allocator is always freed in the same .c file where it was
  75. * created. It is obviously rude to destroy something of someone else's just as it is rude to leave
  76. * things lying around expecting someone else to clean up after you. Sometimes you want to "take
  77. * ownership" of some memory which somebody else allocated and they are passing to you. Rather
  78. * than slowly allocate your own memory and copy the data over, you can use Allocator_adopt() to
  79. * hold that memory in existance until you and the creator both are finished with it.
  80. *
  81. * #3 Assume that any allocator may be freed at any time.
  82. * A typical example is the ping message. When a ping is sent, a structure is allocated to hold
  83. * information about the ping so that when the response comes back it will be recognized. That
  84. * structure is inserted into a table of outstanding pings. If that allocator were freed while the
  85. * ping was outstanding, the response would come back and the table lookup would access freed
  86. * memory. To prevent this, every place where temporary memory is placed into a more permanent
  87. * structure (the table), Allocator_onFree() is used to hook the freeing of that memory and add a
  88. * function to remove the entry from the table.
  89. * Cjdns is notably lacking in "deregister" or "cancel" type functions as the accepted method of
  90. * deregistering a peer or cancelling an operation is by freeing the associated allocator, both
  91. * simplifying the code and avoiding bug prone "cold" codepaths.
  92. *
  93. * The function pointers in the allocator structure are best called through the associated macros.
  94. */
  95. struct Allocator
  96. {
  97. /** The name of the file where this allocator was created. */
  98. const char* fileName;
  99. /** The number of the line where this allocator was created. */
  100. int lineNum;
  101. /** Non-zero if allocator is currently freeing. */
  102. int isFreeing;
  103. };
  104. struct Allocator_Allocation
  105. {
  106. unsigned long size;
  107. };
  108. #define Allocator_Allocation_SIZE __SIZEOF_LONG__
  109. /**
  110. * Get a child of a given allocator.
  111. *
  112. * @param alloc the parent
  113. * @param childNumber
  114. * @return a child allocator or NULL if childNumber is out of range.
  115. */
  116. struct Allocator* Allocator_getChild(struct Allocator* alloc, int childNumber);
  117. /**
  118. * Get one of the allocations held by this allocator.
  119. *
  120. * @param alloc the allocator.
  121. * @param allocNum the number of the allocation.
  122. * @return an allocation or NULL if allocNum is out of range.
  123. */
  124. struct Allocator_Allocation* Allocator_getAllocation(struct Allocator* alloc, int allocNum);
  125. /**
  126. * Allocate some memory from this memory allocator.
  127. * The allocation will be aligned on the size of a pointer, if you need further alignment then
  128. * you must handle it manually.
  129. *
  130. * @param alloc the memory allocator.
  131. * @param size the number of bytes to allocate.
  132. * @return a pointer to the newly allocated memory.
  133. * @see malloc()
  134. */
  135. Gcc_ALLOC_SIZE(2)
  136. void* Allocator__malloc(struct Allocator* allocator,
  137. unsigned long length,
  138. const char* fileName,
  139. int lineNum);
  140. #define Allocator_malloc(a, b) Allocator__malloc((a),(b),Gcc_SHORT_FILE,Gcc_LINE)
  141. /**
  142. * Allocate some memory from this memory allocator.
  143. * The allocation will be aligned on the size of a pointer, if you need further alignment then
  144. * you must handle it manually.
  145. * Memory location will be filled with 0 bytes.
  146. *
  147. * @param alloc the memory allocator.
  148. * @param size the number of bytes per element.
  149. * @param count the number of elements in the allocation.
  150. * @return a pointer to the newly allocated memory.
  151. * @see calloc()
  152. */
  153. Gcc_ALLOC_SIZE(2,3)
  154. void* Allocator__calloc(struct Allocator* alloc,
  155. unsigned long length,
  156. unsigned long count,
  157. const char* fileName,
  158. int lineNum);
  159. #define Allocator_calloc(a, b, c) Allocator__calloc((a),(b),(c),Gcc_SHORT_FILE,Gcc_LINE)
  160. /**
  161. * Re-allocate memory so that an allocation can be expanded.
  162. * The allocation will be aligned on the size of a pointer, if you need further alignment then
  163. * you must handle it manually.
  164. * Caution: Use of this function is not advisable with memory which is shared with other parts
  165. * of the system.
  166. *
  167. * @param alloc the allocator to allocate with, must be the same allocator which allocated orig.
  168. * @param orig a pointer to the original memory allocation which is to be reallocated.
  169. * if NULL, this function will behave exactly as Allocator_malloc().
  170. * @param size how much memory to allocate. If 0, this function will free the specific memory
  171. * without freeing the entire allocator.
  172. * @return a pointer to the newly allocated memory.
  173. */
  174. Gcc_ALLOC_SIZE(3)
  175. void* Allocator__realloc(struct Allocator* allocator,
  176. const void* original,
  177. unsigned long size,
  178. const char* fileName,
  179. int lineNum);
  180. #define Allocator_realloc(a, b, c) Allocator__realloc((a),(b),(c),Gcc_SHORT_FILE,Gcc_LINE)
  181. /**
  182. * Allocate some memory and copy something into that memory space.
  183. * The allocation will be aligned on the size of a pointer, if you need further alignment then
  184. * you must handle it manually.
  185. * Caution: if content is an expression, it will be evaluated twice.
  186. *
  187. * @param alloc the memory allocator.
  188. * @param content a pointer to something which will be cloned into the newly allocated memory.
  189. * the size of the new allocation will be sizeof(*content).
  190. * @return a pointer to the newly allocated memory.
  191. */
  192. Gcc_ALLOC_SIZE(3)
  193. void* Allocator__clone(struct Allocator* allocator,
  194. const void* toClone,
  195. unsigned long length,
  196. const char* fileName,
  197. int lineNum);
  198. #define Allocator_clone(a, b) Allocator__clone((a),(b),sizeof(*(b)),Gcc_SHORT_FILE,Gcc_LINE)
  199. /**
  200. * Spawn a new child of this allocator.
  201. * When this allocator is freed all of its children which have no surviving parent will also be
  202. * freed.
  203. *
  204. * @param alloc the memory allocator.
  205. * @return a child allocator.
  206. */
  207. struct Allocator* Allocator__child(struct Allocator* alloc, const char* fileName, int lineNum);
  208. #define Allocator_child(a) Allocator__child((a),Gcc_SHORT_FILE,Gcc_LINE)
  209. /**
  210. * Sever the link between an allocator and it's original parent.
  211. * If it has been adopted using Allocator_adopt() then the freeing of the allocator will be deferred
  212. * until the allocator returned by Allocator_adopt() has also been freed.
  213. * Any allocator which has no surviving parent allocator will be implicitly freed.
  214. * NOTE: This does not do what it seems to do, it does not necessarily *free* the allocator, it
  215. * only promises to cut the link to the allocator's normal parent, if the allocator has been
  216. * adopter then the adopted parent becomes the normal parent and then the allocator is not
  217. * freed even though you asked to free it!
  218. *
  219. * @param alloc the allocator to disconnect from it's parent.
  220. */
  221. void Allocator__free(struct Allocator* alloc, const char* file, int line);
  222. #define Allocator_free(a) Allocator__free((a),Gcc_SHORT_FILE,Gcc_LINE)
  223. /**
  224. * Add a function to be called when the allocator is freed.
  225. * There is no guarantee of which order the onFree jobs will be executed.
  226. *
  227. * @param alloc the memory allocator.
  228. * @param callback the function to call.
  229. * @return an Allocator_OnFreeJob which can be cancelled with Allocator_cancelOnFree().
  230. */
  231. struct Allocator_OnFreeJob* Allocator__onFree(struct Allocator* alloc,
  232. Allocator_OnFreeCallback callback,
  233. void* context,
  234. const char* file,
  235. int line);
  236. #define Allocator_onFree(a, b, c) Allocator__onFree((a), (b), (c), Gcc_SHORT_FILE, Gcc_LINE)
  237. /**
  238. * Remove a function which was registered with Allocator_onFree().
  239. *
  240. * @param job the return value from calling Allocator_onFree().
  241. * @return 0 if the job was found and removed, -1 otherwise.
  242. */
  243. int Allocator_cancelOnFree(struct Allocator_OnFreeJob* toRemove);
  244. /**
  245. * Tell the allocator that an asynchronous onFree() job has completed.
  246. *
  247. * @param job the return value from calling Allocator_onFree().
  248. */
  249. void Allocator_onFreeComplete(struct Allocator_OnFreeJob* onFreeJob);
  250. /**
  251. * Adopt an allocator.
  252. * This creates a child of parentAlloc which is an adopted parent of toAdopt.
  253. * When Allocator_free() is called on toAdopt or one of it's parents, it will not be freed until
  254. * Allocator_free() has also been called on the allocator newly returned by this function.
  255. * This function may be used multiple times.
  256. *
  257. * Caution: Do not free an allocator which you did not create, even after adopting it.
  258. *
  259. * Allocator_adopt(myAlloc, somebodyElsesAllocator);
  260. * asynchronousStuff();
  261. * .... some time later...
  262. * Allocator_free(somebodyElsesAllocator); <-- WRONG: you freed an allocator that is not yours.
  263. *
  264. *
  265. * struct Allocator* adoptedParent = Allocator_child(myAlloc);
  266. * Allocator_adopt(adoptedParent, somebodyElsesAllocator);
  267. * asynchronousStuff();
  268. * .... some time later...
  269. * Allocator_free(adoptedParent); <-- RIGHT
  270. *
  271. *
  272. * @param parentAlloc the allocator to create a child of.
  273. * @param toAdopt the allocator which should be adopted by the returned child allocator.
  274. */
  275. void Allocator__adopt(struct Allocator* parentAlloc,
  276. struct Allocator* alloc,
  277. const char* fileName,
  278. int lineNum);
  279. #define Allocator_adopt(a, b) Allocator__adopt((a),(b),Gcc_SHORT_FILE,Gcc_LINE)
  280. /**
  281. * Disown an allocator.
  282. *
  283. * Sever the link between an adopted parent allocator and the child which it has adopted.
  284. * If this causes the child allocator to disconnect from the tree entirely, it will be
  285. * freed.
  286. *
  287. * @param parentAlloc the parent which has adopted the child allocator.
  288. * @param childToDisown the child allocator which has been adopted.
  289. */
  290. void Allocator__disown(struct Allocator* parentAlloc,
  291. struct Allocator* allocToDisown,
  292. const char* fileName,
  293. int lineNum);
  294. #define Allocator_disown(a, b) Allocator__disown((a),(b),Gcc_SHORT_FILE,Gcc_LINE)
  295. /**
  296. * Set the heap protection canary for the next child allocator.
  297. * If heap protection canaries are enabled, they will be added at the beginning and end
  298. * of each memory allocation and checked during free and other operations. If one is corrupted
  299. * the program will be aborted to protect against security attacks and other faults.
  300. * By default the canaries are statically set but this allows the value to be changed so that
  301. * the value of the canaries is unpredictable in order to foil targetted attacks.
  302. */
  303. void Allocator_setCanary(struct Allocator* alloc, unsigned long value);
  304. /**
  305. * Get the number of bytes allocated by this allocator and all of it's children.
  306. */
  307. unsigned long Allocator_bytesAllocated(struct Allocator* allocator);
  308. /**
  309. * Dump a memory snapshot to stderr.
  310. *
  311. * @param alloc any allocator in the tree, the whole tree will be dumped.
  312. * @param includeAllocations if non-zero then the individual memory allocations will be printed.
  313. */
  314. void Allocator_snapshot(struct Allocator* alloc, int includeAllocations);
  315. /**
  316. * The underlying memory provider function which backs the allocator.
  317. * This function is roughly equivilant to realloc() API in that it is used for allocation,
  318. * reallocation and freeing but it also contains a context field which allows the provider
  319. * to store it's state in a non-global way and a group pointer.
  320. *
  321. * The group pointer is used to add memory to an allocation group. If the group pointer is set to
  322. * NULL, the provider is requested to begin a new group, if the group pointer is not null, it will
  323. * be set to an allocation which had previously been returned by the provider, in this case the
  324. * provider should internally group this allocation with the other as they will likely be freed
  325. * at the same time.
  326. *
  327. * @param ctx the context which was passed to Allocator_new() along with the provider.
  328. * @param original if this is NULL then the allocator is to provide a new allocation, otherwise it
  329. * should resize or free an existing allocation.
  330. * @param size if this is 0 then the allocator should free original and return NULL, if it is not
  331. * zero then original should be resized or created.
  332. * @param group if this is not NULL then the provider is being informed that the current allocation
  333. * and the allocation in group are likely to have the same life span and should be
  334. * colocated if it is logical to do so.
  335. */
  336. #ifndef Allocator_Provider_CONTEXT_TYPE
  337. #define Allocator_Provider_CONTEXT_TYPE void
  338. #endif
  339. Gcc_ALLOC_SIZE(3)
  340. typedef void* (* Allocator_Provider)(Allocator_Provider_CONTEXT_TYPE* ctx,
  341. struct Allocator_Allocation* original,
  342. unsigned long size,
  343. struct Allocator* group);
  344. struct Allocator* Allocator_new(unsigned long sizeLimit,
  345. Allocator_Provider provider,
  346. Allocator_Provider_CONTEXT_TYPE* providerContext,
  347. const char* fileName,
  348. int lineNum);
  349. #endif