Allocator.c 29 KB

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