dlmalloc.c 72 KB

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