dlmalloc.c 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502
  1. #include <common.h>
  2. #if defined(CONFIG_UNIT_TEST)
  3. #define DEBUG
  4. #endif
  5. #include <malloc.h>
  6. #include <asm/io.h>
  7. #ifdef DEBUG
  8. #if __STD_C
  9. static void malloc_update_mallinfo (void);
  10. void malloc_stats (void);
  11. #else
  12. static void malloc_update_mallinfo ();
  13. void malloc_stats();
  14. #endif
  15. #endif /* DEBUG */
  16. DECLARE_GLOBAL_DATA_PTR;
  17. /*
  18. Emulation of sbrk for WIN32
  19. All code within the ifdef WIN32 is untested by me.
  20. Thanks to Martin Fong and others for supplying this.
  21. */
  22. #ifdef WIN32
  23. #define AlignPage(add) (((add) + (malloc_getpagesize-1)) & \
  24. ~(malloc_getpagesize-1))
  25. #define AlignPage64K(add) (((add) + (0x10000 - 1)) & ~(0x10000 - 1))
  26. /* resrve 64MB to insure large contiguous space */
  27. #define RESERVED_SIZE (1024*1024*64)
  28. #define NEXT_SIZE (2048*1024)
  29. #define TOP_MEMORY ((unsigned long)2*1024*1024*1024)
  30. struct GmListElement;
  31. typedef struct GmListElement GmListElement;
  32. struct GmListElement
  33. {
  34. GmListElement* next;
  35. void* base;
  36. };
  37. static GmListElement* head = 0;
  38. static unsigned int gNextAddress = 0;
  39. static unsigned int gAddressBase = 0;
  40. static unsigned int gAllocatedSize = 0;
  41. static
  42. GmListElement* makeGmListElement (void* bas)
  43. {
  44. GmListElement* this;
  45. this = (GmListElement*)(void*)LocalAlloc (0, sizeof (GmListElement));
  46. assert (this);
  47. if (this)
  48. {
  49. this->base = bas;
  50. this->next = head;
  51. head = this;
  52. }
  53. return this;
  54. }
  55. void gcleanup ()
  56. {
  57. BOOL rval;
  58. assert ( (head == NULL) || (head->base == (void*)gAddressBase));
  59. if (gAddressBase && (gNextAddress - gAddressBase))
  60. {
  61. rval = VirtualFree ((void*)gAddressBase,
  62. gNextAddress - gAddressBase,
  63. MEM_DECOMMIT);
  64. assert (rval);
  65. }
  66. while (head)
  67. {
  68. GmListElement* next = head->next;
  69. rval = VirtualFree (head->base, 0, MEM_RELEASE);
  70. assert (rval);
  71. LocalFree (head);
  72. head = next;
  73. }
  74. }
  75. static
  76. void* findRegion (void* start_address, unsigned long size)
  77. {
  78. MEMORY_BASIC_INFORMATION info;
  79. if (size >= TOP_MEMORY) return NULL;
  80. while ((unsigned long)start_address + size < TOP_MEMORY)
  81. {
  82. VirtualQuery (start_address, &info, sizeof (info));
  83. if ((info.State == MEM_FREE) && (info.RegionSize >= size))
  84. return start_address;
  85. else
  86. {
  87. /* Requested region is not available so see if the */
  88. /* next region is available. Set 'start_address' */
  89. /* to the next region and call 'VirtualQuery()' */
  90. /* again. */
  91. start_address = (char*)info.BaseAddress + info.RegionSize;
  92. /* Make sure we start looking for the next region */
  93. /* on the *next* 64K boundary. Otherwise, even if */
  94. /* the new region is free according to */
  95. /* 'VirtualQuery()', the subsequent call to */
  96. /* 'VirtualAlloc()' (which follows the call to */
  97. /* this routine in 'wsbrk()') will round *down* */
  98. /* the requested address to a 64K boundary which */
  99. /* we already know is an address in the */
  100. /* unavailable region. Thus, the subsequent call */
  101. /* to 'VirtualAlloc()' will fail and bring us back */
  102. /* here, causing us to go into an infinite loop. */
  103. start_address =
  104. (void *) AlignPage64K((unsigned long) start_address);
  105. }
  106. }
  107. return NULL;
  108. }
  109. void* wsbrk (long size)
  110. {
  111. void* tmp;
  112. if (size > 0)
  113. {
  114. if (gAddressBase == 0)
  115. {
  116. gAllocatedSize = max (RESERVED_SIZE, AlignPage (size));
  117. gNextAddress = gAddressBase =
  118. (unsigned int)VirtualAlloc (NULL, gAllocatedSize,
  119. MEM_RESERVE, PAGE_NOACCESS);
  120. } else if (AlignPage (gNextAddress + size) > (gAddressBase +
  121. gAllocatedSize))
  122. {
  123. long new_size = max (NEXT_SIZE, AlignPage (size));
  124. void* new_address = (void*)(gAddressBase+gAllocatedSize);
  125. do
  126. {
  127. new_address = findRegion (new_address, new_size);
  128. if (!new_address)
  129. return (void*)-1;
  130. gAddressBase = gNextAddress =
  131. (unsigned int)VirtualAlloc (new_address, new_size,
  132. MEM_RESERVE, PAGE_NOACCESS);
  133. /* repeat in case of race condition */
  134. /* The region that we found has been snagged */
  135. /* by another thread */
  136. }
  137. while (gAddressBase == 0);
  138. assert (new_address == (void*)gAddressBase);
  139. gAllocatedSize = new_size;
  140. if (!makeGmListElement ((void*)gAddressBase))
  141. return (void*)-1;
  142. }
  143. if ((size + gNextAddress) > AlignPage (gNextAddress))
  144. {
  145. void* res;
  146. res = VirtualAlloc ((void*)AlignPage (gNextAddress),
  147. (size + gNextAddress -
  148. AlignPage (gNextAddress)),
  149. MEM_COMMIT, PAGE_READWRITE);
  150. if (!res)
  151. return (void*)-1;
  152. }
  153. tmp = (void*)gNextAddress;
  154. gNextAddress = (unsigned int)tmp + size;
  155. return tmp;
  156. }
  157. else if (size < 0)
  158. {
  159. unsigned int alignedGoal = AlignPage (gNextAddress + size);
  160. /* Trim by releasing the virtual memory */
  161. if (alignedGoal >= gAddressBase)
  162. {
  163. VirtualFree ((void*)alignedGoal, gNextAddress - alignedGoal,
  164. MEM_DECOMMIT);
  165. gNextAddress = gNextAddress + size;
  166. return (void*)gNextAddress;
  167. }
  168. else
  169. {
  170. VirtualFree ((void*)gAddressBase, gNextAddress - gAddressBase,
  171. MEM_DECOMMIT);
  172. gNextAddress = gAddressBase;
  173. return (void*)-1;
  174. }
  175. }
  176. else
  177. {
  178. return (void*)gNextAddress;
  179. }
  180. }
  181. #endif
  182. /*
  183. Type declarations
  184. */
  185. struct malloc_chunk
  186. {
  187. INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
  188. INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
  189. struct malloc_chunk* fd; /* double links -- used only if free. */
  190. struct malloc_chunk* bk;
  191. } __attribute__((__may_alias__)) ;
  192. typedef struct malloc_chunk* mchunkptr;
  193. /*
  194. malloc_chunk details:
  195. (The following includes lightly edited explanations by Colin Plumb.)
  196. Chunks of memory are maintained using a `boundary tag' method as
  197. described in e.g., Knuth or Standish. (See the paper by Paul
  198. Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
  199. survey of such techniques.) Sizes of free chunks are stored both
  200. in the front of each chunk and at the end. This makes
  201. consolidating fragmented chunks into bigger chunks very fast. The
  202. size fields also hold bits representing whether chunks are free or
  203. in use.
  204. An allocated chunk looks like this:
  205. chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  206. | Size of previous chunk, if allocated | |
  207. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  208. | Size of chunk, in bytes |P|
  209. mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  210. | User data starts here... .
  211. . .
  212. . (malloc_usable_space() bytes) .
  213. . |
  214. nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  215. | Size of chunk |
  216. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  217. Where "chunk" is the front of the chunk for the purpose of most of
  218. the malloc code, but "mem" is the pointer that is returned to the
  219. user. "Nextchunk" is the beginning of the next contiguous chunk.
  220. Chunks always begin on even word boundries, so the mem portion
  221. (which is returned to the user) is also on an even word boundary, and
  222. thus double-word aligned.
  223. Free chunks are stored in circular doubly-linked lists, and look like this:
  224. chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  225. | Size of previous chunk |
  226. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  227. `head:' | Size of chunk, in bytes |P|
  228. mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  229. | Forward pointer to next chunk in list |
  230. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  231. | Back pointer to previous chunk in list |
  232. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  233. | Unused space (may be 0 bytes long) .
  234. . .
  235. . |
  236. nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  237. `foot:' | Size of chunk, in bytes |
  238. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  239. The P (PREV_INUSE) bit, stored in the unused low-order bit of the
  240. chunk size (which is always a multiple of two words), is an in-use
  241. bit for the *previous* chunk. If that bit is *clear*, then the
  242. word before the current chunk size contains the previous chunk
  243. size, and can be used to find the front of the previous chunk.
  244. (The very first chunk allocated always has this bit set,
  245. preventing access to non-existent (or non-owned) memory.)
  246. Note that the `foot' of the current chunk is actually represented
  247. as the prev_size of the NEXT chunk. (This makes it easier to
  248. deal with alignments etc).
  249. The two exceptions to all this are
  250. 1. The special chunk `top', which doesn't bother using the
  251. trailing size field since there is no
  252. next contiguous chunk that would have to index off it. (After
  253. initialization, `top' is forced to always exist. If it would
  254. become less than MINSIZE bytes long, it is replenished via
  255. malloc_extend_top.)
  256. 2. Chunks allocated via mmap, which have the second-lowest-order
  257. bit (IS_MMAPPED) set in their size fields. Because they are
  258. never merged or traversed from any other chunk, they have no
  259. foot size or inuse information.
  260. Available chunks are kept in any of several places (all declared below):
  261. * `av': An array of chunks serving as bin headers for consolidated
  262. chunks. Each bin is doubly linked. The bins are approximately
  263. proportionally (log) spaced. There are a lot of these bins
  264. (128). This may look excessive, but works very well in
  265. practice. All procedures maintain the invariant that no
  266. consolidated chunk physically borders another one. Chunks in
  267. bins are kept in size order, with ties going to the
  268. approximately least recently used chunk.
  269. The chunks in each bin are maintained in decreasing sorted order by
  270. size. This is irrelevant for the small bins, which all contain
  271. the same-sized chunks, but facilitates best-fit allocation for
  272. larger chunks. (These lists are just sequential. Keeping them in
  273. order almost never requires enough traversal to warrant using
  274. fancier ordered data structures.) Chunks of the same size are
  275. linked with the most recently freed at the front, and allocations
  276. are taken from the back. This results in LRU or FIFO allocation
  277. order, which tends to give each chunk an equal opportunity to be
  278. consolidated with adjacent freed chunks, resulting in larger free
  279. chunks and less fragmentation.
  280. * `top': The top-most available chunk (i.e., the one bordering the
  281. end of available memory) is treated specially. It is never
  282. included in any bin, is used only if no other chunk is
  283. available, and is released back to the system if it is very
  284. large (see M_TRIM_THRESHOLD).
  285. * `last_remainder': A bin holding only the remainder of the
  286. most recently split (non-top) chunk. This bin is checked
  287. before other non-fitting chunks, so as to provide better
  288. locality for runs of sequentially allocated chunks.
  289. * Implicitly, through the host system's memory mapping tables.
  290. If supported, requests greater than a threshold are usually
  291. serviced via calls to mmap, and then later released via munmap.
  292. */
  293. /* sizes, alignments */
  294. #define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
  295. #define MALLOC_ALIGNMENT (SIZE_SZ + SIZE_SZ)
  296. #define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
  297. #define MINSIZE (sizeof(struct malloc_chunk))
  298. /* conversion from malloc headers to user pointers, and back */
  299. #define chunk2mem(p) ((Void_t*)((char*)(p) + 2*SIZE_SZ))
  300. #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
  301. /* pad request bytes into a usable size */
  302. #define request2size(req) \
  303. (((long)((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) < \
  304. (long)(MINSIZE + MALLOC_ALIGN_MASK)) ? MINSIZE : \
  305. (((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) & ~(MALLOC_ALIGN_MASK)))
  306. /* Check if m has acceptable alignment */
  307. #define aligned_OK(m) (((unsigned long)((m)) & (MALLOC_ALIGN_MASK)) == 0)
  308. /*
  309. Physical chunk operations
  310. */
  311. /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
  312. #define PREV_INUSE 0x1
  313. /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
  314. #define IS_MMAPPED 0x2
  315. /* Bits to mask off when extracting size */
  316. #define SIZE_BITS (PREV_INUSE|IS_MMAPPED)
  317. /* Ptr to next physical malloc_chunk. */
  318. #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~PREV_INUSE) ))
  319. /* Ptr to previous physical malloc_chunk */
  320. #define prev_chunk(p)\
  321. ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
  322. /* Treat space at ptr + offset as a chunk */
  323. #define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
  324. /*
  325. Dealing with use bits
  326. */
  327. /* extract p's inuse bit */
  328. #define inuse(p)\
  329. ((((mchunkptr)(((char*)(p))+((p)->size & ~PREV_INUSE)))->size) & PREV_INUSE)
  330. /* extract inuse bit of previous chunk */
  331. #define prev_inuse(p) ((p)->size & PREV_INUSE)
  332. /* check for mmap()'ed chunk */
  333. #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
  334. /* set/clear chunk as in use without otherwise disturbing */
  335. #define set_inuse(p)\
  336. ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size |= PREV_INUSE
  337. #define clear_inuse(p)\
  338. ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size &= ~(PREV_INUSE)
  339. /* check/set/clear inuse bits in known places */
  340. #define inuse_bit_at_offset(p, s)\
  341. (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)
  342. #define set_inuse_bit_at_offset(p, s)\
  343. (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
  344. #define clear_inuse_bit_at_offset(p, s)\
  345. (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
  346. /*
  347. Dealing with size fields
  348. */
  349. /* Get size, ignoring use bits */
  350. #define chunksize(p) ((p)->size & ~(SIZE_BITS))
  351. /* Set size at head, without disturbing its use bit */
  352. #define set_head_size(p, s) ((p)->size = (((p)->size & PREV_INUSE) | (s)))
  353. /* Set size/use ignoring previous bits in header */
  354. #define set_head(p, s) ((p)->size = (s))
  355. /* Set size at footer (only when chunk is not in use) */
  356. #define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))
  357. /*
  358. Bins
  359. The bins, `av_' are an array of pairs of pointers serving as the
  360. heads of (initially empty) doubly-linked lists of chunks, laid out
  361. in a way so that each pair can be treated as if it were in a
  362. malloc_chunk. (This way, the fd/bk offsets for linking bin heads
  363. and chunks are the same).
  364. Bins for sizes < 512 bytes contain chunks of all the same size, spaced
  365. 8 bytes apart. Larger bins are approximately logarithmically
  366. spaced. (See the table below.) The `av_' array is never mentioned
  367. directly in the code, but instead via bin access macros.
  368. Bin layout:
  369. 64 bins of size 8
  370. 32 bins of size 64
  371. 16 bins of size 512
  372. 8 bins of size 4096
  373. 4 bins of size 32768
  374. 2 bins of size 262144
  375. 1 bin of size what's left
  376. There is actually a little bit of slop in the numbers in bin_index
  377. for the sake of speed. This makes no difference elsewhere.
  378. The special chunks `top' and `last_remainder' get their own bins,
  379. (this is implemented via yet more trickery with the av_ array),
  380. although `top' is never properly linked to its bin since it is
  381. always handled specially.
  382. */
  383. #define NAV 128 /* number of bins */
  384. typedef struct malloc_chunk* mbinptr;
  385. /* access macros */
  386. #define bin_at(i) ((mbinptr)((char*)&(av_[2*(i) + 2]) - 2*SIZE_SZ))
  387. #define next_bin(b) ((mbinptr)((char*)(b) + 2 * sizeof(mbinptr)))
  388. #define prev_bin(b) ((mbinptr)((char*)(b) - 2 * sizeof(mbinptr)))
  389. /*
  390. The first 2 bins are never indexed. The corresponding av_ cells are instead
  391. used for bookkeeping. This is not to save space, but to simplify
  392. indexing, maintain locality, and avoid some initialization tests.
  393. */
  394. #define top (av_[2]) /* The topmost chunk */
  395. #define last_remainder (bin_at(1)) /* remainder from last split */
  396. /*
  397. Because top initially points to its own bin with initial
  398. zero size, thus forcing extension on the first malloc request,
  399. we avoid having any special code in malloc to check whether
  400. it even exists yet. But we still need to in malloc_extend_top.
  401. */
  402. #define initial_top ((mchunkptr)(bin_at(0)))
  403. /* Helper macro to initialize bins */
  404. #define IAV(i) bin_at(i), bin_at(i)
  405. static mbinptr av_[NAV * 2 + 2] = {
  406. NULL, NULL,
  407. IAV(0), IAV(1), IAV(2), IAV(3), IAV(4), IAV(5), IAV(6), IAV(7),
  408. IAV(8), IAV(9), IAV(10), IAV(11), IAV(12), IAV(13), IAV(14), IAV(15),
  409. IAV(16), IAV(17), IAV(18), IAV(19), IAV(20), IAV(21), IAV(22), IAV(23),
  410. IAV(24), IAV(25), IAV(26), IAV(27), IAV(28), IAV(29), IAV(30), IAV(31),
  411. IAV(32), IAV(33), IAV(34), IAV(35), IAV(36), IAV(37), IAV(38), IAV(39),
  412. IAV(40), IAV(41), IAV(42), IAV(43), IAV(44), IAV(45), IAV(46), IAV(47),
  413. IAV(48), IAV(49), IAV(50), IAV(51), IAV(52), IAV(53), IAV(54), IAV(55),
  414. IAV(56), IAV(57), IAV(58), IAV(59), IAV(60), IAV(61), IAV(62), IAV(63),
  415. IAV(64), IAV(65), IAV(66), IAV(67), IAV(68), IAV(69), IAV(70), IAV(71),
  416. IAV(72), IAV(73), IAV(74), IAV(75), IAV(76), IAV(77), IAV(78), IAV(79),
  417. IAV(80), IAV(81), IAV(82), IAV(83), IAV(84), IAV(85), IAV(86), IAV(87),
  418. IAV(88), IAV(89), IAV(90), IAV(91), IAV(92), IAV(93), IAV(94), IAV(95),
  419. IAV(96), IAV(97), IAV(98), IAV(99), IAV(100), IAV(101), IAV(102), IAV(103),
  420. IAV(104), IAV(105), IAV(106), IAV(107), IAV(108), IAV(109), IAV(110), IAV(111),
  421. IAV(112), IAV(113), IAV(114), IAV(115), IAV(116), IAV(117), IAV(118), IAV(119),
  422. IAV(120), IAV(121), IAV(122), IAV(123), IAV(124), IAV(125), IAV(126), IAV(127)
  423. };
  424. #ifdef CONFIG_NEEDS_MANUAL_RELOC
  425. static void malloc_bin_reloc(void)
  426. {
  427. mbinptr *p = &av_[2];
  428. size_t i;
  429. for (i = 2; i < ARRAY_SIZE(av_); ++i, ++p)
  430. *p = (mbinptr)((ulong)*p + gd->reloc_off);
  431. }
  432. #else
  433. static inline void malloc_bin_reloc(void) {}
  434. #endif
  435. ulong mem_malloc_start = 0;
  436. ulong mem_malloc_end = 0;
  437. ulong mem_malloc_brk = 0;
  438. void *sbrk(ptrdiff_t increment)
  439. {
  440. ulong old = mem_malloc_brk;
  441. ulong new = old + increment;
  442. /*
  443. * if we are giving memory back make sure we clear it out since
  444. * we set MORECORE_CLEARS to 1
  445. */
  446. if (increment < 0)
  447. memset((void *)new, 0, -increment);
  448. if ((new < mem_malloc_start) || (new > mem_malloc_end))
  449. return (void *)MORECORE_FAILURE;
  450. mem_malloc_brk = new;
  451. return (void *)old;
  452. }
  453. void mem_malloc_init(ulong start, ulong size)
  454. {
  455. mem_malloc_start = start;
  456. mem_malloc_end = start + size;
  457. mem_malloc_brk = start;
  458. debug("using memory %#lx-%#lx for malloc()\n", mem_malloc_start,
  459. mem_malloc_end);
  460. #ifdef CONFIG_SYS_MALLOC_CLEAR_ON_INIT
  461. memset((void *)mem_malloc_start, 0x0, size);
  462. #endif
  463. malloc_bin_reloc();
  464. }
  465. /* field-extraction macros */
  466. #define first(b) ((b)->fd)
  467. #define last(b) ((b)->bk)
  468. /*
  469. Indexing into bins
  470. */
  471. #define bin_index(sz) \
  472. (((((unsigned long)(sz)) >> 9) == 0) ? (((unsigned long)(sz)) >> 3): \
  473. ((((unsigned long)(sz)) >> 9) <= 4) ? 56 + (((unsigned long)(sz)) >> 6): \
  474. ((((unsigned long)(sz)) >> 9) <= 20) ? 91 + (((unsigned long)(sz)) >> 9): \
  475. ((((unsigned long)(sz)) >> 9) <= 84) ? 110 + (((unsigned long)(sz)) >> 12): \
  476. ((((unsigned long)(sz)) >> 9) <= 340) ? 119 + (((unsigned long)(sz)) >> 15): \
  477. ((((unsigned long)(sz)) >> 9) <= 1364) ? 124 + (((unsigned long)(sz)) >> 18): \
  478. 126)
  479. /*
  480. bins for chunks < 512 are all spaced 8 bytes apart, and hold
  481. identically sized chunks. This is exploited in malloc.
  482. */
  483. #define MAX_SMALLBIN 63
  484. #define MAX_SMALLBIN_SIZE 512
  485. #define SMALLBIN_WIDTH 8
  486. #define smallbin_index(sz) (((unsigned long)(sz)) >> 3)
  487. /*
  488. Requests are `small' if both the corresponding and the next bin are small
  489. */
  490. #define is_small_request(nb) (nb < MAX_SMALLBIN_SIZE - SMALLBIN_WIDTH)
  491. /*
  492. To help compensate for the large number of bins, a one-level index
  493. structure is used for bin-by-bin searching. `binblocks' is a
  494. one-word bitvector recording whether groups of BINBLOCKWIDTH bins
  495. have any (possibly) non-empty bins, so they can be skipped over
  496. all at once during during traversals. The bits are NOT always
  497. cleared as soon as all bins in a block are empty, but instead only
  498. when all are noticed to be empty during traversal in malloc.
  499. */
  500. #define BINBLOCKWIDTH 4 /* bins per block */
  501. #define binblocks_r ((INTERNAL_SIZE_T)av_[1]) /* bitvector of nonempty blocks */
  502. #define binblocks_w (av_[1])
  503. /* bin<->block macros */
  504. #define idx2binblock(ix) ((unsigned)1 << (ix / BINBLOCKWIDTH))
  505. #define mark_binblock(ii) (binblocks_w = (mbinptr)(binblocks_r | idx2binblock(ii)))
  506. #define clear_binblock(ii) (binblocks_w = (mbinptr)(binblocks_r & ~(idx2binblock(ii))))
  507. /* Other static bookkeeping data */
  508. /* variables holding tunable values */
  509. static unsigned long trim_threshold = DEFAULT_TRIM_THRESHOLD;
  510. static unsigned long top_pad = DEFAULT_TOP_PAD;
  511. static unsigned int n_mmaps_max = DEFAULT_MMAP_MAX;
  512. static unsigned long mmap_threshold = DEFAULT_MMAP_THRESHOLD;
  513. /* The first value returned from sbrk */
  514. static char* sbrk_base = (char*)(-1);
  515. /* The maximum memory obtained from system via sbrk */
  516. static unsigned long max_sbrked_mem = 0;
  517. /* The maximum via either sbrk or mmap */
  518. static unsigned long max_total_mem = 0;
  519. /* internal working copy of mallinfo */
  520. static struct mallinfo current_mallinfo = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  521. /* The total memory obtained from system via sbrk */
  522. #define sbrked_mem (current_mallinfo.arena)
  523. /* Tracking mmaps */
  524. #ifdef DEBUG
  525. static unsigned int n_mmaps = 0;
  526. #endif /* DEBUG */
  527. static unsigned long mmapped_mem = 0;
  528. #if HAVE_MMAP
  529. static unsigned int max_n_mmaps = 0;
  530. static unsigned long max_mmapped_mem = 0;
  531. #endif
  532. /*
  533. Debugging support
  534. */
  535. #ifdef DEBUG
  536. /*
  537. These routines make a number of assertions about the states
  538. of data structures that should be true at all times. If any
  539. are not true, it's very likely that a user program has somehow
  540. trashed memory. (It's also possible that there is a coding error
  541. in malloc. In which case, please report it!)
  542. */
  543. #if __STD_C
  544. static void do_check_chunk(mchunkptr p)
  545. #else
  546. static void do_check_chunk(p) mchunkptr p;
  547. #endif
  548. {
  549. INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
  550. /* No checkable chunk is mmapped */
  551. assert(!chunk_is_mmapped(p));
  552. /* Check for legal address ... */
  553. assert((char*)p >= sbrk_base);
  554. if (p != top)
  555. assert((char*)p + sz <= (char*)top);
  556. else
  557. assert((char*)p + sz <= sbrk_base + sbrked_mem);
  558. }
  559. #if __STD_C
  560. static void do_check_free_chunk(mchunkptr p)
  561. #else
  562. static void do_check_free_chunk(p) mchunkptr p;
  563. #endif
  564. {
  565. INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
  566. mchunkptr next = chunk_at_offset(p, sz);
  567. do_check_chunk(p);
  568. /* Check whether it claims to be free ... */
  569. assert(!inuse(p));
  570. /* Unless a special marker, must have OK fields */
  571. if ((long)sz >= (long)MINSIZE)
  572. {
  573. assert((sz & MALLOC_ALIGN_MASK) == 0);
  574. assert(aligned_OK(chunk2mem(p)));
  575. /* ... matching footer field */
  576. assert(next->prev_size == sz);
  577. /* ... and is fully consolidated */
  578. assert(prev_inuse(p));
  579. assert (next == top || inuse(next));
  580. /* ... and has minimally sane links */
  581. assert(p->fd->bk == p);
  582. assert(p->bk->fd == p);
  583. }
  584. else /* markers are always of size SIZE_SZ */
  585. assert(sz == SIZE_SZ);
  586. }
  587. #if __STD_C
  588. static void do_check_inuse_chunk(mchunkptr p)
  589. #else
  590. static void do_check_inuse_chunk(p) mchunkptr p;
  591. #endif
  592. {
  593. mchunkptr next = next_chunk(p);
  594. do_check_chunk(p);
  595. /* Check whether it claims to be in use ... */
  596. assert(inuse(p));
  597. /* ... and is surrounded by OK chunks.
  598. Since more things can be checked with free chunks than inuse ones,
  599. if an inuse chunk borders them and debug is on, it's worth doing them.
  600. */
  601. if (!prev_inuse(p))
  602. {
  603. mchunkptr prv = prev_chunk(p);
  604. assert(next_chunk(prv) == p);
  605. do_check_free_chunk(prv);
  606. }
  607. if (next == top)
  608. {
  609. assert(prev_inuse(next));
  610. assert(chunksize(next) >= MINSIZE);
  611. }
  612. else if (!inuse(next))
  613. do_check_free_chunk(next);
  614. }
  615. #if __STD_C
  616. static void do_check_malloced_chunk(mchunkptr p, INTERNAL_SIZE_T s)
  617. #else
  618. static void do_check_malloced_chunk(p, s) mchunkptr p; INTERNAL_SIZE_T s;
  619. #endif
  620. {
  621. INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
  622. long room = sz - s;
  623. do_check_inuse_chunk(p);
  624. /* Legal size ... */
  625. assert((long)sz >= (long)MINSIZE);
  626. assert((sz & MALLOC_ALIGN_MASK) == 0);
  627. assert(room >= 0);
  628. assert(room < (long)MINSIZE);
  629. /* ... and alignment */
  630. assert(aligned_OK(chunk2mem(p)));
  631. /* ... and was allocated at front of an available chunk */
  632. assert(prev_inuse(p));
  633. }
  634. #define check_free_chunk(P) do_check_free_chunk(P)
  635. #define check_inuse_chunk(P) do_check_inuse_chunk(P)
  636. #define check_chunk(P) do_check_chunk(P)
  637. #define check_malloced_chunk(P,N) do_check_malloced_chunk(P,N)
  638. #else
  639. #define check_free_chunk(P)
  640. #define check_inuse_chunk(P)
  641. #define check_chunk(P)
  642. #define check_malloced_chunk(P,N)
  643. #endif
  644. /*
  645. Macro-based internal utilities
  646. */
  647. /*
  648. Linking chunks in bin lists.
  649. Call these only with variables, not arbitrary expressions, as arguments.
  650. */
  651. /*
  652. Place chunk p of size s in its bin, in size order,
  653. putting it ahead of others of same size.
  654. */
  655. #define frontlink(P, S, IDX, BK, FD) \
  656. { \
  657. if (S < MAX_SMALLBIN_SIZE) \
  658. { \
  659. IDX = smallbin_index(S); \
  660. mark_binblock(IDX); \
  661. BK = bin_at(IDX); \
  662. FD = BK->fd; \
  663. P->bk = BK; \
  664. P->fd = FD; \
  665. FD->bk = BK->fd = P; \
  666. } \
  667. else \
  668. { \
  669. IDX = bin_index(S); \
  670. BK = bin_at(IDX); \
  671. FD = BK->fd; \
  672. if (FD == BK) mark_binblock(IDX); \
  673. else \
  674. { \
  675. while (FD != BK && S < chunksize(FD)) FD = FD->fd; \
  676. BK = FD->bk; \
  677. } \
  678. P->bk = BK; \
  679. P->fd = FD; \
  680. FD->bk = BK->fd = P; \
  681. } \
  682. }
  683. /* take a chunk off a list */
  684. #define unlink(P, BK, FD) \
  685. { \
  686. BK = P->bk; \
  687. FD = P->fd; \
  688. FD->bk = BK; \
  689. BK->fd = FD; \
  690. } \
  691. /* Place p as the last remainder */
  692. #define link_last_remainder(P) \
  693. { \
  694. last_remainder->fd = last_remainder->bk = P; \
  695. P->fd = P->bk = last_remainder; \
  696. }
  697. /* Clear the last_remainder bin */
  698. #define clear_last_remainder \
  699. (last_remainder->fd = last_remainder->bk = last_remainder)
  700. /* Routines dealing with mmap(). */
  701. #if HAVE_MMAP
  702. #if __STD_C
  703. static mchunkptr mmap_chunk(size_t size)
  704. #else
  705. static mchunkptr mmap_chunk(size) size_t size;
  706. #endif
  707. {
  708. size_t page_mask = malloc_getpagesize - 1;
  709. mchunkptr p;
  710. #ifndef MAP_ANONYMOUS
  711. static int fd = -1;
  712. #endif
  713. if(n_mmaps >= n_mmaps_max) return 0; /* too many regions */
  714. /* For mmapped chunks, the overhead is one SIZE_SZ unit larger, because
  715. * there is no following chunk whose prev_size field could be used.
  716. */
  717. size = (size + SIZE_SZ + page_mask) & ~page_mask;
  718. #ifdef MAP_ANONYMOUS
  719. p = (mchunkptr)mmap(0, size, PROT_READ|PROT_WRITE,
  720. MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  721. #else /* !MAP_ANONYMOUS */
  722. if (fd < 0)
  723. {
  724. fd = open("/dev/zero", O_RDWR);
  725. if(fd < 0) return 0;
  726. }
  727. p = (mchunkptr)mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
  728. #endif
  729. if(p == (mchunkptr)-1) return 0;
  730. n_mmaps++;
  731. if (n_mmaps > max_n_mmaps) max_n_mmaps = n_mmaps;
  732. /* We demand that eight bytes into a page must be 8-byte aligned. */
  733. assert(aligned_OK(chunk2mem(p)));
  734. /* The offset to the start of the mmapped region is stored
  735. * in the prev_size field of the chunk; normally it is zero,
  736. * but that can be changed in memalign().
  737. */
  738. p->prev_size = 0;
  739. set_head(p, size|IS_MMAPPED);
  740. mmapped_mem += size;
  741. if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
  742. max_mmapped_mem = mmapped_mem;
  743. if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
  744. max_total_mem = mmapped_mem + sbrked_mem;
  745. return p;
  746. }
  747. #if __STD_C
  748. static void munmap_chunk(mchunkptr p)
  749. #else
  750. static void munmap_chunk(p) mchunkptr p;
  751. #endif
  752. {
  753. INTERNAL_SIZE_T size = chunksize(p);
  754. int ret;
  755. assert (chunk_is_mmapped(p));
  756. assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
  757. assert((n_mmaps > 0));
  758. assert(((p->prev_size + size) & (malloc_getpagesize-1)) == 0);
  759. n_mmaps--;
  760. mmapped_mem -= (size + p->prev_size);
  761. ret = munmap((char *)p - p->prev_size, size + p->prev_size);
  762. /* munmap returns non-zero on failure */
  763. assert(ret == 0);
  764. }
  765. #if HAVE_MREMAP
  766. #if __STD_C
  767. static mchunkptr mremap_chunk(mchunkptr p, size_t new_size)
  768. #else
  769. static mchunkptr mremap_chunk(p, new_size) mchunkptr p; size_t new_size;
  770. #endif
  771. {
  772. size_t page_mask = malloc_getpagesize - 1;
  773. INTERNAL_SIZE_T offset = p->prev_size;
  774. INTERNAL_SIZE_T size = chunksize(p);
  775. char *cp;
  776. assert (chunk_is_mmapped(p));
  777. assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
  778. assert((n_mmaps > 0));
  779. assert(((size + offset) & (malloc_getpagesize-1)) == 0);
  780. /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
  781. new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask;
  782. cp = (char *)mremap((char *)p - offset, size + offset, new_size, 1);
  783. if (cp == (char *)-1) return 0;
  784. p = (mchunkptr)(cp + offset);
  785. assert(aligned_OK(chunk2mem(p)));
  786. assert((p->prev_size == offset));
  787. set_head(p, (new_size - offset)|IS_MMAPPED);
  788. mmapped_mem -= size + offset;
  789. mmapped_mem += new_size;
  790. if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
  791. max_mmapped_mem = mmapped_mem;
  792. if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
  793. max_total_mem = mmapped_mem + sbrked_mem;
  794. return p;
  795. }
  796. #endif /* HAVE_MREMAP */
  797. #endif /* HAVE_MMAP */
  798. /*
  799. Extend the top-most chunk by obtaining memory from system.
  800. Main interface to sbrk (but see also malloc_trim).
  801. */
  802. #if __STD_C
  803. static void malloc_extend_top(INTERNAL_SIZE_T nb)
  804. #else
  805. static void malloc_extend_top(nb) INTERNAL_SIZE_T nb;
  806. #endif
  807. {
  808. char* brk; /* return value from sbrk */
  809. INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of sbrked space */
  810. INTERNAL_SIZE_T correction; /* bytes for 2nd sbrk call */
  811. char* new_brk; /* return of 2nd sbrk call */
  812. INTERNAL_SIZE_T top_size; /* new size of top chunk */
  813. mchunkptr old_top = top; /* Record state of old top */
  814. INTERNAL_SIZE_T old_top_size = chunksize(old_top);
  815. char* old_end = (char*)(chunk_at_offset(old_top, old_top_size));
  816. /* Pad request with top_pad plus minimal overhead */
  817. INTERNAL_SIZE_T sbrk_size = nb + top_pad + MINSIZE;
  818. unsigned long pagesz = malloc_getpagesize;
  819. /* If not the first time through, round to preserve page boundary */
  820. /* Otherwise, we need to correct to a page size below anyway. */
  821. /* (We also correct below if an intervening foreign sbrk call.) */
  822. if (sbrk_base != (char*)(-1))
  823. sbrk_size = (sbrk_size + (pagesz - 1)) & ~(pagesz - 1);
  824. brk = (char*)(MORECORE (sbrk_size));
  825. /* Fail if sbrk failed or if a foreign sbrk call killed our space */
  826. if (brk == (char*)(MORECORE_FAILURE) ||
  827. (brk < old_end && old_top != initial_top))
  828. return;
  829. sbrked_mem += sbrk_size;
  830. if (brk == old_end) /* can just add bytes to current top */
  831. {
  832. top_size = sbrk_size + old_top_size;
  833. set_head(top, top_size | PREV_INUSE);
  834. }
  835. else
  836. {
  837. if (sbrk_base == (char*)(-1)) /* First time through. Record base */
  838. sbrk_base = brk;
  839. else /* Someone else called sbrk(). Count those bytes as sbrked_mem. */
  840. sbrked_mem += brk - (char*)old_end;
  841. /* Guarantee alignment of first new chunk made from this space */
  842. front_misalign = (unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK;
  843. if (front_misalign > 0)
  844. {
  845. correction = (MALLOC_ALIGNMENT) - front_misalign;
  846. brk += correction;
  847. }
  848. else
  849. correction = 0;
  850. /* Guarantee the next brk will be at a page boundary */
  851. correction += ((((unsigned long)(brk + sbrk_size))+(pagesz-1)) &
  852. ~(pagesz - 1)) - ((unsigned long)(brk + sbrk_size));
  853. /* Allocate correction */
  854. new_brk = (char*)(MORECORE (correction));
  855. if (new_brk == (char*)(MORECORE_FAILURE)) return;
  856. sbrked_mem += correction;
  857. top = (mchunkptr)brk;
  858. top_size = new_brk - brk + correction;
  859. set_head(top, top_size | PREV_INUSE);
  860. if (old_top != initial_top)
  861. {
  862. /* There must have been an intervening foreign sbrk call. */
  863. /* A double fencepost is necessary to prevent consolidation */
  864. /* If not enough space to do this, then user did something very wrong */
  865. if (old_top_size < MINSIZE)
  866. {
  867. set_head(top, PREV_INUSE); /* will force null return from malloc */
  868. return;
  869. }
  870. /* Also keep size a multiple of MALLOC_ALIGNMENT */
  871. old_top_size = (old_top_size - 3*SIZE_SZ) & ~MALLOC_ALIGN_MASK;
  872. set_head_size(old_top, old_top_size);
  873. chunk_at_offset(old_top, old_top_size )->size =
  874. SIZE_SZ|PREV_INUSE;
  875. chunk_at_offset(old_top, old_top_size + SIZE_SZ)->size =
  876. SIZE_SZ|PREV_INUSE;
  877. /* If possible, release the rest. */
  878. if (old_top_size >= MINSIZE)
  879. fREe(chunk2mem(old_top));
  880. }
  881. }
  882. if ((unsigned long)sbrked_mem > (unsigned long)max_sbrked_mem)
  883. max_sbrked_mem = sbrked_mem;
  884. if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
  885. max_total_mem = mmapped_mem + sbrked_mem;
  886. /* We always land on a page boundary */
  887. assert(((unsigned long)((char*)top + top_size) & (pagesz - 1)) == 0);
  888. }
  889. /* Main public routines */
  890. /*
  891. Malloc Algorthim:
  892. The requested size is first converted into a usable form, `nb'.
  893. This currently means to add 4 bytes overhead plus possibly more to
  894. obtain 8-byte alignment and/or to obtain a size of at least
  895. MINSIZE (currently 16 bytes), the smallest allocatable size.
  896. (All fits are considered `exact' if they are within MINSIZE bytes.)
  897. From there, the first successful of the following steps is taken:
  898. 1. The bin corresponding to the request size is scanned, and if
  899. a chunk of exactly the right size is found, it is taken.
  900. 2. The most recently remaindered chunk is used if it is big
  901. enough. This is a form of (roving) first fit, used only in
  902. the absence of exact fits. Runs of consecutive requests use
  903. the remainder of the chunk used for the previous such request
  904. whenever possible. This limited use of a first-fit style
  905. allocation strategy tends to give contiguous chunks
  906. coextensive lifetimes, which improves locality and can reduce
  907. fragmentation in the long run.
  908. 3. Other bins are scanned in increasing size order, using a
  909. chunk big enough to fulfill the request, and splitting off
  910. any remainder. This search is strictly by best-fit; i.e.,
  911. the smallest (with ties going to approximately the least
  912. recently used) chunk that fits is selected.
  913. 4. If large enough, the chunk bordering the end of memory
  914. (`top') is split off. (This use of `top' is in accord with
  915. the best-fit search rule. In effect, `top' is treated as
  916. larger (and thus less well fitting) than any other available
  917. chunk since it can be extended to be as large as necessary
  918. (up to system limitations).
  919. 5. If the request size meets the mmap threshold and the
  920. system supports mmap, and there are few enough currently
  921. allocated mmapped regions, and a call to mmap succeeds,
  922. the request is allocated via direct memory mapping.
  923. 6. Otherwise, the top of memory is extended by
  924. obtaining more space from the system (normally using sbrk,
  925. but definable to anything else via the MORECORE macro).
  926. Memory is gathered from the system (in system page-sized
  927. units) in a way that allows chunks obtained across different
  928. sbrk calls to be consolidated, but does not require
  929. contiguous memory. Thus, it should be safe to intersperse
  930. mallocs with other sbrk calls.
  931. All allocations are made from the the `lowest' part of any found
  932. chunk. (The implementation invariant is that prev_inuse is
  933. always true of any allocated chunk; i.e., that each allocated
  934. chunk borders either a previously allocated and still in-use chunk,
  935. or the base of its memory arena.)
  936. */
  937. #if __STD_C
  938. Void_t* mALLOc(size_t bytes)
  939. #else
  940. Void_t* mALLOc(bytes) size_t bytes;
  941. #endif
  942. {
  943. mchunkptr victim; /* inspected/selected chunk */
  944. INTERNAL_SIZE_T victim_size; /* its size */
  945. int idx; /* index for bin traversal */
  946. mbinptr bin; /* associated bin */
  947. mchunkptr remainder; /* remainder from a split */
  948. long remainder_size; /* its size */
  949. int remainder_index; /* its bin index */
  950. unsigned long block; /* block traverser bit */
  951. int startidx; /* first bin of a traversed block */
  952. mchunkptr fwd; /* misc temp for linking */
  953. mchunkptr bck; /* misc temp for linking */
  954. mbinptr q; /* misc temp */
  955. INTERNAL_SIZE_T nb;
  956. #if CONFIG_VAL(SYS_MALLOC_F_LEN)
  957. if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT))
  958. return malloc_simple(bytes);
  959. #endif
  960. /* check if mem_malloc_init() was run */
  961. if ((mem_malloc_start == 0) && (mem_malloc_end == 0)) {
  962. /* not initialized yet */
  963. return NULL;
  964. }
  965. if ((long)bytes < 0) return NULL;
  966. nb = request2size(bytes); /* padded request size; */
  967. /* Check for exact match in a bin */
  968. if (is_small_request(nb)) /* Faster version for small requests */
  969. {
  970. idx = smallbin_index(nb);
  971. /* No traversal or size check necessary for small bins. */
  972. q = bin_at(idx);
  973. victim = last(q);
  974. /* Also scan the next one, since it would have a remainder < MINSIZE */
  975. if (victim == q)
  976. {
  977. q = next_bin(q);
  978. victim = last(q);
  979. }
  980. if (victim != q)
  981. {
  982. victim_size = chunksize(victim);
  983. unlink(victim, bck, fwd);
  984. set_inuse_bit_at_offset(victim, victim_size);
  985. check_malloced_chunk(victim, nb);
  986. return chunk2mem(victim);
  987. }
  988. idx += 2; /* Set for bin scan below. We've already scanned 2 bins. */
  989. }
  990. else
  991. {
  992. idx = bin_index(nb);
  993. bin = bin_at(idx);
  994. for (victim = last(bin); victim != bin; victim = victim->bk)
  995. {
  996. victim_size = chunksize(victim);
  997. remainder_size = victim_size - nb;
  998. if (remainder_size >= (long)MINSIZE) /* too big */
  999. {
  1000. --idx; /* adjust to rescan below after checking last remainder */
  1001. break;
  1002. }
  1003. else if (remainder_size >= 0) /* exact fit */
  1004. {
  1005. unlink(victim, bck, fwd);
  1006. set_inuse_bit_at_offset(victim, victim_size);
  1007. check_malloced_chunk(victim, nb);
  1008. return chunk2mem(victim);
  1009. }
  1010. }
  1011. ++idx;
  1012. }
  1013. /* Try to use the last split-off remainder */
  1014. if ( (victim = last_remainder->fd) != last_remainder)
  1015. {
  1016. victim_size = chunksize(victim);
  1017. remainder_size = victim_size - nb;
  1018. if (remainder_size >= (long)MINSIZE) /* re-split */
  1019. {
  1020. remainder = chunk_at_offset(victim, nb);
  1021. set_head(victim, nb | PREV_INUSE);
  1022. link_last_remainder(remainder);
  1023. set_head(remainder, remainder_size | PREV_INUSE);
  1024. set_foot(remainder, remainder_size);
  1025. check_malloced_chunk(victim, nb);
  1026. return chunk2mem(victim);
  1027. }
  1028. clear_last_remainder;
  1029. if (remainder_size >= 0) /* exhaust */
  1030. {
  1031. set_inuse_bit_at_offset(victim, victim_size);
  1032. check_malloced_chunk(victim, nb);
  1033. return chunk2mem(victim);
  1034. }
  1035. /* Else place in bin */
  1036. frontlink(victim, victim_size, remainder_index, bck, fwd);
  1037. }
  1038. /*
  1039. If there are any possibly nonempty big-enough blocks,
  1040. search for best fitting chunk by scanning bins in blockwidth units.
  1041. */
  1042. if ( (block = idx2binblock(idx)) <= binblocks_r)
  1043. {
  1044. /* Get to the first marked block */
  1045. if ( (block & binblocks_r) == 0)
  1046. {
  1047. /* force to an even block boundary */
  1048. idx = (idx & ~(BINBLOCKWIDTH - 1)) + BINBLOCKWIDTH;
  1049. block <<= 1;
  1050. while ((block & binblocks_r) == 0)
  1051. {
  1052. idx += BINBLOCKWIDTH;
  1053. block <<= 1;
  1054. }
  1055. }
  1056. /* For each possibly nonempty block ... */
  1057. for (;;)
  1058. {
  1059. startidx = idx; /* (track incomplete blocks) */
  1060. q = bin = bin_at(idx);
  1061. /* For each bin in this block ... */
  1062. do
  1063. {
  1064. /* Find and use first big enough chunk ... */
  1065. for (victim = last(bin); victim != bin; victim = victim->bk)
  1066. {
  1067. victim_size = chunksize(victim);
  1068. remainder_size = victim_size - nb;
  1069. if (remainder_size >= (long)MINSIZE) /* split */
  1070. {
  1071. remainder = chunk_at_offset(victim, nb);
  1072. set_head(victim, nb | PREV_INUSE);
  1073. unlink(victim, bck, fwd);
  1074. link_last_remainder(remainder);
  1075. set_head(remainder, remainder_size | PREV_INUSE);
  1076. set_foot(remainder, remainder_size);
  1077. check_malloced_chunk(victim, nb);
  1078. return chunk2mem(victim);
  1079. }
  1080. else if (remainder_size >= 0) /* take */
  1081. {
  1082. set_inuse_bit_at_offset(victim, victim_size);
  1083. unlink(victim, bck, fwd);
  1084. check_malloced_chunk(victim, nb);
  1085. return chunk2mem(victim);
  1086. }
  1087. }
  1088. bin = next_bin(bin);
  1089. } while ((++idx & (BINBLOCKWIDTH - 1)) != 0);
  1090. /* Clear out the block bit. */
  1091. do /* Possibly backtrack to try to clear a partial block */
  1092. {
  1093. if ((startidx & (BINBLOCKWIDTH - 1)) == 0)
  1094. {
  1095. av_[1] = (mbinptr)(binblocks_r & ~block);
  1096. break;
  1097. }
  1098. --startidx;
  1099. q = prev_bin(q);
  1100. } while (first(q) == q);
  1101. /* Get to the next possibly nonempty block */
  1102. if ( (block <<= 1) <= binblocks_r && (block != 0) )
  1103. {
  1104. while ((block & binblocks_r) == 0)
  1105. {
  1106. idx += BINBLOCKWIDTH;
  1107. block <<= 1;
  1108. }
  1109. }
  1110. else
  1111. break;
  1112. }
  1113. }
  1114. /* Try to use top chunk */
  1115. /* Require that there be a remainder, ensuring top always exists */
  1116. if ( (remainder_size = chunksize(top) - nb) < (long)MINSIZE)
  1117. {
  1118. #if HAVE_MMAP
  1119. /* If big and would otherwise need to extend, try to use mmap instead */
  1120. if ((unsigned long)nb >= (unsigned long)mmap_threshold &&
  1121. (victim = mmap_chunk(nb)))
  1122. return chunk2mem(victim);
  1123. #endif
  1124. /* Try to extend */
  1125. malloc_extend_top(nb);
  1126. if ( (remainder_size = chunksize(top) - nb) < (long)MINSIZE)
  1127. return NULL; /* propagate failure */
  1128. }
  1129. victim = top;
  1130. set_head(victim, nb | PREV_INUSE);
  1131. top = chunk_at_offset(victim, nb);
  1132. set_head(top, remainder_size | PREV_INUSE);
  1133. check_malloced_chunk(victim, nb);
  1134. return chunk2mem(victim);
  1135. }
  1136. /*
  1137. free() algorithm :
  1138. cases:
  1139. 1. free(0) has no effect.
  1140. 2. If the chunk was allocated via mmap, it is release via munmap().
  1141. 3. If a returned chunk borders the current high end of memory,
  1142. it is consolidated into the top, and if the total unused
  1143. topmost memory exceeds the trim threshold, malloc_trim is
  1144. called.
  1145. 4. Other chunks are consolidated as they arrive, and
  1146. placed in corresponding bins. (This includes the case of
  1147. consolidating with the current `last_remainder').
  1148. */
  1149. #if __STD_C
  1150. void fREe(Void_t* mem)
  1151. #else
  1152. void fREe(mem) Void_t* mem;
  1153. #endif
  1154. {
  1155. mchunkptr p; /* chunk corresponding to mem */
  1156. INTERNAL_SIZE_T hd; /* its head field */
  1157. INTERNAL_SIZE_T sz; /* its size */
  1158. int idx; /* its bin index */
  1159. mchunkptr next; /* next contiguous chunk */
  1160. INTERNAL_SIZE_T nextsz; /* its size */
  1161. INTERNAL_SIZE_T prevsz; /* size of previous contiguous chunk */
  1162. mchunkptr bck; /* misc temp for linking */
  1163. mchunkptr fwd; /* misc temp for linking */
  1164. int islr; /* track whether merging with last_remainder */
  1165. #if CONFIG_VAL(SYS_MALLOC_F_LEN)
  1166. /* free() is a no-op - all the memory will be freed on relocation */
  1167. if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT))
  1168. return;
  1169. #endif
  1170. if (mem == NULL) /* free(0) has no effect */
  1171. return;
  1172. p = mem2chunk(mem);
  1173. hd = p->size;
  1174. #if HAVE_MMAP
  1175. if (hd & IS_MMAPPED) /* release mmapped memory. */
  1176. {
  1177. munmap_chunk(p);
  1178. return;
  1179. }
  1180. #endif
  1181. check_inuse_chunk(p);
  1182. sz = hd & ~PREV_INUSE;
  1183. next = chunk_at_offset(p, sz);
  1184. nextsz = chunksize(next);
  1185. if (next == top) /* merge with top */
  1186. {
  1187. sz += nextsz;
  1188. if (!(hd & PREV_INUSE)) /* consolidate backward */
  1189. {
  1190. prevsz = p->prev_size;
  1191. p = chunk_at_offset(p, -((long) prevsz));
  1192. sz += prevsz;
  1193. unlink(p, bck, fwd);
  1194. }
  1195. set_head(p, sz | PREV_INUSE);
  1196. top = p;
  1197. if ((unsigned long)(sz) >= (unsigned long)trim_threshold)
  1198. malloc_trim(top_pad);
  1199. return;
  1200. }
  1201. set_head(next, nextsz); /* clear inuse bit */
  1202. islr = 0;
  1203. if (!(hd & PREV_INUSE)) /* consolidate backward */
  1204. {
  1205. prevsz = p->prev_size;
  1206. p = chunk_at_offset(p, -((long) prevsz));
  1207. sz += prevsz;
  1208. if (p->fd == last_remainder) /* keep as last_remainder */
  1209. islr = 1;
  1210. else
  1211. unlink(p, bck, fwd);
  1212. }
  1213. if (!(inuse_bit_at_offset(next, nextsz))) /* consolidate forward */
  1214. {
  1215. sz += nextsz;
  1216. if (!islr && next->fd == last_remainder) /* re-insert last_remainder */
  1217. {
  1218. islr = 1;
  1219. link_last_remainder(p);
  1220. }
  1221. else
  1222. unlink(next, bck, fwd);
  1223. }
  1224. set_head(p, sz | PREV_INUSE);
  1225. set_foot(p, sz);
  1226. if (!islr)
  1227. frontlink(p, sz, idx, bck, fwd);
  1228. }
  1229. /*
  1230. Realloc algorithm:
  1231. Chunks that were obtained via mmap cannot be extended or shrunk
  1232. unless HAVE_MREMAP is defined, in which case mremap is used.
  1233. Otherwise, if their reallocation is for additional space, they are
  1234. copied. If for less, they are just left alone.
  1235. Otherwise, if the reallocation is for additional space, and the
  1236. chunk can be extended, it is, else a malloc-copy-free sequence is
  1237. taken. There are several different ways that a chunk could be
  1238. extended. All are tried:
  1239. * Extending forward into following adjacent free chunk.
  1240. * Shifting backwards, joining preceding adjacent space
  1241. * Both shifting backwards and extending forward.
  1242. * Extending into newly sbrked space
  1243. Unless the #define REALLOC_ZERO_BYTES_FREES is set, realloc with a
  1244. size argument of zero (re)allocates a minimum-sized chunk.
  1245. If the reallocation is for less space, and the new request is for
  1246. a `small' (<512 bytes) size, then the newly unused space is lopped
  1247. off and freed.
  1248. The old unix realloc convention of allowing the last-free'd chunk
  1249. to be used as an argument to realloc is no longer supported.
  1250. I don't know of any programs still relying on this feature,
  1251. and allowing it would also allow too many other incorrect
  1252. usages of realloc to be sensible.
  1253. */
  1254. #if __STD_C
  1255. Void_t* rEALLOc(Void_t* oldmem, size_t bytes)
  1256. #else
  1257. Void_t* rEALLOc(oldmem, bytes) Void_t* oldmem; size_t bytes;
  1258. #endif
  1259. {
  1260. INTERNAL_SIZE_T nb; /* padded request size */
  1261. mchunkptr oldp; /* chunk corresponding to oldmem */
  1262. INTERNAL_SIZE_T oldsize; /* its size */
  1263. mchunkptr newp; /* chunk to return */
  1264. INTERNAL_SIZE_T newsize; /* its size */
  1265. Void_t* newmem; /* corresponding user mem */
  1266. mchunkptr next; /* next contiguous chunk after oldp */
  1267. INTERNAL_SIZE_T nextsize; /* its size */
  1268. mchunkptr prev; /* previous contiguous chunk before oldp */
  1269. INTERNAL_SIZE_T prevsize; /* its size */
  1270. mchunkptr remainder; /* holds split off extra space from newp */
  1271. INTERNAL_SIZE_T remainder_size; /* its size */
  1272. mchunkptr bck; /* misc temp for linking */
  1273. mchunkptr fwd; /* misc temp for linking */
  1274. #ifdef REALLOC_ZERO_BYTES_FREES
  1275. if (!bytes) {
  1276. fREe(oldmem);
  1277. return NULL;
  1278. }
  1279. #endif
  1280. if ((long)bytes < 0) return NULL;
  1281. /* realloc of null is supposed to be same as malloc */
  1282. if (oldmem == NULL) return mALLOc(bytes);
  1283. #if CONFIG_VAL(SYS_MALLOC_F_LEN)
  1284. if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT)) {
  1285. /* This is harder to support and should not be needed */
  1286. panic("pre-reloc realloc() is not supported");
  1287. }
  1288. #endif
  1289. newp = oldp = mem2chunk(oldmem);
  1290. newsize = oldsize = chunksize(oldp);
  1291. nb = request2size(bytes);
  1292. #if HAVE_MMAP
  1293. if (chunk_is_mmapped(oldp))
  1294. {
  1295. #if HAVE_MREMAP
  1296. newp = mremap_chunk(oldp, nb);
  1297. if(newp) return chunk2mem(newp);
  1298. #endif
  1299. /* Note the extra SIZE_SZ overhead. */
  1300. if(oldsize - SIZE_SZ >= nb) return oldmem; /* do nothing */
  1301. /* Must alloc, copy, free. */
  1302. newmem = mALLOc(bytes);
  1303. if (!newmem)
  1304. return NULL; /* propagate failure */
  1305. MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ);
  1306. munmap_chunk(oldp);
  1307. return newmem;
  1308. }
  1309. #endif
  1310. check_inuse_chunk(oldp);
  1311. if ((long)(oldsize) < (long)(nb))
  1312. {
  1313. /* Try expanding forward */
  1314. next = chunk_at_offset(oldp, oldsize);
  1315. if (next == top || !inuse(next))
  1316. {
  1317. nextsize = chunksize(next);
  1318. /* Forward into top only if a remainder */
  1319. if (next == top)
  1320. {
  1321. if ((long)(nextsize + newsize) >= (long)(nb + MINSIZE))
  1322. {
  1323. newsize += nextsize;
  1324. top = chunk_at_offset(oldp, nb);
  1325. set_head(top, (newsize - nb) | PREV_INUSE);
  1326. set_head_size(oldp, nb);
  1327. return chunk2mem(oldp);
  1328. }
  1329. }
  1330. /* Forward into next chunk */
  1331. else if (((long)(nextsize + newsize) >= (long)(nb)))
  1332. {
  1333. unlink(next, bck, fwd);
  1334. newsize += nextsize;
  1335. goto split;
  1336. }
  1337. }
  1338. else
  1339. {
  1340. next = NULL;
  1341. nextsize = 0;
  1342. }
  1343. /* Try shifting backwards. */
  1344. if (!prev_inuse(oldp))
  1345. {
  1346. prev = prev_chunk(oldp);
  1347. prevsize = chunksize(prev);
  1348. /* try forward + backward first to save a later consolidation */
  1349. if (next != NULL)
  1350. {
  1351. /* into top */
  1352. if (next == top)
  1353. {
  1354. if ((long)(nextsize + prevsize + newsize) >= (long)(nb + MINSIZE))
  1355. {
  1356. unlink(prev, bck, fwd);
  1357. newp = prev;
  1358. newsize += prevsize + nextsize;
  1359. newmem = chunk2mem(newp);
  1360. MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
  1361. top = chunk_at_offset(newp, nb);
  1362. set_head(top, (newsize - nb) | PREV_INUSE);
  1363. set_head_size(newp, nb);
  1364. return newmem;
  1365. }
  1366. }
  1367. /* into next chunk */
  1368. else if (((long)(nextsize + prevsize + newsize) >= (long)(nb)))
  1369. {
  1370. unlink(next, bck, fwd);
  1371. unlink(prev, bck, fwd);
  1372. newp = prev;
  1373. newsize += nextsize + prevsize;
  1374. newmem = chunk2mem(newp);
  1375. MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
  1376. goto split;
  1377. }
  1378. }
  1379. /* backward only */
  1380. if (prev != NULL && (long)(prevsize + newsize) >= (long)nb)
  1381. {
  1382. unlink(prev, bck, fwd);
  1383. newp = prev;
  1384. newsize += prevsize;
  1385. newmem = chunk2mem(newp);
  1386. MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
  1387. goto split;
  1388. }
  1389. }
  1390. /* Must allocate */
  1391. newmem = mALLOc (bytes);
  1392. if (newmem == NULL) /* propagate failure */
  1393. return NULL;
  1394. /* Avoid copy if newp is next chunk after oldp. */
  1395. /* (This can only happen when new chunk is sbrk'ed.) */
  1396. if ( (newp = mem2chunk(newmem)) == next_chunk(oldp))
  1397. {
  1398. newsize += chunksize(newp);
  1399. newp = oldp;
  1400. goto split;
  1401. }
  1402. /* Otherwise copy, free, and exit */
  1403. MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
  1404. fREe(oldmem);
  1405. return newmem;
  1406. }
  1407. split: /* split off extra room in old or expanded chunk */
  1408. if (newsize - nb >= MINSIZE) /* split off remainder */
  1409. {
  1410. remainder = chunk_at_offset(newp, nb);
  1411. remainder_size = newsize - nb;
  1412. set_head_size(newp, nb);
  1413. set_head(remainder, remainder_size | PREV_INUSE);
  1414. set_inuse_bit_at_offset(remainder, remainder_size);
  1415. fREe(chunk2mem(remainder)); /* let free() deal with it */
  1416. }
  1417. else
  1418. {
  1419. set_head_size(newp, newsize);
  1420. set_inuse_bit_at_offset(newp, newsize);
  1421. }
  1422. check_inuse_chunk(newp);
  1423. return chunk2mem(newp);
  1424. }
  1425. /*
  1426. memalign algorithm:
  1427. memalign requests more than enough space from malloc, finds a spot
  1428. within that chunk that meets the alignment request, and then
  1429. possibly frees the leading and trailing space.
  1430. The alignment argument must be a power of two. This property is not
  1431. checked by memalign, so misuse may result in random runtime errors.
  1432. 8-byte alignment is guaranteed by normal malloc calls, so don't
  1433. bother calling memalign with an argument of 8 or less.
  1434. Overreliance on memalign is a sure way to fragment space.
  1435. */
  1436. #if __STD_C
  1437. Void_t* mEMALIGn(size_t alignment, size_t bytes)
  1438. #else
  1439. Void_t* mEMALIGn(alignment, bytes) size_t alignment; size_t bytes;
  1440. #endif
  1441. {
  1442. INTERNAL_SIZE_T nb; /* padded request size */
  1443. char* m; /* memory returned by malloc call */
  1444. mchunkptr p; /* corresponding chunk */
  1445. char* brk; /* alignment point within p */
  1446. mchunkptr newp; /* chunk to return */
  1447. INTERNAL_SIZE_T newsize; /* its size */
  1448. INTERNAL_SIZE_T leadsize; /* leading space befor alignment point */
  1449. mchunkptr remainder; /* spare room at end to split off */
  1450. long remainder_size; /* its size */
  1451. if ((long)bytes < 0) return NULL;
  1452. #if CONFIG_VAL(SYS_MALLOC_F_LEN)
  1453. if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT)) {
  1454. return memalign_simple(alignment, bytes);
  1455. }
  1456. #endif
  1457. /* If need less alignment than we give anyway, just relay to malloc */
  1458. if (alignment <= MALLOC_ALIGNMENT) return mALLOc(bytes);
  1459. /* Otherwise, ensure that it is at least a minimum chunk size */
  1460. if (alignment < MINSIZE) alignment = MINSIZE;
  1461. /* Call malloc with worst case padding to hit alignment. */
  1462. nb = request2size(bytes);
  1463. m = (char*)(mALLOc(nb + alignment + MINSIZE));
  1464. /*
  1465. * The attempt to over-allocate (with a size large enough to guarantee the
  1466. * ability to find an aligned region within allocated memory) failed.
  1467. *
  1468. * Try again, this time only allocating exactly the size the user wants. If
  1469. * the allocation now succeeds and just happens to be aligned, we can still
  1470. * fulfill the user's request.
  1471. */
  1472. if (m == NULL) {
  1473. size_t extra, extra2;
  1474. /*
  1475. * Use bytes not nb, since mALLOc internally calls request2size too, and
  1476. * each call increases the size to allocate, to account for the header.
  1477. */
  1478. m = (char*)(mALLOc(bytes));
  1479. /* Aligned -> return it */
  1480. if ((((unsigned long)(m)) % alignment) == 0)
  1481. return m;
  1482. /*
  1483. * Otherwise, try again, requesting enough extra space to be able to
  1484. * acquire alignment.
  1485. */
  1486. fREe(m);
  1487. /* Add in extra bytes to match misalignment of unexpanded allocation */
  1488. extra = alignment - (((unsigned long)(m)) % alignment);
  1489. m = (char*)(mALLOc(bytes + extra));
  1490. /*
  1491. * m might not be the same as before. Validate that the previous value of
  1492. * extra still works for the current value of m.
  1493. * If (!m), extra2=alignment so
  1494. */
  1495. if (m) {
  1496. extra2 = alignment - (((unsigned long)(m)) % alignment);
  1497. if (extra2 > extra) {
  1498. fREe(m);
  1499. m = NULL;
  1500. }
  1501. }
  1502. /* Fall through to original NULL check and chunk splitting logic */
  1503. }
  1504. if (m == NULL) return NULL; /* propagate failure */
  1505. p = mem2chunk(m);
  1506. if ((((unsigned long)(m)) % alignment) == 0) /* aligned */
  1507. {
  1508. #if HAVE_MMAP
  1509. if(chunk_is_mmapped(p))
  1510. return chunk2mem(p); /* nothing more to do */
  1511. #endif
  1512. }
  1513. else /* misaligned */
  1514. {
  1515. /*
  1516. Find an aligned spot inside chunk.
  1517. Since we need to give back leading space in a chunk of at
  1518. least MINSIZE, if the first calculation places us at
  1519. a spot with less than MINSIZE leader, we can move to the
  1520. next aligned spot -- we've allocated enough total room so that
  1521. this is always possible.
  1522. */
  1523. brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) & -((signed) alignment));
  1524. if ((long)(brk - (char*)(p)) < MINSIZE) brk = brk + alignment;
  1525. newp = (mchunkptr)brk;
  1526. leadsize = brk - (char*)(p);
  1527. newsize = chunksize(p) - leadsize;
  1528. #if HAVE_MMAP
  1529. if(chunk_is_mmapped(p))
  1530. {
  1531. newp->prev_size = p->prev_size + leadsize;
  1532. set_head(newp, newsize|IS_MMAPPED);
  1533. return chunk2mem(newp);
  1534. }
  1535. #endif
  1536. /* give back leader, use the rest */
  1537. set_head(newp, newsize | PREV_INUSE);
  1538. set_inuse_bit_at_offset(newp, newsize);
  1539. set_head_size(p, leadsize);
  1540. fREe(chunk2mem(p));
  1541. p = newp;
  1542. assert (newsize >= nb && (((unsigned long)(chunk2mem(p))) % alignment) == 0);
  1543. }
  1544. /* Also give back spare room at the end */
  1545. remainder_size = chunksize(p) - nb;
  1546. if (remainder_size >= (long)MINSIZE)
  1547. {
  1548. remainder = chunk_at_offset(p, nb);
  1549. set_head(remainder, remainder_size | PREV_INUSE);
  1550. set_head_size(p, nb);
  1551. fREe(chunk2mem(remainder));
  1552. }
  1553. check_inuse_chunk(p);
  1554. return chunk2mem(p);
  1555. }
  1556. /*
  1557. valloc just invokes memalign with alignment argument equal
  1558. to the page size of the system (or as near to this as can
  1559. be figured out from all the includes/defines above.)
  1560. */
  1561. #if __STD_C
  1562. Void_t* vALLOc(size_t bytes)
  1563. #else
  1564. Void_t* vALLOc(bytes) size_t bytes;
  1565. #endif
  1566. {
  1567. return mEMALIGn (malloc_getpagesize, bytes);
  1568. }
  1569. /*
  1570. pvalloc just invokes valloc for the nearest pagesize
  1571. that will accommodate request
  1572. */
  1573. #if __STD_C
  1574. Void_t* pvALLOc(size_t bytes)
  1575. #else
  1576. Void_t* pvALLOc(bytes) size_t bytes;
  1577. #endif
  1578. {
  1579. size_t pagesize = malloc_getpagesize;
  1580. return mEMALIGn (pagesize, (bytes + pagesize - 1) & ~(pagesize - 1));
  1581. }
  1582. /*
  1583. calloc calls malloc, then zeroes out the allocated chunk.
  1584. */
  1585. #if __STD_C
  1586. Void_t* cALLOc(size_t n, size_t elem_size)
  1587. #else
  1588. Void_t* cALLOc(n, elem_size) size_t n; size_t elem_size;
  1589. #endif
  1590. {
  1591. mchunkptr p;
  1592. INTERNAL_SIZE_T csz;
  1593. INTERNAL_SIZE_T sz = n * elem_size;
  1594. /* check if expand_top called, in which case don't need to clear */
  1595. #ifdef CONFIG_SYS_MALLOC_CLEAR_ON_INIT
  1596. #if MORECORE_CLEARS
  1597. mchunkptr oldtop = top;
  1598. INTERNAL_SIZE_T oldtopsize = chunksize(top);
  1599. #endif
  1600. #endif
  1601. Void_t* mem = mALLOc (sz);
  1602. if ((long)n < 0) return NULL;
  1603. if (mem == NULL)
  1604. return NULL;
  1605. else
  1606. {
  1607. #if CONFIG_VAL(SYS_MALLOC_F_LEN)
  1608. if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT)) {
  1609. memset(mem, 0, sz);
  1610. return mem;
  1611. }
  1612. #endif
  1613. p = mem2chunk(mem);
  1614. /* Two optional cases in which clearing not necessary */
  1615. #if HAVE_MMAP
  1616. if (chunk_is_mmapped(p)) return mem;
  1617. #endif
  1618. csz = chunksize(p);
  1619. #ifdef CONFIG_SYS_MALLOC_CLEAR_ON_INIT
  1620. #if MORECORE_CLEARS
  1621. if (p == oldtop && csz > oldtopsize)
  1622. {
  1623. /* clear only the bytes from non-freshly-sbrked memory */
  1624. csz = oldtopsize;
  1625. }
  1626. #endif
  1627. #endif
  1628. MALLOC_ZERO(mem, csz - SIZE_SZ);
  1629. return mem;
  1630. }
  1631. }
  1632. /*
  1633. cfree just calls free. It is needed/defined on some systems
  1634. that pair it with calloc, presumably for odd historical reasons.
  1635. */
  1636. #if !defined(INTERNAL_LINUX_C_LIB) || !defined(__ELF__)
  1637. #if __STD_C
  1638. void cfree(Void_t *mem)
  1639. #else
  1640. void cfree(mem) Void_t *mem;
  1641. #endif
  1642. {
  1643. fREe(mem);
  1644. }
  1645. #endif
  1646. /*
  1647. Malloc_trim gives memory back to the system (via negative
  1648. arguments to sbrk) if there is unused memory at the `high' end of
  1649. the malloc pool. You can call this after freeing large blocks of
  1650. memory to potentially reduce the system-level memory requirements
  1651. of a program. However, it cannot guarantee to reduce memory. Under
  1652. some allocation patterns, some large free blocks of memory will be
  1653. locked between two used chunks, so they cannot be given back to
  1654. the system.
  1655. The `pad' argument to malloc_trim represents the amount of free
  1656. trailing space to leave untrimmed. If this argument is zero,
  1657. only the minimum amount of memory to maintain internal data
  1658. structures will be left (one page or less). Non-zero arguments
  1659. can be supplied to maintain enough trailing space to service
  1660. future expected allocations without having to re-obtain memory
  1661. from the system.
  1662. Malloc_trim returns 1 if it actually released any memory, else 0.
  1663. */
  1664. #if __STD_C
  1665. int malloc_trim(size_t pad)
  1666. #else
  1667. int malloc_trim(pad) size_t pad;
  1668. #endif
  1669. {
  1670. long top_size; /* Amount of top-most memory */
  1671. long extra; /* Amount to release */
  1672. char* current_brk; /* address returned by pre-check sbrk call */
  1673. char* new_brk; /* address returned by negative sbrk call */
  1674. unsigned long pagesz = malloc_getpagesize;
  1675. top_size = chunksize(top);
  1676. extra = ((top_size - pad - MINSIZE + (pagesz-1)) / pagesz - 1) * pagesz;
  1677. if (extra < (long)pagesz) /* Not enough memory to release */
  1678. return 0;
  1679. else
  1680. {
  1681. /* Test to make sure no one else called sbrk */
  1682. current_brk = (char*)(MORECORE (0));
  1683. if (current_brk != (char*)(top) + top_size)
  1684. return 0; /* Apparently we don't own memory; must fail */
  1685. else
  1686. {
  1687. new_brk = (char*)(MORECORE (-extra));
  1688. if (new_brk == (char*)(MORECORE_FAILURE)) /* sbrk failed? */
  1689. {
  1690. /* Try to figure out what we have */
  1691. current_brk = (char*)(MORECORE (0));
  1692. top_size = current_brk - (char*)top;
  1693. if (top_size >= (long)MINSIZE) /* if not, we are very very dead! */
  1694. {
  1695. sbrked_mem = current_brk - sbrk_base;
  1696. set_head(top, top_size | PREV_INUSE);
  1697. }
  1698. check_chunk(top);
  1699. return 0;
  1700. }
  1701. else
  1702. {
  1703. /* Success. Adjust top accordingly. */
  1704. set_head(top, (top_size - extra) | PREV_INUSE);
  1705. sbrked_mem -= extra;
  1706. check_chunk(top);
  1707. return 1;
  1708. }
  1709. }
  1710. }
  1711. }
  1712. /*
  1713. malloc_usable_size:
  1714. This routine tells you how many bytes you can actually use in an
  1715. allocated chunk, which may be more than you requested (although
  1716. often not). You can use this many bytes without worrying about
  1717. overwriting other allocated objects. Not a particularly great
  1718. programming practice, but still sometimes useful.
  1719. */
  1720. #if __STD_C
  1721. size_t malloc_usable_size(Void_t* mem)
  1722. #else
  1723. size_t malloc_usable_size(mem) Void_t* mem;
  1724. #endif
  1725. {
  1726. mchunkptr p;
  1727. if (mem == NULL)
  1728. return 0;
  1729. else
  1730. {
  1731. p = mem2chunk(mem);
  1732. if(!chunk_is_mmapped(p))
  1733. {
  1734. if (!inuse(p)) return 0;
  1735. check_inuse_chunk(p);
  1736. return chunksize(p) - SIZE_SZ;
  1737. }
  1738. return chunksize(p) - 2*SIZE_SZ;
  1739. }
  1740. }
  1741. /* Utility to update current_mallinfo for malloc_stats and mallinfo() */
  1742. #ifdef DEBUG
  1743. static void malloc_update_mallinfo()
  1744. {
  1745. int i;
  1746. mbinptr b;
  1747. mchunkptr p;
  1748. #ifdef DEBUG
  1749. mchunkptr q;
  1750. #endif
  1751. INTERNAL_SIZE_T avail = chunksize(top);
  1752. int navail = ((long)(avail) >= (long)MINSIZE)? 1 : 0;
  1753. for (i = 1; i < NAV; ++i)
  1754. {
  1755. b = bin_at(i);
  1756. for (p = last(b); p != b; p = p->bk)
  1757. {
  1758. #ifdef DEBUG
  1759. check_free_chunk(p);
  1760. for (q = next_chunk(p);
  1761. q < top && inuse(q) && (long)(chunksize(q)) >= (long)MINSIZE;
  1762. q = next_chunk(q))
  1763. check_inuse_chunk(q);
  1764. #endif
  1765. avail += chunksize(p);
  1766. navail++;
  1767. }
  1768. }
  1769. current_mallinfo.ordblks = navail;
  1770. current_mallinfo.uordblks = sbrked_mem - avail;
  1771. current_mallinfo.fordblks = avail;
  1772. current_mallinfo.hblks = n_mmaps;
  1773. current_mallinfo.hblkhd = mmapped_mem;
  1774. current_mallinfo.keepcost = chunksize(top);
  1775. }
  1776. #endif /* DEBUG */
  1777. /*
  1778. malloc_stats:
  1779. Prints on the amount of space obtain from the system (both
  1780. via sbrk and mmap), the maximum amount (which may be more than
  1781. current if malloc_trim and/or munmap got called), the maximum
  1782. number of simultaneous mmap regions used, and the current number
  1783. of bytes allocated via malloc (or realloc, etc) but not yet
  1784. freed. (Note that this is the number of bytes allocated, not the
  1785. number requested. It will be larger than the number requested
  1786. because of alignment and bookkeeping overhead.)
  1787. */
  1788. #ifdef DEBUG
  1789. void malloc_stats()
  1790. {
  1791. malloc_update_mallinfo();
  1792. printf("max system bytes = %10u\n",
  1793. (unsigned int)(max_total_mem));
  1794. printf("system bytes = %10u\n",
  1795. (unsigned int)(sbrked_mem + mmapped_mem));
  1796. printf("in use bytes = %10u\n",
  1797. (unsigned int)(current_mallinfo.uordblks + mmapped_mem));
  1798. #if HAVE_MMAP
  1799. printf("max mmap regions = %10u\n",
  1800. (unsigned int)max_n_mmaps);
  1801. #endif
  1802. }
  1803. #endif /* DEBUG */
  1804. /*
  1805. mallinfo returns a copy of updated current mallinfo.
  1806. */
  1807. #ifdef DEBUG
  1808. struct mallinfo mALLINFo()
  1809. {
  1810. malloc_update_mallinfo();
  1811. return current_mallinfo;
  1812. }
  1813. #endif /* DEBUG */
  1814. /*
  1815. mallopt:
  1816. mallopt is the general SVID/XPG interface to tunable parameters.
  1817. The format is to provide a (parameter-number, parameter-value) pair.
  1818. mallopt then sets the corresponding parameter to the argument
  1819. value if it can (i.e., so long as the value is meaningful),
  1820. and returns 1 if successful else 0.
  1821. See descriptions of tunable parameters above.
  1822. */
  1823. #if __STD_C
  1824. int mALLOPt(int param_number, int value)
  1825. #else
  1826. int mALLOPt(param_number, value) int param_number; int value;
  1827. #endif
  1828. {
  1829. switch(param_number)
  1830. {
  1831. case M_TRIM_THRESHOLD:
  1832. trim_threshold = value; return 1;
  1833. case M_TOP_PAD:
  1834. top_pad = value; return 1;
  1835. case M_MMAP_THRESHOLD:
  1836. mmap_threshold = value; return 1;
  1837. case M_MMAP_MAX:
  1838. #if HAVE_MMAP
  1839. n_mmaps_max = value; return 1;
  1840. #else
  1841. if (value != 0) return 0; else n_mmaps_max = value; return 1;
  1842. #endif
  1843. default:
  1844. return 0;
  1845. }
  1846. }
  1847. int initf_malloc(void)
  1848. {
  1849. #if CONFIG_VAL(SYS_MALLOC_F_LEN)
  1850. assert(gd->malloc_base); /* Set up by crt0.S */
  1851. gd->malloc_limit = CONFIG_VAL(SYS_MALLOC_F_LEN);
  1852. gd->malloc_ptr = 0;
  1853. #endif
  1854. return 0;
  1855. }
  1856. /*
  1857. History:
  1858. V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee)
  1859. * return null for negative arguments
  1860. * Added Several WIN32 cleanups from Martin C. Fong <mcfong@yahoo.com>
  1861. * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
  1862. (e.g. WIN32 platforms)
  1863. * Cleanup up header file inclusion for WIN32 platforms
  1864. * Cleanup code to avoid Microsoft Visual C++ compiler complaints
  1865. * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
  1866. memory allocation routines
  1867. * Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
  1868. * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
  1869. usage of 'assert' in non-WIN32 code
  1870. * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
  1871. avoid infinite loop
  1872. * Always call 'fREe()' rather than 'free()'
  1873. V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee)
  1874. * Fixed ordering problem with boundary-stamping
  1875. V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
  1876. * Added pvalloc, as recommended by H.J. Liu
  1877. * Added 64bit pointer support mainly from Wolfram Gloger
  1878. * Added anonymously donated WIN32 sbrk emulation
  1879. * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
  1880. * malloc_extend_top: fix mask error that caused wastage after
  1881. foreign sbrks
  1882. * Add linux mremap support code from HJ Liu
  1883. V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
  1884. * Integrated most documentation with the code.
  1885. * Add support for mmap, with help from
  1886. Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
  1887. * Use last_remainder in more cases.
  1888. * Pack bins using idea from colin@nyx10.cs.du.edu
  1889. * Use ordered bins instead of best-fit threshhold
  1890. * Eliminate block-local decls to simplify tracing and debugging.
  1891. * Support another case of realloc via move into top
  1892. * Fix error occuring when initial sbrk_base not word-aligned.
  1893. * Rely on page size for units instead of SBRK_UNIT to
  1894. avoid surprises about sbrk alignment conventions.
  1895. * Add mallinfo, mallopt. Thanks to Raymond Nijssen
  1896. (raymond@es.ele.tue.nl) for the suggestion.
  1897. * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
  1898. * More precautions for cases where other routines call sbrk,
  1899. courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
  1900. * Added macros etc., allowing use in linux libc from
  1901. H.J. Lu (hjl@gnu.ai.mit.edu)
  1902. * Inverted this history list
  1903. V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
  1904. * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
  1905. * Removed all preallocation code since under current scheme
  1906. the work required to undo bad preallocations exceeds
  1907. the work saved in good cases for most test programs.
  1908. * No longer use return list or unconsolidated bins since
  1909. no scheme using them consistently outperforms those that don't
  1910. given above changes.
  1911. * Use best fit for very large chunks to prevent some worst-cases.
  1912. * Added some support for debugging
  1913. V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
  1914. * Removed footers when chunks are in use. Thanks to
  1915. Paul Wilson (wilson@cs.texas.edu) for the suggestion.
  1916. V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
  1917. * Added malloc_trim, with help from Wolfram Gloger
  1918. (wmglo@Dent.MED.Uni-Muenchen.DE).
  1919. V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
  1920. V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
  1921. * realloc: try to expand in both directions
  1922. * malloc: swap order of clean-bin strategy;
  1923. * realloc: only conditionally expand backwards
  1924. * Try not to scavenge used bins
  1925. * Use bin counts as a guide to preallocation
  1926. * Occasionally bin return list chunks in first scan
  1927. * Add a few optimizations from colin@nyx10.cs.du.edu
  1928. V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
  1929. * faster bin computation & slightly different binning
  1930. * merged all consolidations to one part of malloc proper
  1931. (eliminating old malloc_find_space & malloc_clean_bin)
  1932. * Scan 2 returns chunks (not just 1)
  1933. * Propagate failure in realloc if malloc returns 0
  1934. * Add stuff to allow compilation on non-ANSI compilers
  1935. from kpv@research.att.com
  1936. V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
  1937. * removed potential for odd address access in prev_chunk
  1938. * removed dependency on getpagesize.h
  1939. * misc cosmetics and a bit more internal documentation
  1940. * anticosmetics: mangled names in macros to evade debugger strangeness
  1941. * tested on sparc, hp-700, dec-mips, rs6000
  1942. with gcc & native cc (hp, dec only) allowing
  1943. Detlefs & Zorn comparison study (in SIGPLAN Notices.)
  1944. Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
  1945. * Based loosely on libg++-1.2X malloc. (It retains some of the overall
  1946. structure of old version, but most details differ.)
  1947. */