Allocator.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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 <http://www.gnu.org/licenses/>.
  14. */
  15. #include "memory/Allocator.h"
  16. #include "memory/Allocator_pvt.h"
  17. #include "util/Bits.h"
  18. #include "util/Defined.h"
  19. #include <stdio.h>
  20. /** This provides the padding for each line based on the depth in the stack. */
  21. struct Unroller;
  22. struct Unroller
  23. {
  24. const char* const content;
  25. const struct Unroller* const last;
  26. };
  27. static void writeUnroller(const struct Unroller* unroller)
  28. {
  29. if (unroller) {
  30. writeUnroller(unroller->last);
  31. fprintf(stderr, "%s", unroller->content);
  32. }
  33. }
  34. static void unroll(struct Allocator_pvt* context,
  35. int includeAllocations,
  36. struct Unroller* unroller)
  37. {
  38. writeUnroller(unroller);
  39. const char* ident = (context->pub.fileName) ? context->pub.fileName : "UNKNOWN";
  40. fprintf(stderr, "%s:%d [%lu] bytes%s\n",
  41. ident,
  42. context->pub.lineNum,
  43. context->allocatedHere,
  44. (context->pub.isFreeing) ? " (freeing)" : "");
  45. struct Unroller childUnroller = {
  46. .content = ((context->nextSibling) ? "| " : " "),
  47. .last = unroller
  48. };
  49. if (context->firstChild) {
  50. unroll(context->firstChild, includeAllocations, &childUnroller);
  51. }
  52. struct Allocator_Allocation_pvt* allocation = context->allocations;
  53. while (allocation && includeAllocations) {
  54. writeUnroller(&childUnroller);
  55. fprintf(stderr, "%s:%d [%lu] bytes at [0x%lx]\n",
  56. allocation->pub.fileName,
  57. allocation->pub.lineNum,
  58. allocation->pub.size,
  59. (long)(uintptr_t)allocation);
  60. allocation = allocation->next;
  61. }
  62. if (context->nextSibling) {
  63. unroll(context->nextSibling, includeAllocations, unroller);
  64. }
  65. }
  66. static inline uint64_t bytesAllocated(struct Allocator_pvt* ctx)
  67. {
  68. uint64_t bytes = ctx->allocatedHere;
  69. for (struct Allocator_pvt* child = ctx->firstChild; child; child = child->nextSibling) {
  70. bytes += bytesAllocated(child);
  71. }
  72. return bytes;
  73. }
  74. void Allocator_snapshot(struct Allocator* allocator, int includeAllocations)
  75. {
  76. // get the root allocator.
  77. struct Allocator_pvt* alloc = Identity_check((struct Allocator_pvt*)allocator);
  78. struct Allocator_FirstCtx* rootAlloc = Identity_check(alloc->rootAlloc);
  79. alloc = Identity_check((struct Allocator_pvt*)rootAlloc);
  80. fprintf(stderr, "----- %scjdns memory snapshot -----\n", "");
  81. uint64_t totalAllocated = rootAlloc->maxSpace - rootAlloc->spaceAvailable;
  82. uint64_t realAllocated = bytesAllocated(alloc);
  83. unroll(alloc, includeAllocations, NULL);
  84. if (totalAllocated != realAllocated) {
  85. fprintf(stderr, "!!!!!! INTERNAL ERROR totalAllocated = [%lu] realAllocated = [%lu] !!!!!",
  86. (unsigned long)totalAllocated, (unsigned long)realAllocated);
  87. }
  88. fprintf(stderr, "totalBytes [%ld] remaining [%ld]\n",
  89. (long)rootAlloc->maxSpace,
  90. (long)rootAlloc->spaceAvailable);
  91. fprintf(stderr, "----- %scjdns memory snapshot -----\n", "end ");
  92. }
  93. Gcc_NORETURN
  94. static void failure(struct Allocator_pvt* context,
  95. const char* message,
  96. const char* fileName,
  97. int lineNum)
  98. {
  99. Allocator_snapshot(&context->pub, 1);
  100. Assert_failure("%s:%d Fatal error: [%s]", fileName, lineNum, message);
  101. }
  102. static inline unsigned long getRealSize(unsigned long requestedSize)
  103. {
  104. return ((requestedSize + (sizeof(char*) - 1)) & ~(sizeof(char*) - 1)) // align
  105. + sizeof(struct Allocator_Allocation_pvt)
  106. #ifdef Allocator_USE_CANARIES
  107. + sizeof(unsigned long)
  108. #endif
  109. ;
  110. }
  111. #define END_CANARY(alloc) ((unsigned long*) alloc)[ (alloc->pub.size / sizeof(unsigned long)) - 1 ]
  112. static inline void setCanaries(struct Allocator_Allocation_pvt* alloc,
  113. struct Allocator_pvt* context)
  114. {
  115. #ifdef Allocator_USE_CANARIES
  116. END_CANARY(alloc) = alloc->beginCanary = context->canary;
  117. #endif
  118. }
  119. static inline void checkCanaries(struct Allocator_Allocation_pvt* alloc,
  120. struct Allocator_pvt* context)
  121. {
  122. #ifdef Allocator_USE_CANARIES
  123. char* canary;
  124. if (alloc->beginCanary != context->canary) {
  125. canary = "begin";
  126. } else if (END_CANARY(alloc) != alloc->beginCanary) {
  127. canary = "end";
  128. } else {
  129. return;
  130. }
  131. Assert_failure("%s:%d Fatal error: invalid [%s] canary\n",
  132. context->pub.fileName, context->pub.lineNum, canary);
  133. #endif
  134. }
  135. Gcc_ALLOC_SIZE(2)
  136. static inline void* newAllocation(struct Allocator_pvt* context,
  137. unsigned long size,
  138. const char* fileName,
  139. int lineNum)
  140. {
  141. int64_t realSize = getRealSize(size);
  142. struct Allocator_FirstCtx* rootAlloc = Identity_check(context->rootAlloc);
  143. if (rootAlloc->spaceAvailable <= realSize) {
  144. failure(context, "Out of memory, limit exceeded", fileName, lineNum);
  145. }
  146. rootAlloc->spaceAvailable -= realSize;
  147. context->allocatedHere += realSize;
  148. struct Allocator_Allocation_pvt* alloc =
  149. rootAlloc->provider(rootAlloc->providerContext,
  150. NULL,
  151. realSize,
  152. &context->pub);
  153. if (alloc == NULL) {
  154. failure(context, "Out of memory, malloc() returned NULL", fileName, lineNum);
  155. }
  156. alloc->next = context->allocations;
  157. alloc->pub.size = realSize;
  158. alloc->pub.fileName = fileName;
  159. alloc->pub.lineNum = lineNum;
  160. context->allocations = alloc;
  161. setCanaries(alloc, context);
  162. return (void*) (alloc + 1);
  163. }
  164. struct Allocator_Allocation* Allocator_getAllocation(struct Allocator* alloc, int allocNum)
  165. {
  166. struct Allocator_pvt* ctx = Identity_check((struct Allocator_pvt*)alloc);
  167. if (allocNum < 0) {
  168. return NULL;
  169. }
  170. struct Allocator_Allocation_pvt* allocation = ctx->allocations;
  171. for (;allocation && allocNum > 0; allocNum--) {
  172. allocation = allocation->next;
  173. }
  174. return (allocation) ? &allocation->pub : NULL;
  175. }
  176. struct Allocator* Allocator_getChild(struct Allocator* alloc, int childNumber)
  177. {
  178. struct Allocator_pvt* ctx = Identity_check((struct Allocator_pvt*)alloc);
  179. if (childNumber < 0) {
  180. return NULL;
  181. }
  182. struct Allocator_pvt* child = ctx->firstChild;
  183. for (;child && childNumber > 0; childNumber--) {
  184. child = child->nextSibling;
  185. }
  186. return (child) ? &child->pub : NULL;
  187. }
  188. static int removeJob(struct Allocator_OnFreeJob_pvt* job)
  189. {
  190. struct Allocator_pvt* context = Identity_check(job->alloc);
  191. struct Allocator_OnFreeJob_pvt* j = context->onFree;
  192. struct Allocator_OnFreeJob_pvt** jP = &context->onFree;
  193. while (j && j != job) {
  194. jP = &j->next;
  195. j = j->next;
  196. }
  197. if (j == job) {
  198. *jP = j->next;
  199. return 0;
  200. } else {
  201. return -1;
  202. failure(context, "Allocator_onFreeComplete() called multiple times", job->file, job->line);
  203. }
  204. }
  205. static void releaseAllocation(struct Allocator_pvt* context,
  206. struct Allocator_Allocation_pvt* allocation,
  207. Allocator_Provider provider,
  208. Allocator_Provider_CONTEXT_TYPE* providerCtx)
  209. {
  210. checkCanaries(allocation, context);
  211. // TODO(cjd): make this optional.
  212. Bits_memset(&(&allocation->pub)[1],
  213. 0xee,
  214. allocation->pub.size - sizeof(struct Allocator_Allocation));
  215. provider(providerCtx,
  216. &allocation->pub,
  217. 0,
  218. ((char*)context != (char*)allocation) ? &context->pub : NULL);
  219. }
  220. static void releaseMemory(struct Allocator_pvt* context,
  221. Allocator_Provider provider,
  222. Allocator_Provider_CONTEXT_TYPE* providerCtx)
  223. {
  224. // Free all of the allocations including the one which holds the allocator.
  225. #ifdef PARANOIA
  226. unsigned long allocatedHere = context->allocatedHere;
  227. #endif
  228. Identity_check(context->rootAlloc)->spaceAvailable += context->allocatedHere;
  229. struct Allocator_Allocation_pvt* loc = context->allocations;
  230. while (loc != NULL) {
  231. #ifdef PARANOIA
  232. allocatedHere -= loc->pub.size;
  233. #endif
  234. struct Allocator_Allocation_pvt* nextLoc = loc->next;
  235. releaseAllocation(context, loc, provider, providerCtx);
  236. loc = nextLoc;
  237. }
  238. #ifdef PARANOIA
  239. Assert_true(allocatedHere == 0);
  240. #endif
  241. }
  242. // disconnect an allocator from it's parent.
  243. static void disconnect(struct Allocator_pvt* context)
  244. {
  245. // Remove this allocator from the sibling list.
  246. Assert_true(context->parent);
  247. if (context->lastSibling) {
  248. Assert_ifParanoid(context->lastSibling->nextSibling == context);
  249. Assert_ifParanoid(context->parent->firstChild != context);
  250. context->lastSibling->nextSibling = context->nextSibling;
  251. } else {
  252. // must be first in the list or a root allocator.
  253. Assert_ifParanoid(context->parent->firstChild == context || context->parent == context);
  254. Assert_ifParanoid(context->parent != context || !context->nextSibling);
  255. context->parent->firstChild = context->nextSibling;
  256. }
  257. if (context->nextSibling) {
  258. Assert_ifParanoid(context->nextSibling->lastSibling == context);
  259. context->nextSibling->lastSibling = context->lastSibling;
  260. }
  261. context->lastSibling = NULL;
  262. context->nextSibling = NULL;
  263. context->parent = NULL;
  264. }
  265. // connect an allocator to a new parent.
  266. static void connect(struct Allocator_pvt* parent,
  267. struct Allocator_pvt* child,
  268. const char* file,
  269. int line)
  270. {
  271. Assert_ifParanoid(child->parent == NULL);
  272. Assert_ifParanoid(child->lastSibling == NULL);
  273. Assert_ifParanoid(child->nextSibling == NULL);
  274. Assert_true(parent != child);
  275. if (Defined(PARANOIA)) {
  276. for (struct Allocator_pvt* c = parent->firstChild; c; c = c->nextSibling) {
  277. Assert_true(child != c);
  278. }
  279. }
  280. child->nextSibling = parent->firstChild;
  281. if (parent->firstChild) {
  282. parent->firstChild->lastSibling = child;
  283. }
  284. parent->firstChild = child;
  285. child->parent = parent;
  286. }
  287. static int disconnectAllocator(struct Allocator_pvt* target, struct Allocator_List** cpp)
  288. {
  289. int found = 0;
  290. struct Allocator_List* cp;
  291. while ((cp = *cpp)) {
  292. if (cp->alloc == target) {
  293. *cpp = cp->next;
  294. found = 1;
  295. break;
  296. }
  297. cpp = &cp->next;
  298. }
  299. return found;
  300. }
  301. static void disconnectAdopted(struct Allocator_pvt* parent, struct Allocator_pvt* child)
  302. {
  303. Assert_true(parent->adoptions);
  304. Assert_true(parent->adoptions->children);
  305. Assert_true(child->adoptions);
  306. Assert_true(child->adoptions->parents);
  307. Assert_true(disconnectAllocator(child, &parent->adoptions->children));
  308. Assert_true(disconnectAllocator(parent, &child->adoptions->parents));
  309. }
  310. // Shallow first search to prevent lots of flapping while we tear down the tree.
  311. static int pivotChildrenToAdoptedParents0(struct Allocator_pvt* context,
  312. int depth,
  313. int maxDepth,
  314. const char* file,
  315. int line)
  316. {
  317. int out = 0;
  318. if (depth == maxDepth) {
  319. if (context->adoptions) {
  320. // Attempt to pivot around to a parent in order to save this allocator
  321. if (context->adoptions->parents) {
  322. Assert_true(!context->adoptions->parents->alloc->pub.isFreeing);
  323. disconnect(context);
  324. connect(context->adoptions->parents->alloc, context, file, line);
  325. disconnectAdopted(context->adoptions->parents->alloc, context);
  326. return 0;
  327. }
  328. // No saving it, drop it's adoptions.
  329. for (struct Allocator_List* c = context->adoptions->children; c; c = c->next) {
  330. Assert_true(!c->alloc->pub.isFreeing);
  331. disconnectAdopted(context, c->alloc);
  332. }
  333. }
  334. // If (context->parent == context) it's a root allocator and disconnect does the wrong thing
  335. if (depth == 0 && context->parent != context) { disconnect(context); }
  336. Assert_true(!context->pub.isFreeing);
  337. context->pub.isFreeing = 1;
  338. out++;
  339. } else {
  340. struct Allocator_pvt* child = context->firstChild;
  341. while (child) {
  342. Assert_ifParanoid(child != context);
  343. struct Allocator_pvt* nextChild = child->nextSibling;
  344. out += pivotChildrenToAdoptedParents0(child, depth+1, maxDepth, file, line);
  345. child = nextChild;
  346. }
  347. }
  348. return out;
  349. }
  350. static int pivotChildrenToAdoptedParents(struct Allocator_pvt* context, const char* file, int line)
  351. {
  352. for (int i = 0; i < 10000; i++) {
  353. if (!pivotChildrenToAdoptedParents0(context, 0, i, file, line)) {
  354. // No out on i == 0 -> the allocator pivoted to another parent, cease freeing.
  355. return (i != 0);
  356. }
  357. }
  358. Assert_failure("Didn't free all allocators in 10000 deep iterations");
  359. }
  360. /**
  361. * Collect all of the onFree jobs from all of the child allocators (deep) and attach them all
  362. * to the root of the tree which is being freed. They are not detached from their relevant
  363. * allocators because those allocators will be freed soon anyway.
  364. */
  365. static void marshalOnFreeJobs(struct Allocator_pvt* context, struct Allocator_pvt* rootToFree)
  366. {
  367. struct Allocator_pvt* child = context->firstChild;
  368. while (child) {
  369. // Theoretically the order of free jobs is not promised but this prevents libuv crashing.
  370. struct Allocator_OnFreeJob_pvt** jobP = &rootToFree->onFree;
  371. while (*jobP != NULL) {
  372. struct Allocator_OnFreeJob_pvt* job = *jobP;
  373. jobP = &job->next;
  374. }
  375. *jobP = child->onFree;
  376. while (*jobP != NULL) {
  377. struct Allocator_OnFreeJob_pvt* job = *jobP;
  378. job->alloc = rootToFree;
  379. jobP = &job->next;
  380. }
  381. struct Allocator_pvt* nextChild = child->nextSibling;
  382. marshalOnFreeJobs(child, rootToFree);
  383. child = nextChild;
  384. }
  385. }
  386. static void doOnFreeJobs(struct Allocator_pvt* context)
  387. {
  388. // Do the onFree jobs.
  389. struct Allocator_OnFreeJob_pvt** jobP = &context->onFree;
  390. while (*jobP != NULL) {
  391. struct Allocator_OnFreeJob_pvt* job = *jobP;
  392. if (!job->pub.callback) {
  393. // no callback, remove the job
  394. Assert_true(!removeJob(job));
  395. continue;
  396. } else {
  397. if (job->pub.callback(&job->pub) != Allocator_ONFREE_ASYNC) {
  398. Assert_true(!removeJob(job));
  399. continue;
  400. }
  401. }
  402. jobP = &job->next;
  403. }
  404. }
  405. static void freeAllocator(struct Allocator_pvt* context)
  406. {
  407. struct Allocator_pvt* child = context->firstChild;
  408. while (child) {
  409. struct Allocator_pvt* nextChild = child->nextSibling;
  410. freeAllocator(child);
  411. child = nextChild;
  412. }
  413. // Grab out the provider and provider context in case the root allocator is freed.
  414. struct Allocator_FirstCtx* rootAlloc = Identity_check(context->rootAlloc);
  415. Allocator_Provider provider = rootAlloc->provider;
  416. Allocator_Provider_CONTEXT_TYPE* providerCtx = rootAlloc->providerContext;
  417. releaseMemory(context, provider, providerCtx);
  418. }
  419. void Allocator_onFreeComplete(struct Allocator_OnFreeJob* onFreeJob)
  420. {
  421. struct Allocator_OnFreeJob_pvt* job = (struct Allocator_OnFreeJob_pvt*) onFreeJob;
  422. struct Allocator_pvt* context = Identity_check(job->alloc);
  423. if (removeJob(job)) {
  424. failure(context, "OnFreeJob->complete() called multiple times", job->file, job->line);
  425. }
  426. if (!context->onFree) {
  427. // There are no more jobs, release the memory.
  428. freeAllocator(context);
  429. }
  430. }
  431. void Allocator__free(struct Allocator* alloc, const char* file, int line)
  432. {
  433. struct Allocator_pvt* context = Identity_check((struct Allocator_pvt*) alloc);
  434. // It's really difficult to know that you didn't get called back inside of a freeing of a
  435. // parent of a parent allocator which causes your allocator to be in isFreeing state so
  436. // lets be forgiving here.
  437. if (context->pub.isFreeing) { return; }
  438. if (context->rootAlloc == (struct Allocator_FirstCtx*)context) {
  439. struct Allocator_FirstCtx* rootAlloc = Identity_check((struct Allocator_FirstCtx*)context);
  440. if (bytesAllocated(context) + rootAlloc->spaceAvailable != (uint64_t)rootAlloc->maxSpace) {
  441. failure(context, "unaccounted for memory", file, line);
  442. }
  443. }
  444. if (!pivotChildrenToAdoptedParents(context, file, line)) { return; }
  445. marshalOnFreeJobs(context, context);
  446. doOnFreeJobs(context);
  447. if (!context->onFree) {
  448. freeAllocator(context);
  449. }
  450. }
  451. void* Allocator__malloc(struct Allocator* allocator,
  452. unsigned long length,
  453. const char* fileName,
  454. int lineNum)
  455. {
  456. struct Allocator_pvt* ctx = Identity_check((struct Allocator_pvt*) allocator);
  457. return newAllocation(ctx, length, fileName, lineNum);
  458. }
  459. void* Allocator__calloc(struct Allocator* alloc,
  460. unsigned long length,
  461. unsigned long count,
  462. const char* fileName,
  463. int lineNum)
  464. {
  465. void* pointer = Allocator__malloc(alloc, length * count, fileName, lineNum);
  466. Bits_memset(pointer, 0, length * count);
  467. return pointer;
  468. }
  469. void* Allocator__realloc(struct Allocator* allocator,
  470. const void* original,
  471. unsigned long size,
  472. const char* fileName,
  473. int lineNum)
  474. {
  475. if (original == NULL) {
  476. return Allocator__malloc(allocator, size, fileName, lineNum);
  477. }
  478. struct Allocator_pvt* context = Identity_check((struct Allocator_pvt*) allocator);
  479. struct Allocator_Allocation_pvt** locPtr = &context->allocations;
  480. struct Allocator_Allocation_pvt* origLoc =
  481. ((struct Allocator_Allocation_pvt*) original) - 1;
  482. for (;;) {
  483. struct Allocator_Allocation_pvt* loc = *locPtr;
  484. if (loc == NULL) {
  485. failure(context,
  486. "Reallocation of memory which was not allocated using this allocator.",
  487. fileName,
  488. lineNum);
  489. }
  490. checkCanaries(loc, context);
  491. if (loc == origLoc) {
  492. break;
  493. }
  494. locPtr = &loc->next;
  495. }
  496. struct Allocator_Allocation_pvt* nextLoc = origLoc->next;
  497. if (size == 0) {
  498. // realloc(0) means free()
  499. *locPtr = nextLoc;
  500. Assert_true(origLoc->pub.size <= context->allocatedHere);
  501. context->rootAlloc->spaceAvailable += origLoc->pub.size;
  502. context->allocatedHere -= origLoc->pub.size;
  503. releaseAllocation(context,
  504. origLoc,
  505. context->rootAlloc->provider,
  506. context->rootAlloc->providerContext);
  507. return NULL;
  508. }
  509. size_t realSize = getRealSize(size);
  510. if (context->rootAlloc->spaceAvailable + origLoc->pub.size < realSize) {
  511. failure(context, "Out of memory, limit exceeded.", fileName, lineNum);
  512. }
  513. context->rootAlloc->spaceAvailable += origLoc->pub.size;
  514. context->rootAlloc->spaceAvailable -= realSize;
  515. context->allocatedHere -= origLoc->pub.size;
  516. context->allocatedHere += realSize;
  517. struct Allocator_Allocation_pvt* alloc =
  518. context->rootAlloc->provider(context->rootAlloc->providerContext,
  519. &origLoc->pub,
  520. realSize,
  521. allocator);
  522. if (alloc == NULL) {
  523. failure(context, "Out of memory, realloc() returned NULL.", fileName, lineNum);
  524. }
  525. alloc->next = nextLoc;
  526. alloc->pub.size = realSize;
  527. *locPtr = alloc;
  528. setCanaries(alloc, context);
  529. return (void*) (alloc + 1);
  530. }
  531. void* Allocator__clone(struct Allocator* allocator,
  532. const void* toClone,
  533. unsigned long length,
  534. const char* fileName,
  535. int lineNum)
  536. {
  537. void* pointer = Allocator__malloc(allocator, length, fileName, lineNum);
  538. Bits_memcpy(pointer, toClone, length);
  539. return pointer;
  540. }
  541. struct Allocator* Allocator__child(struct Allocator* allocator, const char* file, int line)
  542. {
  543. struct Allocator_pvt* parent = Identity_check((struct Allocator_pvt*) allocator);
  544. struct Allocator_pvt stackChild = {
  545. .pub = {
  546. .fileName = file,
  547. .lineNum = line,
  548. },
  549. .rootAlloc = parent->rootAlloc
  550. };
  551. Identity_set(&stackChild);
  552. #ifdef Allocator_USE_CANARIES
  553. stackChild.nextCanary = stackChild.canary = parent->nextCanary;
  554. #endif
  555. struct Allocator_pvt* child =
  556. newAllocation(&stackChild, sizeof(struct Allocator_pvt), file, line);
  557. Bits_memcpy(child, &stackChild, sizeof(struct Allocator_pvt));
  558. // Link the child into the parent's allocator list
  559. connect(parent, child, file, line);
  560. return &child->pub;
  561. }
  562. int Allocator_cancelOnFree(struct Allocator_OnFreeJob* toRemove)
  563. {
  564. struct Allocator_OnFreeJob_pvt* job = (struct Allocator_OnFreeJob_pvt*) toRemove;
  565. struct Allocator_pvt* context = Identity_check(job->alloc);
  566. struct Allocator_OnFreeJob_pvt** jobPtr = &(context->onFree);
  567. while (*jobPtr != NULL) {
  568. if (*jobPtr == job) {
  569. *jobPtr = (*jobPtr)->next;
  570. return 0;
  571. }
  572. jobPtr = &(*jobPtr)->next;
  573. }
  574. return -1;
  575. }
  576. /** return 1 if true, otherwise zero. */
  577. static int isAncestorOf(struct Allocator_pvt* maybeParent,
  578. struct Allocator_pvt* maybeChild)
  579. {
  580. if (maybeParent == maybeChild) {
  581. return 1;
  582. }
  583. if (maybeParent == NULL || maybeChild == NULL || maybeChild->parent == maybeChild) {
  584. return 0;
  585. }
  586. if (isAncestorOf(maybeParent, maybeChild->parent)) {
  587. return 1;
  588. }
  589. if (maybeChild->adoptions) {
  590. struct Allocator_List* al = maybeChild->adoptions->parents;
  591. while (al) {
  592. if (isAncestorOf(maybeParent, al->alloc)) {
  593. return 1;
  594. }
  595. }
  596. }
  597. return 0;
  598. }
  599. void Allocator__disown(struct Allocator* parentAlloc,
  600. struct Allocator* allocToDisown,
  601. const char* fileName,
  602. int lineNum)
  603. {
  604. struct Allocator_pvt* parent = Identity_check((struct Allocator_pvt*) parentAlloc);
  605. struct Allocator_pvt* child = Identity_check((struct Allocator_pvt*) allocToDisown);
  606. if (parent->pub.isFreeing || child->pub.isFreeing) { return; }
  607. if (child->parent == parent) {
  608. // The child's natural parent has been freed and it has pivoted to the adopted parent
  609. // Do a normal Allocator_free() and it will either pivot once again to another adopter
  610. // or it will drop from the tree and free.
  611. Allocator__free(&child->pub, fileName, lineNum);
  612. return;
  613. }
  614. if (isAncestorOf(child, parent)) {
  615. // Rare but possible way that the child would never have been adopted.
  616. return;
  617. }
  618. disconnectAdopted(parent, child);
  619. }
  620. void Allocator__adopt(struct Allocator* adoptedParent,
  621. struct Allocator* childToAdopt,
  622. const char* file,
  623. int line)
  624. {
  625. struct Allocator_pvt* parent = Identity_check((struct Allocator_pvt*) adoptedParent);
  626. struct Allocator_pvt* child = Identity_check((struct Allocator_pvt*) childToAdopt);
  627. if (parent->pub.isFreeing) { return; }
  628. Assert_true(!child->pub.isFreeing);
  629. if (isAncestorOf(child, parent)) {
  630. // The child is a parent of the parent, this means an adoption would be meaningless
  631. // because if the child is otherwise freed, it will take the parent along with it.
  632. return;
  633. }
  634. if (!parent->adoptions) {
  635. parent->adoptions =
  636. Allocator__calloc(adoptedParent, sizeof(struct Allocator_Adoptions), 1, file, line);
  637. }
  638. if (!child->adoptions) {
  639. child->adoptions =
  640. Allocator__calloc(childToAdopt, sizeof(struct Allocator_Adoptions), 1, file, line);
  641. }
  642. struct Allocator_List* pl =
  643. Allocator__calloc(childToAdopt, sizeof(struct Allocator_List), 1, file, line);
  644. pl->alloc = child;
  645. pl->next = parent->adoptions->children;
  646. parent->adoptions->children = pl;
  647. struct Allocator_List* cl =
  648. Allocator__calloc(childToAdopt, sizeof(struct Allocator_List), 1, file, line);
  649. cl->alloc = parent;
  650. cl->next = child->adoptions->parents;
  651. child->adoptions->parents = cl;
  652. }
  653. struct Allocator_OnFreeJob* Allocator__onFree(struct Allocator* alloc,
  654. Allocator_OnFreeCallback callback,
  655. void* callbackContext,
  656. const char* file,
  657. int line)
  658. {
  659. struct Allocator_pvt* context = Identity_check((struct Allocator_pvt*) alloc);
  660. struct Allocator_OnFreeJob_pvt* newJob =
  661. Allocator_clone(alloc, (&(struct Allocator_OnFreeJob_pvt) {
  662. .pub = {
  663. .callback = callback,
  664. .userData = callbackContext
  665. },
  666. .alloc = context,
  667. .file = file,
  668. .line = line
  669. }));
  670. Identity_set(newJob);
  671. struct Allocator_OnFreeJob_pvt* job = context->onFree;
  672. if (job == NULL) {
  673. context->onFree = newJob;
  674. } else {
  675. while (job->next != NULL) {
  676. job = job->next;
  677. }
  678. job->next = newJob;
  679. }
  680. return &newJob->pub;
  681. }
  682. struct Allocator* Allocator_new(unsigned long sizeLimit,
  683. Allocator_Provider provider,
  684. void* providerContext,
  685. const char* fileName,
  686. int lineNum)
  687. {
  688. if (sizeLimit == 0) {
  689. sizeLimit = INT64_MAX - getRealSize(sizeof(struct Allocator_FirstCtx));
  690. }
  691. // Add in the size of the allocator so that a very small sizeLimit is sane.
  692. sizeLimit += getRealSize(sizeof(struct Allocator_FirstCtx));
  693. struct Allocator_FirstCtx stackContext = {
  694. .spaceAvailable = sizeLimit,
  695. .provider = provider,
  696. .providerContext = providerContext,
  697. .context = {
  698. .pub = {
  699. .fileName = fileName,
  700. .lineNum = lineNum,
  701. },
  702. #ifdef Allocator_USE_CANARIES
  703. .canary = (unsigned long) Constant_rand64(),
  704. .nextCanary = (unsigned long) Constant_rand64(),
  705. #endif
  706. }
  707. };
  708. stackContext.maxSpace = stackContext.spaceAvailable;
  709. stackContext.context.rootAlloc = &stackContext;
  710. Identity_set(&stackContext);
  711. Identity_set(&stackContext.context);
  712. struct Allocator_FirstCtx* firstContext =
  713. Allocator__clone(&stackContext.context.pub,
  714. &stackContext,
  715. sizeof(struct Allocator_FirstCtx),
  716. fileName,
  717. lineNum);
  718. struct Allocator_pvt* context = &firstContext->context;
  719. context->rootAlloc = firstContext;
  720. context->parent = context;
  721. return &context->pub;
  722. }
  723. unsigned long Allocator_bytesAllocated(struct Allocator* allocator)
  724. {
  725. struct Allocator_pvt* context = Identity_check((struct Allocator_pvt*) allocator);
  726. return bytesAllocated(context);
  727. }
  728. void Allocator_setCanary(struct Allocator* alloc, unsigned long value)
  729. {
  730. #ifdef Allocator_USE_CANARIES
  731. struct Allocator_pvt* context = Identity_check((struct Allocator_pvt*) alloc);
  732. context->nextCanary ^= value;
  733. #endif
  734. }