1
0

Allocator.c 29 KB

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