Allocator.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  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 void disconnectAdopted(struct Allocator_pvt* parent, struct Allocator_pvt* child)
  288. {
  289. Assert_true(parent->adoptions);
  290. Assert_true(parent->adoptions->children);
  291. Assert_true(child->adoptions);
  292. Assert_true(child->adoptions->parents);
  293. int foundChild = 0;
  294. int foundParent = 0;
  295. {
  296. struct Allocator_List** cpp = &parent->adoptions->children;
  297. struct Allocator_List* cp;
  298. while ((cp = *cpp)) {
  299. if (cp->alloc == child) {
  300. *cpp = cp->next;
  301. foundChild = 1;
  302. break;
  303. }
  304. cpp = &cp->next;
  305. }
  306. }
  307. {
  308. struct Allocator_List** cpp = &child->adoptions->parents;
  309. struct Allocator_List* cp;
  310. while ((cp = *cpp)) {
  311. if (cp->alloc == parent) {
  312. *cpp = cp->next;
  313. foundParent = 1;
  314. break;
  315. }
  316. cpp = &cp->next;
  317. }
  318. }
  319. Assert_true(foundChild);
  320. Assert_true(foundParent);
  321. }
  322. // Shallow first search to prevent lots of flapping while we tear down the tree.
  323. static int pivotChildrenToAdoptedParents0(struct Allocator_pvt* context,
  324. int depth,
  325. int maxDepth,
  326. const char* file,
  327. int line)
  328. {
  329. int out = 0;
  330. if (depth == maxDepth) {
  331. if (context->adoptions) {
  332. // Attempt to pivot around to a parent in order to save this allocator
  333. if (context->adoptions->parents) {
  334. Assert_true(!context->adoptions->parents->alloc->pub.isFreeing);
  335. disconnect(context);
  336. connect(context->adoptions->parents->alloc, context, file, line);
  337. disconnectAdopted(context->adoptions->parents->alloc, context);
  338. return 0;
  339. }
  340. // No saving it, drop it's adoptions.
  341. for (struct Allocator_List* c = context->adoptions->children; c; c = c->next) {
  342. Assert_true(!c->alloc->pub.isFreeing);
  343. disconnectAdopted(context, c->alloc);
  344. }
  345. }
  346. // If (context->parent == context) it's a root allocator and disconnect does the wrong thing
  347. if (depth == 0 && context->parent != context) { disconnect(context); }
  348. Assert_true(!context->pub.isFreeing);
  349. context->pub.isFreeing = 1;
  350. out++;
  351. } else {
  352. struct Allocator_pvt* child = context->firstChild;
  353. while (child) {
  354. Assert_ifParanoid(child != context);
  355. struct Allocator_pvt* nextChild = child->nextSibling;
  356. out += pivotChildrenToAdoptedParents0(child, depth+1, maxDepth, file, line);
  357. child = nextChild;
  358. }
  359. }
  360. return out;
  361. }
  362. static int pivotChildrenToAdoptedParents(struct Allocator_pvt* context, const char* file, int line)
  363. {
  364. for (int i = 0; i < 10000; i++) {
  365. if (!pivotChildrenToAdoptedParents0(context, 0, i, file, line)) {
  366. // No out on i == 0 -> the allocator pivoted to another parent, cease freeing.
  367. return (i != 0);
  368. }
  369. }
  370. Assert_failure("Didn't free all allocators in 10000 deep iterations");
  371. }
  372. /**
  373. * Collect all of the onFree jobs from all of the child allocators (deep) and attach them all
  374. * to the root of the tree which is being freed. They are not detached from their relevant
  375. * allocators because those allocators will be freed soon anyway.
  376. */
  377. static void marshalOnFreeJobs(struct Allocator_pvt* context, struct Allocator_pvt* rootToFree)
  378. {
  379. struct Allocator_pvt* child = context->firstChild;
  380. while (child) {
  381. // Theoretically the order of free jobs is not promised but this prevents libuv crashing.
  382. struct Allocator_OnFreeJob_pvt** jobP = &rootToFree->onFree;
  383. while (*jobP != NULL) {
  384. struct Allocator_OnFreeJob_pvt* job = *jobP;
  385. jobP = &job->next;
  386. }
  387. *jobP = child->onFree;
  388. while (*jobP != NULL) {
  389. struct Allocator_OnFreeJob_pvt* job = *jobP;
  390. job->alloc = rootToFree;
  391. jobP = &job->next;
  392. }
  393. struct Allocator_pvt* nextChild = child->nextSibling;
  394. marshalOnFreeJobs(child, rootToFree);
  395. child = nextChild;
  396. }
  397. }
  398. static void doOnFreeJobs(struct Allocator_pvt* context)
  399. {
  400. // Do the onFree jobs.
  401. struct Allocator_OnFreeJob_pvt** jobP = &context->onFree;
  402. while (*jobP != NULL) {
  403. struct Allocator_OnFreeJob_pvt* job = *jobP;
  404. if (!job->pub.callback) {
  405. // no callback, remove the job
  406. Assert_true(!removeJob(job));
  407. continue;
  408. } else {
  409. if (job->pub.callback(&job->pub) != Allocator_ONFREE_ASYNC) {
  410. Assert_true(!removeJob(job));
  411. continue;
  412. }
  413. }
  414. jobP = &job->next;
  415. }
  416. }
  417. static void freeAllocator(struct Allocator_pvt* context)
  418. {
  419. struct Allocator_pvt* child = context->firstChild;
  420. while (child) {
  421. struct Allocator_pvt* nextChild = child->nextSibling;
  422. freeAllocator(child);
  423. child = nextChild;
  424. }
  425. // Grab out the provider and provider context in case the root allocator is freed.
  426. struct Allocator_FirstCtx* rootAlloc = Identity_check(context->rootAlloc);
  427. Allocator_Provider provider = rootAlloc->provider;
  428. Allocator_Provider_CONTEXT_TYPE* providerCtx = rootAlloc->providerContext;
  429. releaseMemory(context, provider, providerCtx);
  430. }
  431. void Allocator_onFreeComplete(struct Allocator_OnFreeJob* onFreeJob)
  432. {
  433. struct Allocator_OnFreeJob_pvt* job = (struct Allocator_OnFreeJob_pvt*) onFreeJob;
  434. struct Allocator_pvt* context = Identity_check(job->alloc);
  435. if (removeJob(job)) {
  436. failure(context, "OnFreeJob->complete() called multiple times", job->file, job->line);
  437. }
  438. if (!context->onFree) {
  439. // There are no more jobs, release the memory.
  440. freeAllocator(context);
  441. }
  442. }
  443. void Allocator__free(struct Allocator* alloc, const char* file, int line)
  444. {
  445. struct Allocator_pvt* context = Identity_check((struct Allocator_pvt*) alloc);
  446. // It's really difficult to know that you didn't get called back inside of a freeing of a
  447. // parent of a parent allocator which causes your allocator to be in isFreeing state so
  448. // lets be forgiving here.
  449. if (context->pub.isFreeing) { return; }
  450. if (context->rootAlloc == (struct Allocator_FirstCtx*)context) {
  451. struct Allocator_FirstCtx* rootAlloc = Identity_check((struct Allocator_FirstCtx*)context);
  452. if (bytesAllocated(context) + rootAlloc->spaceAvailable != (uint64_t)rootAlloc->maxSpace) {
  453. failure(context, "unaccounted for memory", file, line);
  454. }
  455. }
  456. if (!pivotChildrenToAdoptedParents(context, file, line)) { return; }
  457. marshalOnFreeJobs(context, context);
  458. doOnFreeJobs(context);
  459. if (!context->onFree) {
  460. freeAllocator(context);
  461. }
  462. }
  463. void* Allocator__malloc(struct Allocator* allocator,
  464. unsigned long length,
  465. const char* fileName,
  466. int lineNum)
  467. {
  468. struct Allocator_pvt* ctx = Identity_check((struct Allocator_pvt*) allocator);
  469. return newAllocation(ctx, length, fileName, lineNum);
  470. }
  471. void* Allocator__calloc(struct Allocator* alloc,
  472. unsigned long length,
  473. unsigned long count,
  474. const char* fileName,
  475. int lineNum)
  476. {
  477. void* pointer = Allocator__malloc(alloc, length * count, fileName, lineNum);
  478. Bits_memset(pointer, 0, length * count);
  479. return pointer;
  480. }
  481. void* Allocator__realloc(struct Allocator* allocator,
  482. const void* original,
  483. unsigned long size,
  484. const char* fileName,
  485. int lineNum)
  486. {
  487. if (original == NULL) {
  488. return Allocator__malloc(allocator, size, fileName, lineNum);
  489. }
  490. struct Allocator_pvt* context = Identity_check((struct Allocator_pvt*) allocator);
  491. struct Allocator_Allocation_pvt** locPtr = &context->allocations;
  492. struct Allocator_Allocation_pvt* origLoc =
  493. ((struct Allocator_Allocation_pvt*) original) - 1;
  494. for (;;) {
  495. struct Allocator_Allocation_pvt* loc = *locPtr;
  496. if (loc == NULL) {
  497. failure(context,
  498. "Reallocation of memory which was not allocated using this allocator.",
  499. fileName,
  500. lineNum);
  501. }
  502. checkCanaries(loc, context);
  503. if (loc == origLoc) {
  504. break;
  505. }
  506. locPtr = &loc->next;
  507. }
  508. struct Allocator_Allocation_pvt* nextLoc = origLoc->next;
  509. if (size == 0) {
  510. // realloc(0) means free()
  511. *locPtr = nextLoc;
  512. Assert_true(origLoc->pub.size <= context->allocatedHere);
  513. context->rootAlloc->spaceAvailable += origLoc->pub.size;
  514. context->allocatedHere -= origLoc->pub.size;
  515. releaseAllocation(context,
  516. origLoc,
  517. context->rootAlloc->provider,
  518. context->rootAlloc->providerContext);
  519. return NULL;
  520. }
  521. size_t realSize = getRealSize(size);
  522. if (context->rootAlloc->spaceAvailable + origLoc->pub.size < realSize) {
  523. failure(context, "Out of memory, limit exceeded.", fileName, lineNum);
  524. }
  525. context->rootAlloc->spaceAvailable += origLoc->pub.size;
  526. context->rootAlloc->spaceAvailable -= realSize;
  527. context->allocatedHere -= origLoc->pub.size;
  528. context->allocatedHere += realSize;
  529. struct Allocator_Allocation_pvt* alloc =
  530. context->rootAlloc->provider(context->rootAlloc->providerContext,
  531. &origLoc->pub,
  532. realSize,
  533. allocator);
  534. if (alloc == NULL) {
  535. failure(context, "Out of memory, realloc() returned NULL.", fileName, lineNum);
  536. }
  537. alloc->next = nextLoc;
  538. alloc->pub.size = realSize;
  539. *locPtr = alloc;
  540. setCanaries(alloc, context);
  541. return (void*) (alloc + 1);
  542. }
  543. void* Allocator__clone(struct Allocator* allocator,
  544. const void* toClone,
  545. unsigned long length,
  546. const char* fileName,
  547. int lineNum)
  548. {
  549. void* pointer = Allocator__malloc(allocator, length, fileName, lineNum);
  550. Bits_memcpy(pointer, toClone, length);
  551. return pointer;
  552. }
  553. struct Allocator* Allocator__child(struct Allocator* allocator, const char* file, int line)
  554. {
  555. struct Allocator_pvt* parent = Identity_check((struct Allocator_pvt*) allocator);
  556. struct Allocator_pvt stackChild = {
  557. .pub = {
  558. .fileName = file,
  559. .lineNum = line,
  560. },
  561. .rootAlloc = parent->rootAlloc
  562. };
  563. Identity_set(&stackChild);
  564. #ifdef Allocator_USE_CANARIES
  565. stackChild.nextCanary = stackChild.canary = parent->nextCanary;
  566. #endif
  567. struct Allocator_pvt* child =
  568. newAllocation(&stackChild, sizeof(struct Allocator_pvt), file, line);
  569. Bits_memcpy(child, &stackChild, sizeof(struct Allocator_pvt));
  570. // Link the child into the parent's allocator list
  571. connect(parent, child, file, line);
  572. return &child->pub;
  573. }
  574. int Allocator_cancelOnFree(struct Allocator_OnFreeJob* toRemove)
  575. {
  576. struct Allocator_OnFreeJob_pvt* job = (struct Allocator_OnFreeJob_pvt*) toRemove;
  577. struct Allocator_pvt* context = Identity_check(job->alloc);
  578. struct Allocator_OnFreeJob_pvt** jobPtr = &(context->onFree);
  579. while (*jobPtr != NULL) {
  580. if (*jobPtr == job) {
  581. *jobPtr = (*jobPtr)->next;
  582. return 0;
  583. }
  584. jobPtr = &(*jobPtr)->next;
  585. }
  586. return -1;
  587. }
  588. /** return 1 if true, otherwise zero. */
  589. static int isAncestorOf(struct Allocator_pvt* maybeParent,
  590. struct Allocator_pvt* maybeChild)
  591. {
  592. if (maybeParent == maybeChild) {
  593. return 1;
  594. }
  595. if (maybeParent == NULL || maybeChild == NULL || maybeChild->parent == maybeChild) {
  596. return 0;
  597. }
  598. if (isAncestorOf(maybeParent, maybeChild->parent)) {
  599. return 1;
  600. }
  601. if (maybeChild->adoptions) {
  602. struct Allocator_List* al = maybeChild->adoptions->parents;
  603. while (al) {
  604. if (isAncestorOf(maybeParent, al->alloc)) {
  605. return 1;
  606. }
  607. }
  608. }
  609. return 0;
  610. }
  611. void Allocator__disown(struct Allocator* parentAlloc,
  612. struct Allocator* allocToDisown,
  613. const char* fileName,
  614. int lineNum)
  615. {
  616. struct Allocator_pvt* parent = Identity_check((struct Allocator_pvt*) parentAlloc);
  617. struct Allocator_pvt* child = Identity_check((struct Allocator_pvt*) allocToDisown);
  618. if (parent->pub.isFreeing || child->pub.isFreeing) { return; }
  619. if (child->parent == parent) {
  620. // The child's natural parent has been freed and it has pivoted to the adopted parent
  621. // Do a normal Allocator_free() and it will either pivot once again to another adopter
  622. // or it will drop from the tree and free.
  623. Allocator__free(&child->pub, fileName, lineNum);
  624. return;
  625. }
  626. if (isAncestorOf(child, parent)) {
  627. // Rare but possible way that the child would never have been adopted.
  628. return;
  629. }
  630. disconnectAdopted(parent, child);
  631. }
  632. void Allocator__adopt(struct Allocator* adoptedParent,
  633. struct Allocator* childToAdopt,
  634. const char* file,
  635. int line)
  636. {
  637. struct Allocator_pvt* parent = Identity_check((struct Allocator_pvt*) adoptedParent);
  638. struct Allocator_pvt* child = Identity_check((struct Allocator_pvt*) childToAdopt);
  639. if (parent->pub.isFreeing) { return; }
  640. Assert_true(!child->pub.isFreeing);
  641. if (isAncestorOf(child, parent)) {
  642. // The child is a parent of the parent, this means an adoption would be meaningless
  643. // because if the child is otherwise freed, it will take the parent along with it.
  644. return;
  645. }
  646. if (!parent->adoptions) {
  647. parent->adoptions =
  648. Allocator__calloc(adoptedParent, sizeof(struct Allocator_Adoptions), 1, file, line);
  649. }
  650. if (!child->adoptions) {
  651. child->adoptions =
  652. Allocator__calloc(childToAdopt, sizeof(struct Allocator_Adoptions), 1, file, line);
  653. }
  654. struct Allocator_List* pl =
  655. Allocator__calloc(childToAdopt, sizeof(struct Allocator_List), 1, file, line);
  656. pl->alloc = child;
  657. pl->next = parent->adoptions->children;
  658. parent->adoptions->children = pl;
  659. struct Allocator_List* cl =
  660. Allocator__calloc(childToAdopt, sizeof(struct Allocator_List), 1, file, line);
  661. cl->alloc = parent;
  662. cl->next = child->adoptions->parents;
  663. child->adoptions->parents = cl;
  664. }
  665. struct Allocator_OnFreeJob* Allocator__onFree(struct Allocator* alloc,
  666. Allocator_OnFreeCallback callback,
  667. void* callbackContext,
  668. const char* file,
  669. int line)
  670. {
  671. struct Allocator_pvt* context = Identity_check((struct Allocator_pvt*) alloc);
  672. struct Allocator_OnFreeJob_pvt* newJob =
  673. Allocator_clone(alloc, (&(struct Allocator_OnFreeJob_pvt) {
  674. .pub = {
  675. .callback = callback,
  676. .userData = callbackContext
  677. },
  678. .alloc = context,
  679. .file = file,
  680. .line = line
  681. }));
  682. Identity_set(newJob);
  683. struct Allocator_OnFreeJob_pvt* job = context->onFree;
  684. if (job == NULL) {
  685. context->onFree = newJob;
  686. } else {
  687. while (job->next != NULL) {
  688. job = job->next;
  689. }
  690. job->next = newJob;
  691. }
  692. return &newJob->pub;
  693. }
  694. struct Allocator* Allocator_new(unsigned long sizeLimit,
  695. Allocator_Provider provider,
  696. void* providerContext,
  697. const char* fileName,
  698. int lineNum)
  699. {
  700. if (sizeLimit == 0) {
  701. sizeLimit = INT64_MAX - getRealSize(sizeof(struct Allocator_FirstCtx));
  702. }
  703. // Add in the size of the allocator so that a very small sizeLimit is sane.
  704. sizeLimit += getRealSize(sizeof(struct Allocator_FirstCtx));
  705. struct Allocator_FirstCtx stackContext = {
  706. .spaceAvailable = sizeLimit,
  707. .provider = provider,
  708. .providerContext = providerContext,
  709. .context = {
  710. .pub = {
  711. .fileName = fileName,
  712. .lineNum = lineNum,
  713. },
  714. #ifdef Allocator_USE_CANARIES
  715. .canary = (unsigned long) Constant_rand64(),
  716. .nextCanary = (unsigned long) Constant_rand64(),
  717. #endif
  718. }
  719. };
  720. stackContext.maxSpace = stackContext.spaceAvailable;
  721. stackContext.context.rootAlloc = &stackContext;
  722. Identity_set(&stackContext);
  723. Identity_set(&stackContext.context);
  724. struct Allocator_FirstCtx* firstContext =
  725. Allocator__clone(&stackContext.context.pub,
  726. &stackContext,
  727. sizeof(struct Allocator_FirstCtx),
  728. fileName,
  729. lineNum);
  730. struct Allocator_pvt* context = &firstContext->context;
  731. context->rootAlloc = firstContext;
  732. context->parent = context;
  733. return &context->pub;
  734. }
  735. unsigned long Allocator_bytesAllocated(struct Allocator* allocator)
  736. {
  737. struct Allocator_pvt* context = Identity_check((struct Allocator_pvt*) allocator);
  738. return bytesAllocated(context);
  739. }
  740. void Allocator_setCanary(struct Allocator* alloc, unsigned long value)
  741. {
  742. #ifdef Allocator_USE_CANARIES
  743. struct Allocator_pvt* context = Identity_check((struct Allocator_pvt*) alloc);
  744. context->nextCanary ^= value;
  745. #endif
  746. }