dlmalloc.c 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332
  1. #include <common.h>
  2. #if 0 /* Moved to malloc.h */
  3. /* ---------- To make a malloc.h, start cutting here ------------ */
  4. /*
  5. A version of malloc/free/realloc written by Doug Lea and released to the
  6. public domain. Send questions/comments/complaints/performance data
  7. to dl@cs.oswego.edu
  8. * VERSION 2.6.6 Sun Mar 5 19:10:03 2000 Doug Lea (dl at gee)
  9. Note: There may be an updated version of this malloc obtainable at
  10. ftp://g.oswego.edu/pub/misc/malloc.c
  11. Check before installing!
  12. * Why use this malloc?
  13. This is not the fastest, most space-conserving, most portable, or
  14. most tunable malloc ever written. However it is among the fastest
  15. while also being among the most space-conserving, portable and tunable.
  16. Consistent balance across these factors results in a good general-purpose
  17. allocator. For a high-level description, see
  18. http://g.oswego.edu/dl/html/malloc.html
  19. * Synopsis of public routines
  20. (Much fuller descriptions are contained in the program documentation below.)
  21. malloc(size_t n);
  22. Return a pointer to a newly allocated chunk of at least n bytes, or null
  23. if no space is available.
  24. free(Void_t* p);
  25. Release the chunk of memory pointed to by p, or no effect if p is null.
  26. realloc(Void_t* p, size_t n);
  27. Return a pointer to a chunk of size n that contains the same data
  28. as does chunk p up to the minimum of (n, p's size) bytes, or null
  29. if no space is available. The returned pointer may or may not be
  30. the same as p. If p is null, equivalent to malloc. Unless the
  31. #define REALLOC_ZERO_BYTES_FREES below is set, realloc with a
  32. size argument of zero (re)allocates a minimum-sized chunk.
  33. memalign(size_t alignment, size_t n);
  34. Return a pointer to a newly allocated chunk of n bytes, aligned
  35. in accord with the alignment argument, which must be a power of
  36. two.
  37. valloc(size_t n);
  38. Equivalent to memalign(pagesize, n), where pagesize is the page
  39. size of the system (or as near to this as can be figured out from
  40. all the includes/defines below.)
  41. pvalloc(size_t n);
  42. Equivalent to valloc(minimum-page-that-holds(n)), that is,
  43. round up n to nearest pagesize.
  44. calloc(size_t unit, size_t quantity);
  45. Returns a pointer to quantity * unit bytes, with all locations
  46. set to zero.
  47. cfree(Void_t* p);
  48. Equivalent to free(p).
  49. malloc_trim(size_t pad);
  50. Release all but pad bytes of freed top-most memory back
  51. to the system. Return 1 if successful, else 0.
  52. malloc_usable_size(Void_t* p);
  53. Report the number usable allocated bytes associated with allocated
  54. chunk p. This may or may not report more bytes than were requested,
  55. due to alignment and minimum size constraints.
  56. malloc_stats();
  57. Prints brief summary statistics.
  58. mallinfo()
  59. Returns (by copy) a struct containing various summary statistics.
  60. mallopt(int parameter_number, int parameter_value)
  61. Changes one of the tunable parameters described below. Returns
  62. 1 if successful in changing the parameter, else 0.
  63. * Vital statistics:
  64. Alignment: 8-byte
  65. 8 byte alignment is currently hardwired into the design. This
  66. seems to suffice for all current machines and C compilers.
  67. Assumed pointer representation: 4 or 8 bytes
  68. Code for 8-byte pointers is untested by me but has worked
  69. reliably by Wolfram Gloger, who contributed most of the
  70. changes supporting this.
  71. Assumed size_t representation: 4 or 8 bytes
  72. Note that size_t is allowed to be 4 bytes even if pointers are 8.
  73. Minimum overhead per allocated chunk: 4 or 8 bytes
  74. Each malloced chunk has a hidden overhead of 4 bytes holding size
  75. and status information.
  76. Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
  77. 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
  78. When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
  79. ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
  80. needed; 4 (8) for a trailing size field
  81. and 8 (16) bytes for free list pointers. Thus, the minimum
  82. allocatable size is 16/24/32 bytes.
  83. Even a request for zero bytes (i.e., malloc(0)) returns a
  84. pointer to something of the minimum allocatable size.
  85. Maximum allocated size: 4-byte size_t: 2^31 - 8 bytes
  86. 8-byte size_t: 2^63 - 16 bytes
  87. It is assumed that (possibly signed) size_t bit values suffice to
  88. represent chunk sizes. `Possibly signed' is due to the fact
  89. that `size_t' may be defined on a system as either a signed or
  90. an unsigned type. To be conservative, values that would appear
  91. as negative numbers are avoided.
  92. Requests for sizes with a negative sign bit when the request
  93. size is treaded as a long will return null.
  94. Maximum overhead wastage per allocated chunk: normally 15 bytes
  95. Alignnment demands, plus the minimum allocatable size restriction
  96. make the normal worst-case wastage 15 bytes (i.e., up to 15
  97. more bytes will be allocated than were requested in malloc), with
  98. two exceptions:
  99. 1. Because requests for zero bytes allocate non-zero space,
  100. the worst case wastage for a request of zero bytes is 24 bytes.
  101. 2. For requests >= mmap_threshold that are serviced via
  102. mmap(), the worst case wastage is 8 bytes plus the remainder
  103. from a system page (the minimal mmap unit); typically 4096 bytes.
  104. * Limitations
  105. Here are some features that are NOT currently supported
  106. * No user-definable hooks for callbacks and the like.
  107. * No automated mechanism for fully checking that all accesses
  108. to malloced memory stay within their bounds.
  109. * No support for compaction.
  110. * Synopsis of compile-time options:
  111. People have reported using previous versions of this malloc on all
  112. versions of Unix, sometimes by tweaking some of the defines
  113. below. It has been tested most extensively on Solaris and
  114. Linux. It is also reported to work on WIN32 platforms.
  115. People have also reported adapting this malloc for use in
  116. stand-alone embedded systems.
  117. The implementation is in straight, hand-tuned ANSI C. Among other
  118. consequences, it uses a lot of macros. Because of this, to be at
  119. all usable, this code should be compiled using an optimizing compiler
  120. (for example gcc -O2) that can simplify expressions and control
  121. paths.
  122. __STD_C (default: derived from C compiler defines)
  123. Nonzero if using ANSI-standard C compiler, a C++ compiler, or
  124. a C compiler sufficiently close to ANSI to get away with it.
  125. DEBUG (default: NOT defined)
  126. Define to enable debugging. Adds fairly extensive assertion-based
  127. checking to help track down memory errors, but noticeably slows down
  128. execution.
  129. REALLOC_ZERO_BYTES_FREES (default: NOT defined)
  130. Define this if you think that realloc(p, 0) should be equivalent
  131. to free(p). Otherwise, since malloc returns a unique pointer for
  132. malloc(0), so does realloc(p, 0).
  133. HAVE_MEMCPY (default: defined)
  134. Define if you are not otherwise using ANSI STD C, but still
  135. have memcpy and memset in your C library and want to use them.
  136. Otherwise, simple internal versions are supplied.
  137. USE_MEMCPY (default: 1 if HAVE_MEMCPY is defined, 0 otherwise)
  138. Define as 1 if you want the C library versions of memset and
  139. memcpy called in realloc and calloc (otherwise macro versions are used).
  140. At least on some platforms, the simple macro versions usually
  141. outperform libc versions.
  142. HAVE_MMAP (default: defined as 1)
  143. Define to non-zero to optionally make malloc() use mmap() to
  144. allocate very large blocks.
  145. HAVE_MREMAP (default: defined as 0 unless Linux libc set)
  146. Define to non-zero to optionally make realloc() use mremap() to
  147. reallocate very large blocks.
  148. malloc_getpagesize (default: derived from system #includes)
  149. Either a constant or routine call returning the system page size.
  150. HAVE_USR_INCLUDE_MALLOC_H (default: NOT defined)
  151. Optionally define if you are on a system with a /usr/include/malloc.h
  152. that declares struct mallinfo. It is not at all necessary to
  153. define this even if you do, but will ensure consistency.
  154. INTERNAL_SIZE_T (default: size_t)
  155. Define to a 32-bit type (probably `unsigned int') if you are on a
  156. 64-bit machine, yet do not want or need to allow malloc requests of
  157. greater than 2^31 to be handled. This saves space, especially for
  158. very small chunks.
  159. INTERNAL_LINUX_C_LIB (default: NOT defined)
  160. Defined only when compiled as part of Linux libc.
  161. Also note that there is some odd internal name-mangling via defines
  162. (for example, internally, `malloc' is named `mALLOc') needed
  163. when compiling in this case. These look funny but don't otherwise
  164. affect anything.
  165. WIN32 (default: undefined)
  166. Define this on MS win (95, nt) platforms to compile in sbrk emulation.
  167. LACKS_UNISTD_H (default: undefined if not WIN32)
  168. Define this if your system does not have a <unistd.h>.
  169. LACKS_SYS_PARAM_H (default: undefined if not WIN32)
  170. Define this if your system does not have a <sys/param.h>.
  171. MORECORE (default: sbrk)
  172. The name of the routine to call to obtain more memory from the system.
  173. MORECORE_FAILURE (default: -1)
  174. The value returned upon failure of MORECORE.
  175. MORECORE_CLEARS (default 1)
  176. true (1) if the routine mapped to MORECORE zeroes out memory (which
  177. holds for sbrk).
  178. DEFAULT_TRIM_THRESHOLD
  179. DEFAULT_TOP_PAD
  180. DEFAULT_MMAP_THRESHOLD
  181. DEFAULT_MMAP_MAX
  182. Default values of tunable parameters (described in detail below)
  183. controlling interaction with host system routines (sbrk, mmap, etc).
  184. These values may also be changed dynamically via mallopt(). The
  185. preset defaults are those that give best performance for typical
  186. programs/systems.
  187. USE_DL_PREFIX (default: undefined)
  188. Prefix all public routines with the string 'dl'. Useful to
  189. quickly avoid procedure declaration conflicts and linker symbol
  190. conflicts with existing memory allocation routines.
  191. */
  192. /* Preliminaries */
  193. #ifndef __STD_C
  194. #ifdef __STDC__
  195. #define __STD_C 1
  196. #else
  197. #if __cplusplus
  198. #define __STD_C 1
  199. #else
  200. #define __STD_C 0
  201. #endif /*__cplusplus*/
  202. #endif /*__STDC__*/
  203. #endif /*__STD_C*/
  204. #ifndef Void_t
  205. #if (__STD_C || defined(WIN32))
  206. #define Void_t void
  207. #else
  208. #define Void_t char
  209. #endif
  210. #endif /*Void_t*/
  211. #if __STD_C
  212. #include <stddef.h> /* for size_t */
  213. #else
  214. #include <sys/types.h>
  215. #endif
  216. #ifdef __cplusplus
  217. extern "C" {
  218. #endif
  219. #include <stdio.h> /* needed for malloc_stats */
  220. /*
  221. Compile-time options
  222. */
  223. /*
  224. Debugging:
  225. Because freed chunks may be overwritten with link fields, this
  226. malloc will often die when freed memory is overwritten by user
  227. programs. This can be very effective (albeit in an annoying way)
  228. in helping track down dangling pointers.
  229. If you compile with -DDEBUG, a number of assertion checks are
  230. enabled that will catch more memory errors. You probably won't be
  231. able to make much sense of the actual assertion errors, but they
  232. should help you locate incorrectly overwritten memory. The
  233. checking is fairly extensive, and will slow down execution
  234. noticeably. Calling malloc_stats or mallinfo with DEBUG set will
  235. attempt to check every non-mmapped allocated and free chunk in the
  236. course of computing the summmaries. (By nature, mmapped regions
  237. cannot be checked very much automatically.)
  238. Setting DEBUG may also be helpful if you are trying to modify
  239. this code. The assertions in the check routines spell out in more
  240. detail the assumptions and invariants underlying the algorithms.
  241. */
  242. /*
  243. INTERNAL_SIZE_T is the word-size used for internal bookkeeping
  244. of chunk sizes. On a 64-bit machine, you can reduce malloc
  245. overhead by defining INTERNAL_SIZE_T to be a 32 bit `unsigned int'
  246. at the expense of not being able to handle requests greater than
  247. 2^31. This limitation is hardly ever a concern; you are encouraged
  248. to set this. However, the default version is the same as size_t.
  249. */
  250. #ifndef INTERNAL_SIZE_T
  251. #define INTERNAL_SIZE_T size_t
  252. #endif
  253. /*
  254. REALLOC_ZERO_BYTES_FREES should be set if a call to
  255. realloc with zero bytes should be the same as a call to free.
  256. Some people think it should. Otherwise, since this malloc
  257. returns a unique pointer for malloc(0), so does realloc(p, 0).
  258. */
  259. /* #define REALLOC_ZERO_BYTES_FREES */
  260. /*
  261. WIN32 causes an emulation of sbrk to be compiled in
  262. mmap-based options are not currently supported in WIN32.
  263. */
  264. /* #define WIN32 */
  265. #ifdef WIN32
  266. #define MORECORE wsbrk
  267. #define HAVE_MMAP 0
  268. #define LACKS_UNISTD_H
  269. #define LACKS_SYS_PARAM_H
  270. /*
  271. Include 'windows.h' to get the necessary declarations for the
  272. Microsoft Visual C++ data structures and routines used in the 'sbrk'
  273. emulation.
  274. Define WIN32_LEAN_AND_MEAN so that only the essential Microsoft
  275. Visual C++ header files are included.
  276. */
  277. #define WIN32_LEAN_AND_MEAN
  278. #include <windows.h>
  279. #endif
  280. /*
  281. HAVE_MEMCPY should be defined if you are not otherwise using
  282. ANSI STD C, but still have memcpy and memset in your C library
  283. and want to use them in calloc and realloc. Otherwise simple
  284. macro versions are defined here.
  285. USE_MEMCPY should be defined as 1 if you actually want to
  286. have memset and memcpy called. People report that the macro
  287. versions are often enough faster than libc versions on many
  288. systems that it is better to use them.
  289. */
  290. #define HAVE_MEMCPY
  291. #ifndef USE_MEMCPY
  292. #ifdef HAVE_MEMCPY
  293. #define USE_MEMCPY 1
  294. #else
  295. #define USE_MEMCPY 0
  296. #endif
  297. #endif
  298. #if (__STD_C || defined(HAVE_MEMCPY))
  299. #if __STD_C
  300. void* memset(void*, int, size_t);
  301. void* memcpy(void*, const void*, size_t);
  302. #else
  303. #ifdef WIN32
  304. /* On Win32 platforms, 'memset()' and 'memcpy()' are already declared in */
  305. /* 'windows.h' */
  306. #else
  307. Void_t* memset();
  308. Void_t* memcpy();
  309. #endif
  310. #endif
  311. #endif
  312. #if USE_MEMCPY
  313. /* The following macros are only invoked with (2n+1)-multiples of
  314. INTERNAL_SIZE_T units, with a positive integer n. This is exploited
  315. for fast inline execution when n is small. */
  316. #define MALLOC_ZERO(charp, nbytes) \
  317. do { \
  318. INTERNAL_SIZE_T mzsz = (nbytes); \
  319. if(mzsz <= 9*sizeof(mzsz)) { \
  320. INTERNAL_SIZE_T* mz = (INTERNAL_SIZE_T*) (charp); \
  321. if(mzsz >= 5*sizeof(mzsz)) { *mz++ = 0; \
  322. *mz++ = 0; \
  323. if(mzsz >= 7*sizeof(mzsz)) { *mz++ = 0; \
  324. *mz++ = 0; \
  325. if(mzsz >= 9*sizeof(mzsz)) { *mz++ = 0; \
  326. *mz++ = 0; }}} \
  327. *mz++ = 0; \
  328. *mz++ = 0; \
  329. *mz = 0; \
  330. } else memset((charp), 0, mzsz); \
  331. } while(0)
  332. #define MALLOC_COPY(dest,src,nbytes) \
  333. do { \
  334. INTERNAL_SIZE_T mcsz = (nbytes); \
  335. if(mcsz <= 9*sizeof(mcsz)) { \
  336. INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) (src); \
  337. INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) (dest); \
  338. if(mcsz >= 5*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
  339. *mcdst++ = *mcsrc++; \
  340. if(mcsz >= 7*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
  341. *mcdst++ = *mcsrc++; \
  342. if(mcsz >= 9*sizeof(mcsz)) { *mcdst++ = *mcsrc++; \
  343. *mcdst++ = *mcsrc++; }}} \
  344. *mcdst++ = *mcsrc++; \
  345. *mcdst++ = *mcsrc++; \
  346. *mcdst = *mcsrc ; \
  347. } else memcpy(dest, src, mcsz); \
  348. } while(0)
  349. #else /* !USE_MEMCPY */
  350. /* Use Duff's device for good zeroing/copying performance. */
  351. #define MALLOC_ZERO(charp, nbytes) \
  352. do { \
  353. INTERNAL_SIZE_T* mzp = (INTERNAL_SIZE_T*)(charp); \
  354. long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T), mcn; \
  355. if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
  356. switch (mctmp) { \
  357. case 0: for(;;) { *mzp++ = 0; \
  358. case 7: *mzp++ = 0; \
  359. case 6: *mzp++ = 0; \
  360. case 5: *mzp++ = 0; \
  361. case 4: *mzp++ = 0; \
  362. case 3: *mzp++ = 0; \
  363. case 2: *mzp++ = 0; \
  364. case 1: *mzp++ = 0; if(mcn <= 0) break; mcn--; } \
  365. } \
  366. } while(0)
  367. #define MALLOC_COPY(dest,src,nbytes) \
  368. do { \
  369. INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) src; \
  370. INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) dest; \
  371. long mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T), mcn; \
  372. if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \
  373. switch (mctmp) { \
  374. case 0: for(;;) { *mcdst++ = *mcsrc++; \
  375. case 7: *mcdst++ = *mcsrc++; \
  376. case 6: *mcdst++ = *mcsrc++; \
  377. case 5: *mcdst++ = *mcsrc++; \
  378. case 4: *mcdst++ = *mcsrc++; \
  379. case 3: *mcdst++ = *mcsrc++; \
  380. case 2: *mcdst++ = *mcsrc++; \
  381. case 1: *mcdst++ = *mcsrc++; if(mcn <= 0) break; mcn--; } \
  382. } \
  383. } while(0)
  384. #endif
  385. /*
  386. Define HAVE_MMAP to optionally make malloc() use mmap() to
  387. allocate very large blocks. These will be returned to the
  388. operating system immediately after a free().
  389. */
  390. #ifndef HAVE_MMAP
  391. #define HAVE_MMAP 1
  392. #endif
  393. /*
  394. Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
  395. large blocks. This is currently only possible on Linux with
  396. kernel versions newer than 1.3.77.
  397. */
  398. #ifndef HAVE_MREMAP
  399. #ifdef INTERNAL_LINUX_C_LIB
  400. #define HAVE_MREMAP 1
  401. #else
  402. #define HAVE_MREMAP 0
  403. #endif
  404. #endif
  405. #if HAVE_MMAP
  406. #include <unistd.h>
  407. #include <fcntl.h>
  408. #include <sys/mman.h>
  409. #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
  410. #define MAP_ANONYMOUS MAP_ANON
  411. #endif
  412. #endif /* HAVE_MMAP */
  413. /*
  414. Access to system page size. To the extent possible, this malloc
  415. manages memory from the system in page-size units.
  416. The following mechanics for getpagesize were adapted from
  417. bsd/gnu getpagesize.h
  418. */
  419. #ifndef LACKS_UNISTD_H
  420. # include <unistd.h>
  421. #endif
  422. #ifndef malloc_getpagesize
  423. # ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
  424. # ifndef _SC_PAGE_SIZE
  425. # define _SC_PAGE_SIZE _SC_PAGESIZE
  426. # endif
  427. # endif
  428. # ifdef _SC_PAGE_SIZE
  429. # define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
  430. # else
  431. # if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
  432. extern size_t getpagesize();
  433. # define malloc_getpagesize getpagesize()
  434. # else
  435. # ifdef WIN32
  436. # define malloc_getpagesize (4096) /* TBD: Use 'GetSystemInfo' instead */
  437. # else
  438. # ifndef LACKS_SYS_PARAM_H
  439. # include <sys/param.h>
  440. # endif
  441. # ifdef EXEC_PAGESIZE
  442. # define malloc_getpagesize EXEC_PAGESIZE
  443. # else
  444. # ifdef NBPG
  445. # ifndef CLSIZE
  446. # define malloc_getpagesize NBPG
  447. # else
  448. # define malloc_getpagesize (NBPG * CLSIZE)
  449. # endif
  450. # else
  451. # ifdef NBPC
  452. # define malloc_getpagesize NBPC
  453. # else
  454. # ifdef PAGESIZE
  455. # define malloc_getpagesize PAGESIZE
  456. # else
  457. # define malloc_getpagesize (4096) /* just guess */
  458. # endif
  459. # endif
  460. # endif
  461. # endif
  462. # endif
  463. # endif
  464. # endif
  465. #endif
  466. /*
  467. This version of malloc supports the standard SVID/XPG mallinfo
  468. routine that returns a struct containing the same kind of
  469. information you can get from malloc_stats. It should work on
  470. any SVID/XPG compliant system that has a /usr/include/malloc.h
  471. defining struct mallinfo. (If you'd like to install such a thing
  472. yourself, cut out the preliminary declarations as described above
  473. and below and save them in a malloc.h file. But there's no
  474. compelling reason to bother to do this.)
  475. The main declaration needed is the mallinfo struct that is returned
  476. (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
  477. bunch of fields, most of which are not even meaningful in this
  478. version of malloc. Some of these fields are are instead filled by
  479. mallinfo() with other numbers that might possibly be of interest.
  480. HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
  481. /usr/include/malloc.h file that includes a declaration of struct
  482. mallinfo. If so, it is included; else an SVID2/XPG2 compliant
  483. version is declared below. These must be precisely the same for
  484. mallinfo() to work.
  485. */
  486. /* #define HAVE_USR_INCLUDE_MALLOC_H */
  487. #if HAVE_USR_INCLUDE_MALLOC_H
  488. #include "/usr/include/malloc.h"
  489. #else
  490. /* SVID2/XPG mallinfo structure */
  491. struct mallinfo {
  492. int arena; /* total space allocated from system */
  493. int ordblks; /* number of non-inuse chunks */
  494. int smblks; /* unused -- always zero */
  495. int hblks; /* number of mmapped regions */
  496. int hblkhd; /* total space in mmapped regions */
  497. int usmblks; /* unused -- always zero */
  498. int fsmblks; /* unused -- always zero */
  499. int uordblks; /* total allocated space */
  500. int fordblks; /* total non-inuse space */
  501. int keepcost; /* top-most, releasable (via malloc_trim) space */
  502. };
  503. /* SVID2/XPG mallopt options */
  504. #define M_MXFAST 1 /* UNUSED in this malloc */
  505. #define M_NLBLKS 2 /* UNUSED in this malloc */
  506. #define M_GRAIN 3 /* UNUSED in this malloc */
  507. #define M_KEEP 4 /* UNUSED in this malloc */
  508. #endif
  509. /* mallopt options that actually do something */
  510. #define M_TRIM_THRESHOLD -1
  511. #define M_TOP_PAD -2
  512. #define M_MMAP_THRESHOLD -3
  513. #define M_MMAP_MAX -4
  514. #ifndef DEFAULT_TRIM_THRESHOLD
  515. #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
  516. #endif
  517. /*
  518. M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
  519. to keep before releasing via malloc_trim in free().
  520. Automatic trimming is mainly useful in long-lived programs.
  521. Because trimming via sbrk can be slow on some systems, and can
  522. sometimes be wasteful (in cases where programs immediately
  523. afterward allocate more large chunks) the value should be high
  524. enough so that your overall system performance would improve by
  525. releasing.
  526. The trim threshold and the mmap control parameters (see below)
  527. can be traded off with one another. Trimming and mmapping are
  528. two different ways of releasing unused memory back to the
  529. system. Between these two, it is often possible to keep
  530. system-level demands of a long-lived program down to a bare
  531. minimum. For example, in one test suite of sessions measuring
  532. the XF86 X server on Linux, using a trim threshold of 128K and a
  533. mmap threshold of 192K led to near-minimal long term resource
  534. consumption.
  535. If you are using this malloc in a long-lived program, it should
  536. pay to experiment with these values. As a rough guide, you
  537. might set to a value close to the average size of a process
  538. (program) running on your system. Releasing this much memory
  539. would allow such a process to run in memory. Generally, it's
  540. worth it to tune for trimming rather tham memory mapping when a
  541. program undergoes phases where several large chunks are
  542. allocated and released in ways that can reuse each other's
  543. storage, perhaps mixed with phases where there are no such
  544. chunks at all. And in well-behaved long-lived programs,
  545. controlling release of large blocks via trimming versus mapping
  546. is usually faster.
  547. However, in most programs, these parameters serve mainly as
  548. protection against the system-level effects of carrying around
  549. massive amounts of unneeded memory. Since frequent calls to
  550. sbrk, mmap, and munmap otherwise degrade performance, the default
  551. parameters are set to relatively high values that serve only as
  552. safeguards.
  553. The default trim value is high enough to cause trimming only in
  554. fairly extreme (by current memory consumption standards) cases.
  555. It must be greater than page size to have any useful effect. To
  556. disable trimming completely, you can set to (unsigned long)(-1);
  557. */
  558. #ifndef DEFAULT_TOP_PAD
  559. #define DEFAULT_TOP_PAD (0)
  560. #endif
  561. /*
  562. M_TOP_PAD is the amount of extra `padding' space to allocate or
  563. retain whenever sbrk is called. It is used in two ways internally:
  564. * When sbrk is called to extend the top of the arena to satisfy
  565. a new malloc request, this much padding is added to the sbrk
  566. request.
  567. * When malloc_trim is called automatically from free(),
  568. it is used as the `pad' argument.
  569. In both cases, the actual amount of padding is rounded
  570. so that the end of the arena is always a system page boundary.
  571. The main reason for using padding is to avoid calling sbrk so
  572. often. Having even a small pad greatly reduces the likelihood
  573. that nearly every malloc request during program start-up (or
  574. after trimming) will invoke sbrk, which needlessly wastes
  575. time.
  576. Automatic rounding-up to page-size units is normally sufficient
  577. to avoid measurable overhead, so the default is 0. However, in
  578. systems where sbrk is relatively slow, it can pay to increase
  579. this value, at the expense of carrying around more memory than
  580. the program needs.
  581. */
  582. #ifndef DEFAULT_MMAP_THRESHOLD
  583. #define DEFAULT_MMAP_THRESHOLD (128 * 1024)
  584. #endif
  585. /*
  586. M_MMAP_THRESHOLD is the request size threshold for using mmap()
  587. to service a request. Requests of at least this size that cannot
  588. be allocated using already-existing space will be serviced via mmap.
  589. (If enough normal freed space already exists it is used instead.)
  590. Using mmap segregates relatively large chunks of memory so that
  591. they can be individually obtained and released from the host
  592. system. A request serviced through mmap is never reused by any
  593. other request (at least not directly; the system may just so
  594. happen to remap successive requests to the same locations).
  595. Segregating space in this way has the benefit that mmapped space
  596. can ALWAYS be individually released back to the system, which
  597. helps keep the system level memory demands of a long-lived
  598. program low. Mapped memory can never become `locked' between
  599. other chunks, as can happen with normally allocated chunks, which
  600. menas that even trimming via malloc_trim would not release them.
  601. However, it has the disadvantages that:
  602. 1. The space cannot be reclaimed, consolidated, and then
  603. used to service later requests, as happens with normal chunks.
  604. 2. It can lead to more wastage because of mmap page alignment
  605. requirements
  606. 3. It causes malloc performance to be more dependent on host
  607. system memory management support routines which may vary in
  608. implementation quality and may impose arbitrary
  609. limitations. Generally, servicing a request via normal
  610. malloc steps is faster than going through a system's mmap.
  611. All together, these considerations should lead you to use mmap
  612. only for relatively large requests.
  613. */
  614. #ifndef DEFAULT_MMAP_MAX
  615. #if HAVE_MMAP
  616. #define DEFAULT_MMAP_MAX (64)
  617. #else
  618. #define DEFAULT_MMAP_MAX (0)
  619. #endif
  620. #endif
  621. /*
  622. M_MMAP_MAX is the maximum number of requests to simultaneously
  623. service using mmap. This parameter exists because:
  624. 1. Some systems have a limited number of internal tables for
  625. use by mmap.
  626. 2. In most systems, overreliance on mmap can degrade overall
  627. performance.
  628. 3. If a program allocates many large regions, it is probably
  629. better off using normal sbrk-based allocation routines that
  630. can reclaim and reallocate normal heap memory. Using a
  631. small value allows transition into this mode after the
  632. first few allocations.
  633. Setting to 0 disables all use of mmap. If HAVE_MMAP is not set,
  634. the default value is 0, and attempts to set it to non-zero values
  635. in mallopt will fail.
  636. */
  637. /*
  638. USE_DL_PREFIX will prefix all public routines with the string 'dl'.
  639. Useful to quickly avoid procedure declaration conflicts and linker
  640. symbol conflicts with existing memory allocation routines.
  641. */
  642. /* #define USE_DL_PREFIX */
  643. /*
  644. Special defines for linux libc
  645. Except when compiled using these special defines for Linux libc
  646. using weak aliases, this malloc is NOT designed to work in
  647. multithreaded applications. No semaphores or other concurrency
  648. control are provided to ensure that multiple malloc or free calls
  649. don't run at the same time, which could be disasterous. A single
  650. semaphore could be used across malloc, realloc, and free (which is
  651. essentially the effect of the linux weak alias approach). It would
  652. be hard to obtain finer granularity.
  653. */
  654. #ifdef INTERNAL_LINUX_C_LIB
  655. #if __STD_C
  656. Void_t * __default_morecore_init (ptrdiff_t);
  657. Void_t *(*__morecore)(ptrdiff_t) = __default_morecore_init;
  658. #else
  659. Void_t * __default_morecore_init ();
  660. Void_t *(*__morecore)() = __default_morecore_init;
  661. #endif
  662. #define MORECORE (*__morecore)
  663. #define MORECORE_FAILURE 0
  664. #define MORECORE_CLEARS 1
  665. #else /* INTERNAL_LINUX_C_LIB */
  666. #if __STD_C
  667. extern Void_t* sbrk(ptrdiff_t);
  668. #else
  669. extern Void_t* sbrk();
  670. #endif
  671. #ifndef MORECORE
  672. #define MORECORE sbrk
  673. #endif
  674. #ifndef MORECORE_FAILURE
  675. #define MORECORE_FAILURE -1
  676. #endif
  677. #ifndef MORECORE_CLEARS
  678. #define MORECORE_CLEARS 1
  679. #endif
  680. #endif /* INTERNAL_LINUX_C_LIB */
  681. #if defined(INTERNAL_LINUX_C_LIB) && defined(__ELF__)
  682. #define cALLOc __libc_calloc
  683. #define fREe __libc_free
  684. #define mALLOc __libc_malloc
  685. #define mEMALIGn __libc_memalign
  686. #define rEALLOc __libc_realloc
  687. #define vALLOc __libc_valloc
  688. #define pvALLOc __libc_pvalloc
  689. #define mALLINFo __libc_mallinfo
  690. #define mALLOPt __libc_mallopt
  691. #pragma weak calloc = __libc_calloc
  692. #pragma weak free = __libc_free
  693. #pragma weak cfree = __libc_free
  694. #pragma weak malloc = __libc_malloc
  695. #pragma weak memalign = __libc_memalign
  696. #pragma weak realloc = __libc_realloc
  697. #pragma weak valloc = __libc_valloc
  698. #pragma weak pvalloc = __libc_pvalloc
  699. #pragma weak mallinfo = __libc_mallinfo
  700. #pragma weak mallopt = __libc_mallopt
  701. #else
  702. #ifdef USE_DL_PREFIX
  703. #define cALLOc dlcalloc
  704. #define fREe dlfree
  705. #define mALLOc dlmalloc
  706. #define mEMALIGn dlmemalign
  707. #define rEALLOc dlrealloc
  708. #define vALLOc dlvalloc
  709. #define pvALLOc dlpvalloc
  710. #define mALLINFo dlmallinfo
  711. #define mALLOPt dlmallopt
  712. #else /* USE_DL_PREFIX */
  713. #define cALLOc calloc
  714. #define fREe free
  715. #define mALLOc malloc
  716. #define mEMALIGn memalign
  717. #define rEALLOc realloc
  718. #define vALLOc valloc
  719. #define pvALLOc pvalloc
  720. #define mALLINFo mallinfo
  721. #define mALLOPt mallopt
  722. #endif /* USE_DL_PREFIX */
  723. #endif
  724. /* Public routines */
  725. #if __STD_C
  726. Void_t* mALLOc(size_t);
  727. void fREe(Void_t*);
  728. Void_t* rEALLOc(Void_t*, size_t);
  729. Void_t* mEMALIGn(size_t, size_t);
  730. Void_t* vALLOc(size_t);
  731. Void_t* pvALLOc(size_t);
  732. Void_t* cALLOc(size_t, size_t);
  733. void cfree(Void_t*);
  734. int malloc_trim(size_t);
  735. size_t malloc_usable_size(Void_t*);
  736. void malloc_stats();
  737. int mALLOPt(int, int);
  738. struct mallinfo mALLINFo(void);
  739. #else
  740. Void_t* mALLOc();
  741. void fREe();
  742. Void_t* rEALLOc();
  743. Void_t* mEMALIGn();
  744. Void_t* vALLOc();
  745. Void_t* pvALLOc();
  746. Void_t* cALLOc();
  747. void cfree();
  748. int malloc_trim();
  749. size_t malloc_usable_size();
  750. void malloc_stats();
  751. int mALLOPt();
  752. struct mallinfo mALLINFo();
  753. #endif
  754. #ifdef __cplusplus
  755. }; /* end of extern "C" */
  756. #endif
  757. /* ---------- To make a malloc.h, end cutting here ------------ */
  758. #endif /* 0 */ /* Moved to malloc.h */
  759. #include <malloc.h>
  760. #ifdef DEBUG
  761. #if __STD_C
  762. static void malloc_update_mallinfo (void);
  763. void malloc_stats (void);
  764. #else
  765. static void malloc_update_mallinfo ();
  766. void malloc_stats();
  767. #endif
  768. #endif /* DEBUG */
  769. DECLARE_GLOBAL_DATA_PTR;
  770. /*
  771. Emulation of sbrk for WIN32
  772. All code within the ifdef WIN32 is untested by me.
  773. Thanks to Martin Fong and others for supplying this.
  774. */
  775. #ifdef WIN32
  776. #define AlignPage(add) (((add) + (malloc_getpagesize-1)) & \
  777. ~(malloc_getpagesize-1))
  778. #define AlignPage64K(add) (((add) + (0x10000 - 1)) & ~(0x10000 - 1))
  779. /* resrve 64MB to insure large contiguous space */
  780. #define RESERVED_SIZE (1024*1024*64)
  781. #define NEXT_SIZE (2048*1024)
  782. #define TOP_MEMORY ((unsigned long)2*1024*1024*1024)
  783. struct GmListElement;
  784. typedef struct GmListElement GmListElement;
  785. struct GmListElement
  786. {
  787. GmListElement* next;
  788. void* base;
  789. };
  790. static GmListElement* head = 0;
  791. static unsigned int gNextAddress = 0;
  792. static unsigned int gAddressBase = 0;
  793. static unsigned int gAllocatedSize = 0;
  794. static
  795. GmListElement* makeGmListElement (void* bas)
  796. {
  797. GmListElement* this;
  798. this = (GmListElement*)(void*)LocalAlloc (0, sizeof (GmListElement));
  799. assert (this);
  800. if (this)
  801. {
  802. this->base = bas;
  803. this->next = head;
  804. head = this;
  805. }
  806. return this;
  807. }
  808. void gcleanup ()
  809. {
  810. BOOL rval;
  811. assert ( (head == NULL) || (head->base == (void*)gAddressBase));
  812. if (gAddressBase && (gNextAddress - gAddressBase))
  813. {
  814. rval = VirtualFree ((void*)gAddressBase,
  815. gNextAddress - gAddressBase,
  816. MEM_DECOMMIT);
  817. assert (rval);
  818. }
  819. while (head)
  820. {
  821. GmListElement* next = head->next;
  822. rval = VirtualFree (head->base, 0, MEM_RELEASE);
  823. assert (rval);
  824. LocalFree (head);
  825. head = next;
  826. }
  827. }
  828. static
  829. void* findRegion (void* start_address, unsigned long size)
  830. {
  831. MEMORY_BASIC_INFORMATION info;
  832. if (size >= TOP_MEMORY) return NULL;
  833. while ((unsigned long)start_address + size < TOP_MEMORY)
  834. {
  835. VirtualQuery (start_address, &info, sizeof (info));
  836. if ((info.State == MEM_FREE) && (info.RegionSize >= size))
  837. return start_address;
  838. else
  839. {
  840. /* Requested region is not available so see if the */
  841. /* next region is available. Set 'start_address' */
  842. /* to the next region and call 'VirtualQuery()' */
  843. /* again. */
  844. start_address = (char*)info.BaseAddress + info.RegionSize;
  845. /* Make sure we start looking for the next region */
  846. /* on the *next* 64K boundary. Otherwise, even if */
  847. /* the new region is free according to */
  848. /* 'VirtualQuery()', the subsequent call to */
  849. /* 'VirtualAlloc()' (which follows the call to */
  850. /* this routine in 'wsbrk()') will round *down* */
  851. /* the requested address to a 64K boundary which */
  852. /* we already know is an address in the */
  853. /* unavailable region. Thus, the subsequent call */
  854. /* to 'VirtualAlloc()' will fail and bring us back */
  855. /* here, causing us to go into an infinite loop. */
  856. start_address =
  857. (void *) AlignPage64K((unsigned long) start_address);
  858. }
  859. }
  860. return NULL;
  861. }
  862. void* wsbrk (long size)
  863. {
  864. void* tmp;
  865. if (size > 0)
  866. {
  867. if (gAddressBase == 0)
  868. {
  869. gAllocatedSize = max (RESERVED_SIZE, AlignPage (size));
  870. gNextAddress = gAddressBase =
  871. (unsigned int)VirtualAlloc (NULL, gAllocatedSize,
  872. MEM_RESERVE, PAGE_NOACCESS);
  873. } else if (AlignPage (gNextAddress + size) > (gAddressBase +
  874. gAllocatedSize))
  875. {
  876. long new_size = max (NEXT_SIZE, AlignPage (size));
  877. void* new_address = (void*)(gAddressBase+gAllocatedSize);
  878. do
  879. {
  880. new_address = findRegion (new_address, new_size);
  881. if (new_address == 0)
  882. return (void*)-1;
  883. gAddressBase = gNextAddress =
  884. (unsigned int)VirtualAlloc (new_address, new_size,
  885. MEM_RESERVE, PAGE_NOACCESS);
  886. /* repeat in case of race condition */
  887. /* The region that we found has been snagged */
  888. /* by another thread */
  889. }
  890. while (gAddressBase == 0);
  891. assert (new_address == (void*)gAddressBase);
  892. gAllocatedSize = new_size;
  893. if (!makeGmListElement ((void*)gAddressBase))
  894. return (void*)-1;
  895. }
  896. if ((size + gNextAddress) > AlignPage (gNextAddress))
  897. {
  898. void* res;
  899. res = VirtualAlloc ((void*)AlignPage (gNextAddress),
  900. (size + gNextAddress -
  901. AlignPage (gNextAddress)),
  902. MEM_COMMIT, PAGE_READWRITE);
  903. if (res == 0)
  904. return (void*)-1;
  905. }
  906. tmp = (void*)gNextAddress;
  907. gNextAddress = (unsigned int)tmp + size;
  908. return tmp;
  909. }
  910. else if (size < 0)
  911. {
  912. unsigned int alignedGoal = AlignPage (gNextAddress + size);
  913. /* Trim by releasing the virtual memory */
  914. if (alignedGoal >= gAddressBase)
  915. {
  916. VirtualFree ((void*)alignedGoal, gNextAddress - alignedGoal,
  917. MEM_DECOMMIT);
  918. gNextAddress = gNextAddress + size;
  919. return (void*)gNextAddress;
  920. }
  921. else
  922. {
  923. VirtualFree ((void*)gAddressBase, gNextAddress - gAddressBase,
  924. MEM_DECOMMIT);
  925. gNextAddress = gAddressBase;
  926. return (void*)-1;
  927. }
  928. }
  929. else
  930. {
  931. return (void*)gNextAddress;
  932. }
  933. }
  934. #endif
  935. /*
  936. Type declarations
  937. */
  938. struct malloc_chunk
  939. {
  940. INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
  941. INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
  942. struct malloc_chunk* fd; /* double links -- used only if free. */
  943. struct malloc_chunk* bk;
  944. } __attribute__((__may_alias__)) ;
  945. typedef struct malloc_chunk* mchunkptr;
  946. /*
  947. malloc_chunk details:
  948. (The following includes lightly edited explanations by Colin Plumb.)
  949. Chunks of memory are maintained using a `boundary tag' method as
  950. described in e.g., Knuth or Standish. (See the paper by Paul
  951. Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
  952. survey of such techniques.) Sizes of free chunks are stored both
  953. in the front of each chunk and at the end. This makes
  954. consolidating fragmented chunks into bigger chunks very fast. The
  955. size fields also hold bits representing whether chunks are free or
  956. in use.
  957. An allocated chunk looks like this:
  958. chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  959. | Size of previous chunk, if allocated | |
  960. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  961. | Size of chunk, in bytes |P|
  962. mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  963. | User data starts here... .
  964. . .
  965. . (malloc_usable_space() bytes) .
  966. . |
  967. nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  968. | Size of chunk |
  969. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  970. Where "chunk" is the front of the chunk for the purpose of most of
  971. the malloc code, but "mem" is the pointer that is returned to the
  972. user. "Nextchunk" is the beginning of the next contiguous chunk.
  973. Chunks always begin on even word boundries, so the mem portion
  974. (which is returned to the user) is also on an even word boundary, and
  975. thus double-word aligned.
  976. Free chunks are stored in circular doubly-linked lists, and look like this:
  977. chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  978. | Size of previous chunk |
  979. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  980. `head:' | Size of chunk, in bytes |P|
  981. mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  982. | Forward pointer to next chunk in list |
  983. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  984. | Back pointer to previous chunk in list |
  985. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  986. | Unused space (may be 0 bytes long) .
  987. . .
  988. . |
  989. nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  990. `foot:' | Size of chunk, in bytes |
  991. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  992. The P (PREV_INUSE) bit, stored in the unused low-order bit of the
  993. chunk size (which is always a multiple of two words), is an in-use
  994. bit for the *previous* chunk. If that bit is *clear*, then the
  995. word before the current chunk size contains the previous chunk
  996. size, and can be used to find the front of the previous chunk.
  997. (The very first chunk allocated always has this bit set,
  998. preventing access to non-existent (or non-owned) memory.)
  999. Note that the `foot' of the current chunk is actually represented
  1000. as the prev_size of the NEXT chunk. (This makes it easier to
  1001. deal with alignments etc).
  1002. The two exceptions to all this are
  1003. 1. The special chunk `top', which doesn't bother using the
  1004. trailing size field since there is no
  1005. next contiguous chunk that would have to index off it. (After
  1006. initialization, `top' is forced to always exist. If it would
  1007. become less than MINSIZE bytes long, it is replenished via
  1008. malloc_extend_top.)
  1009. 2. Chunks allocated via mmap, which have the second-lowest-order
  1010. bit (IS_MMAPPED) set in their size fields. Because they are
  1011. never merged or traversed from any other chunk, they have no
  1012. foot size or inuse information.
  1013. Available chunks are kept in any of several places (all declared below):
  1014. * `av': An array of chunks serving as bin headers for consolidated
  1015. chunks. Each bin is doubly linked. The bins are approximately
  1016. proportionally (log) spaced. There are a lot of these bins
  1017. (128). This may look excessive, but works very well in
  1018. practice. All procedures maintain the invariant that no
  1019. consolidated chunk physically borders another one. Chunks in
  1020. bins are kept in size order, with ties going to the
  1021. approximately least recently used chunk.
  1022. The chunks in each bin are maintained in decreasing sorted order by
  1023. size. This is irrelevant for the small bins, which all contain
  1024. the same-sized chunks, but facilitates best-fit allocation for
  1025. larger chunks. (These lists are just sequential. Keeping them in
  1026. order almost never requires enough traversal to warrant using
  1027. fancier ordered data structures.) Chunks of the same size are
  1028. linked with the most recently freed at the front, and allocations
  1029. are taken from the back. This results in LRU or FIFO allocation
  1030. order, which tends to give each chunk an equal opportunity to be
  1031. consolidated with adjacent freed chunks, resulting in larger free
  1032. chunks and less fragmentation.
  1033. * `top': The top-most available chunk (i.e., the one bordering the
  1034. end of available memory) is treated specially. It is never
  1035. included in any bin, is used only if no other chunk is
  1036. available, and is released back to the system if it is very
  1037. large (see M_TRIM_THRESHOLD).
  1038. * `last_remainder': A bin holding only the remainder of the
  1039. most recently split (non-top) chunk. This bin is checked
  1040. before other non-fitting chunks, so as to provide better
  1041. locality for runs of sequentially allocated chunks.
  1042. * Implicitly, through the host system's memory mapping tables.
  1043. If supported, requests greater than a threshold are usually
  1044. serviced via calls to mmap, and then later released via munmap.
  1045. */
  1046. /* sizes, alignments */
  1047. #define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
  1048. #define MALLOC_ALIGNMENT (SIZE_SZ + SIZE_SZ)
  1049. #define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
  1050. #define MINSIZE (sizeof(struct malloc_chunk))
  1051. /* conversion from malloc headers to user pointers, and back */
  1052. #define chunk2mem(p) ((Void_t*)((char*)(p) + 2*SIZE_SZ))
  1053. #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
  1054. /* pad request bytes into a usable size */
  1055. #define request2size(req) \
  1056. (((long)((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) < \
  1057. (long)(MINSIZE + MALLOC_ALIGN_MASK)) ? MINSIZE : \
  1058. (((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) & ~(MALLOC_ALIGN_MASK)))
  1059. /* Check if m has acceptable alignment */
  1060. #define aligned_OK(m) (((unsigned long)((m)) & (MALLOC_ALIGN_MASK)) == 0)
  1061. /*
  1062. Physical chunk operations
  1063. */
  1064. /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
  1065. #define PREV_INUSE 0x1
  1066. /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
  1067. #define IS_MMAPPED 0x2
  1068. /* Bits to mask off when extracting size */
  1069. #define SIZE_BITS (PREV_INUSE|IS_MMAPPED)
  1070. /* Ptr to next physical malloc_chunk. */
  1071. #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~PREV_INUSE) ))
  1072. /* Ptr to previous physical malloc_chunk */
  1073. #define prev_chunk(p)\
  1074. ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
  1075. /* Treat space at ptr + offset as a chunk */
  1076. #define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
  1077. /*
  1078. Dealing with use bits
  1079. */
  1080. /* extract p's inuse bit */
  1081. #define inuse(p)\
  1082. ((((mchunkptr)(((char*)(p))+((p)->size & ~PREV_INUSE)))->size) & PREV_INUSE)
  1083. /* extract inuse bit of previous chunk */
  1084. #define prev_inuse(p) ((p)->size & PREV_INUSE)
  1085. /* check for mmap()'ed chunk */
  1086. #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
  1087. /* set/clear chunk as in use without otherwise disturbing */
  1088. #define set_inuse(p)\
  1089. ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size |= PREV_INUSE
  1090. #define clear_inuse(p)\
  1091. ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size &= ~(PREV_INUSE)
  1092. /* check/set/clear inuse bits in known places */
  1093. #define inuse_bit_at_offset(p, s)\
  1094. (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)
  1095. #define set_inuse_bit_at_offset(p, s)\
  1096. (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
  1097. #define clear_inuse_bit_at_offset(p, s)\
  1098. (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
  1099. /*
  1100. Dealing with size fields
  1101. */
  1102. /* Get size, ignoring use bits */
  1103. #define chunksize(p) ((p)->size & ~(SIZE_BITS))
  1104. /* Set size at head, without disturbing its use bit */
  1105. #define set_head_size(p, s) ((p)->size = (((p)->size & PREV_INUSE) | (s)))
  1106. /* Set size/use ignoring previous bits in header */
  1107. #define set_head(p, s) ((p)->size = (s))
  1108. /* Set size at footer (only when chunk is not in use) */
  1109. #define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))
  1110. /*
  1111. Bins
  1112. The bins, `av_' are an array of pairs of pointers serving as the
  1113. heads of (initially empty) doubly-linked lists of chunks, laid out
  1114. in a way so that each pair can be treated as if it were in a
  1115. malloc_chunk. (This way, the fd/bk offsets for linking bin heads
  1116. and chunks are the same).
  1117. Bins for sizes < 512 bytes contain chunks of all the same size, spaced
  1118. 8 bytes apart. Larger bins are approximately logarithmically
  1119. spaced. (See the table below.) The `av_' array is never mentioned
  1120. directly in the code, but instead via bin access macros.
  1121. Bin layout:
  1122. 64 bins of size 8
  1123. 32 bins of size 64
  1124. 16 bins of size 512
  1125. 8 bins of size 4096
  1126. 4 bins of size 32768
  1127. 2 bins of size 262144
  1128. 1 bin of size what's left
  1129. There is actually a little bit of slop in the numbers in bin_index
  1130. for the sake of speed. This makes no difference elsewhere.
  1131. The special chunks `top' and `last_remainder' get their own bins,
  1132. (this is implemented via yet more trickery with the av_ array),
  1133. although `top' is never properly linked to its bin since it is
  1134. always handled specially.
  1135. */
  1136. #define NAV 128 /* number of bins */
  1137. typedef struct malloc_chunk* mbinptr;
  1138. /* access macros */
  1139. #define bin_at(i) ((mbinptr)((char*)&(av_[2*(i) + 2]) - 2*SIZE_SZ))
  1140. #define next_bin(b) ((mbinptr)((char*)(b) + 2 * sizeof(mbinptr)))
  1141. #define prev_bin(b) ((mbinptr)((char*)(b) - 2 * sizeof(mbinptr)))
  1142. /*
  1143. The first 2 bins are never indexed. The corresponding av_ cells are instead
  1144. used for bookkeeping. This is not to save space, but to simplify
  1145. indexing, maintain locality, and avoid some initialization tests.
  1146. */
  1147. #define top (av_[2]) /* The topmost chunk */
  1148. #define last_remainder (bin_at(1)) /* remainder from last split */
  1149. /*
  1150. Because top initially points to its own bin with initial
  1151. zero size, thus forcing extension on the first malloc request,
  1152. we avoid having any special code in malloc to check whether
  1153. it even exists yet. But we still need to in malloc_extend_top.
  1154. */
  1155. #define initial_top ((mchunkptr)(bin_at(0)))
  1156. /* Helper macro to initialize bins */
  1157. #define IAV(i) bin_at(i), bin_at(i)
  1158. static mbinptr av_[NAV * 2 + 2] = {
  1159. NULL, NULL,
  1160. IAV(0), IAV(1), IAV(2), IAV(3), IAV(4), IAV(5), IAV(6), IAV(7),
  1161. IAV(8), IAV(9), IAV(10), IAV(11), IAV(12), IAV(13), IAV(14), IAV(15),
  1162. IAV(16), IAV(17), IAV(18), IAV(19), IAV(20), IAV(21), IAV(22), IAV(23),
  1163. IAV(24), IAV(25), IAV(26), IAV(27), IAV(28), IAV(29), IAV(30), IAV(31),
  1164. IAV(32), IAV(33), IAV(34), IAV(35), IAV(36), IAV(37), IAV(38), IAV(39),
  1165. IAV(40), IAV(41), IAV(42), IAV(43), IAV(44), IAV(45), IAV(46), IAV(47),
  1166. IAV(48), IAV(49), IAV(50), IAV(51), IAV(52), IAV(53), IAV(54), IAV(55),
  1167. IAV(56), IAV(57), IAV(58), IAV(59), IAV(60), IAV(61), IAV(62), IAV(63),
  1168. IAV(64), IAV(65), IAV(66), IAV(67), IAV(68), IAV(69), IAV(70), IAV(71),
  1169. IAV(72), IAV(73), IAV(74), IAV(75), IAV(76), IAV(77), IAV(78), IAV(79),
  1170. IAV(80), IAV(81), IAV(82), IAV(83), IAV(84), IAV(85), IAV(86), IAV(87),
  1171. IAV(88), IAV(89), IAV(90), IAV(91), IAV(92), IAV(93), IAV(94), IAV(95),
  1172. IAV(96), IAV(97), IAV(98), IAV(99), IAV(100), IAV(101), IAV(102), IAV(103),
  1173. IAV(104), IAV(105), IAV(106), IAV(107), IAV(108), IAV(109), IAV(110), IAV(111),
  1174. IAV(112), IAV(113), IAV(114), IAV(115), IAV(116), IAV(117), IAV(118), IAV(119),
  1175. IAV(120), IAV(121), IAV(122), IAV(123), IAV(124), IAV(125), IAV(126), IAV(127)
  1176. };
  1177. #ifdef CONFIG_NEEDS_MANUAL_RELOC
  1178. static void malloc_bin_reloc(void)
  1179. {
  1180. mbinptr *p = &av_[2];
  1181. size_t i;
  1182. for (i = 2; i < ARRAY_SIZE(av_); ++i, ++p)
  1183. *p = (mbinptr)((ulong)*p + gd->reloc_off);
  1184. }
  1185. #else
  1186. static inline void malloc_bin_reloc(void) {}
  1187. #endif
  1188. ulong mem_malloc_start = 0;
  1189. ulong mem_malloc_end = 0;
  1190. ulong mem_malloc_brk = 0;
  1191. void *sbrk(ptrdiff_t increment)
  1192. {
  1193. ulong old = mem_malloc_brk;
  1194. ulong new = old + increment;
  1195. /*
  1196. * if we are giving memory back make sure we clear it out since
  1197. * we set MORECORE_CLEARS to 1
  1198. */
  1199. if (increment < 0)
  1200. memset((void *)new, 0, -increment);
  1201. if ((new < mem_malloc_start) || (new > mem_malloc_end))
  1202. return (void *)MORECORE_FAILURE;
  1203. mem_malloc_brk = new;
  1204. return (void *)old;
  1205. }
  1206. void mem_malloc_init(ulong start, ulong size)
  1207. {
  1208. mem_malloc_start = start;
  1209. mem_malloc_end = start + size;
  1210. mem_malloc_brk = start;
  1211. memset((void *)mem_malloc_start, 0, size);
  1212. malloc_bin_reloc();
  1213. }
  1214. /* field-extraction macros */
  1215. #define first(b) ((b)->fd)
  1216. #define last(b) ((b)->bk)
  1217. /*
  1218. Indexing into bins
  1219. */
  1220. #define bin_index(sz) \
  1221. (((((unsigned long)(sz)) >> 9) == 0) ? (((unsigned long)(sz)) >> 3): \
  1222. ((((unsigned long)(sz)) >> 9) <= 4) ? 56 + (((unsigned long)(sz)) >> 6): \
  1223. ((((unsigned long)(sz)) >> 9) <= 20) ? 91 + (((unsigned long)(sz)) >> 9): \
  1224. ((((unsigned long)(sz)) >> 9) <= 84) ? 110 + (((unsigned long)(sz)) >> 12): \
  1225. ((((unsigned long)(sz)) >> 9) <= 340) ? 119 + (((unsigned long)(sz)) >> 15): \
  1226. ((((unsigned long)(sz)) >> 9) <= 1364) ? 124 + (((unsigned long)(sz)) >> 18): \
  1227. 126)
  1228. /*
  1229. bins for chunks < 512 are all spaced 8 bytes apart, and hold
  1230. identically sized chunks. This is exploited in malloc.
  1231. */
  1232. #define MAX_SMALLBIN 63
  1233. #define MAX_SMALLBIN_SIZE 512
  1234. #define SMALLBIN_WIDTH 8
  1235. #define smallbin_index(sz) (((unsigned long)(sz)) >> 3)
  1236. /*
  1237. Requests are `small' if both the corresponding and the next bin are small
  1238. */
  1239. #define is_small_request(nb) (nb < MAX_SMALLBIN_SIZE - SMALLBIN_WIDTH)
  1240. /*
  1241. To help compensate for the large number of bins, a one-level index
  1242. structure is used for bin-by-bin searching. `binblocks' is a
  1243. one-word bitvector recording whether groups of BINBLOCKWIDTH bins
  1244. have any (possibly) non-empty bins, so they can be skipped over
  1245. all at once during during traversals. The bits are NOT always
  1246. cleared as soon as all bins in a block are empty, but instead only
  1247. when all are noticed to be empty during traversal in malloc.
  1248. */
  1249. #define BINBLOCKWIDTH 4 /* bins per block */
  1250. #define binblocks_r ((INTERNAL_SIZE_T)av_[1]) /* bitvector of nonempty blocks */
  1251. #define binblocks_w (av_[1])
  1252. /* bin<->block macros */
  1253. #define idx2binblock(ix) ((unsigned)1 << (ix / BINBLOCKWIDTH))
  1254. #define mark_binblock(ii) (binblocks_w = (mbinptr)(binblocks_r | idx2binblock(ii)))
  1255. #define clear_binblock(ii) (binblocks_w = (mbinptr)(binblocks_r & ~(idx2binblock(ii))))
  1256. /* Other static bookkeeping data */
  1257. /* variables holding tunable values */
  1258. static unsigned long trim_threshold = DEFAULT_TRIM_THRESHOLD;
  1259. static unsigned long top_pad = DEFAULT_TOP_PAD;
  1260. static unsigned int n_mmaps_max = DEFAULT_MMAP_MAX;
  1261. static unsigned long mmap_threshold = DEFAULT_MMAP_THRESHOLD;
  1262. /* The first value returned from sbrk */
  1263. static char* sbrk_base = (char*)(-1);
  1264. /* The maximum memory obtained from system via sbrk */
  1265. static unsigned long max_sbrked_mem = 0;
  1266. /* The maximum via either sbrk or mmap */
  1267. static unsigned long max_total_mem = 0;
  1268. /* internal working copy of mallinfo */
  1269. static struct mallinfo current_mallinfo = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  1270. /* The total memory obtained from system via sbrk */
  1271. #define sbrked_mem (current_mallinfo.arena)
  1272. /* Tracking mmaps */
  1273. #ifdef DEBUG
  1274. static unsigned int n_mmaps = 0;
  1275. #endif /* DEBUG */
  1276. static unsigned long mmapped_mem = 0;
  1277. #if HAVE_MMAP
  1278. static unsigned int max_n_mmaps = 0;
  1279. static unsigned long max_mmapped_mem = 0;
  1280. #endif
  1281. /*
  1282. Debugging support
  1283. */
  1284. #ifdef DEBUG
  1285. /*
  1286. These routines make a number of assertions about the states
  1287. of data structures that should be true at all times. If any
  1288. are not true, it's very likely that a user program has somehow
  1289. trashed memory. (It's also possible that there is a coding error
  1290. in malloc. In which case, please report it!)
  1291. */
  1292. #if __STD_C
  1293. static void do_check_chunk(mchunkptr p)
  1294. #else
  1295. static void do_check_chunk(p) mchunkptr p;
  1296. #endif
  1297. {
  1298. INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
  1299. /* No checkable chunk is mmapped */
  1300. assert(!chunk_is_mmapped(p));
  1301. /* Check for legal address ... */
  1302. assert((char*)p >= sbrk_base);
  1303. if (p != top)
  1304. assert((char*)p + sz <= (char*)top);
  1305. else
  1306. assert((char*)p + sz <= sbrk_base + sbrked_mem);
  1307. }
  1308. #if __STD_C
  1309. static void do_check_free_chunk(mchunkptr p)
  1310. #else
  1311. static void do_check_free_chunk(p) mchunkptr p;
  1312. #endif
  1313. {
  1314. INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
  1315. mchunkptr next = chunk_at_offset(p, sz);
  1316. do_check_chunk(p);
  1317. /* Check whether it claims to be free ... */
  1318. assert(!inuse(p));
  1319. /* Unless a special marker, must have OK fields */
  1320. if ((long)sz >= (long)MINSIZE)
  1321. {
  1322. assert((sz & MALLOC_ALIGN_MASK) == 0);
  1323. assert(aligned_OK(chunk2mem(p)));
  1324. /* ... matching footer field */
  1325. assert(next->prev_size == sz);
  1326. /* ... and is fully consolidated */
  1327. assert(prev_inuse(p));
  1328. assert (next == top || inuse(next));
  1329. /* ... and has minimally sane links */
  1330. assert(p->fd->bk == p);
  1331. assert(p->bk->fd == p);
  1332. }
  1333. else /* markers are always of size SIZE_SZ */
  1334. assert(sz == SIZE_SZ);
  1335. }
  1336. #if __STD_C
  1337. static void do_check_inuse_chunk(mchunkptr p)
  1338. #else
  1339. static void do_check_inuse_chunk(p) mchunkptr p;
  1340. #endif
  1341. {
  1342. mchunkptr next = next_chunk(p);
  1343. do_check_chunk(p);
  1344. /* Check whether it claims to be in use ... */
  1345. assert(inuse(p));
  1346. /* ... and is surrounded by OK chunks.
  1347. Since more things can be checked with free chunks than inuse ones,
  1348. if an inuse chunk borders them and debug is on, it's worth doing them.
  1349. */
  1350. if (!prev_inuse(p))
  1351. {
  1352. mchunkptr prv = prev_chunk(p);
  1353. assert(next_chunk(prv) == p);
  1354. do_check_free_chunk(prv);
  1355. }
  1356. if (next == top)
  1357. {
  1358. assert(prev_inuse(next));
  1359. assert(chunksize(next) >= MINSIZE);
  1360. }
  1361. else if (!inuse(next))
  1362. do_check_free_chunk(next);
  1363. }
  1364. #if __STD_C
  1365. static void do_check_malloced_chunk(mchunkptr p, INTERNAL_SIZE_T s)
  1366. #else
  1367. static void do_check_malloced_chunk(p, s) mchunkptr p; INTERNAL_SIZE_T s;
  1368. #endif
  1369. {
  1370. INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
  1371. long room = sz - s;
  1372. do_check_inuse_chunk(p);
  1373. /* Legal size ... */
  1374. assert((long)sz >= (long)MINSIZE);
  1375. assert((sz & MALLOC_ALIGN_MASK) == 0);
  1376. assert(room >= 0);
  1377. assert(room < (long)MINSIZE);
  1378. /* ... and alignment */
  1379. assert(aligned_OK(chunk2mem(p)));
  1380. /* ... and was allocated at front of an available chunk */
  1381. assert(prev_inuse(p));
  1382. }
  1383. #define check_free_chunk(P) do_check_free_chunk(P)
  1384. #define check_inuse_chunk(P) do_check_inuse_chunk(P)
  1385. #define check_chunk(P) do_check_chunk(P)
  1386. #define check_malloced_chunk(P,N) do_check_malloced_chunk(P,N)
  1387. #else
  1388. #define check_free_chunk(P)
  1389. #define check_inuse_chunk(P)
  1390. #define check_chunk(P)
  1391. #define check_malloced_chunk(P,N)
  1392. #endif
  1393. /*
  1394. Macro-based internal utilities
  1395. */
  1396. /*
  1397. Linking chunks in bin lists.
  1398. Call these only with variables, not arbitrary expressions, as arguments.
  1399. */
  1400. /*
  1401. Place chunk p of size s in its bin, in size order,
  1402. putting it ahead of others of same size.
  1403. */
  1404. #define frontlink(P, S, IDX, BK, FD) \
  1405. { \
  1406. if (S < MAX_SMALLBIN_SIZE) \
  1407. { \
  1408. IDX = smallbin_index(S); \
  1409. mark_binblock(IDX); \
  1410. BK = bin_at(IDX); \
  1411. FD = BK->fd; \
  1412. P->bk = BK; \
  1413. P->fd = FD; \
  1414. FD->bk = BK->fd = P; \
  1415. } \
  1416. else \
  1417. { \
  1418. IDX = bin_index(S); \
  1419. BK = bin_at(IDX); \
  1420. FD = BK->fd; \
  1421. if (FD == BK) mark_binblock(IDX); \
  1422. else \
  1423. { \
  1424. while (FD != BK && S < chunksize(FD)) FD = FD->fd; \
  1425. BK = FD->bk; \
  1426. } \
  1427. P->bk = BK; \
  1428. P->fd = FD; \
  1429. FD->bk = BK->fd = P; \
  1430. } \
  1431. }
  1432. /* take a chunk off a list */
  1433. #define unlink(P, BK, FD) \
  1434. { \
  1435. BK = P->bk; \
  1436. FD = P->fd; \
  1437. FD->bk = BK; \
  1438. BK->fd = FD; \
  1439. } \
  1440. /* Place p as the last remainder */
  1441. #define link_last_remainder(P) \
  1442. { \
  1443. last_remainder->fd = last_remainder->bk = P; \
  1444. P->fd = P->bk = last_remainder; \
  1445. }
  1446. /* Clear the last_remainder bin */
  1447. #define clear_last_remainder \
  1448. (last_remainder->fd = last_remainder->bk = last_remainder)
  1449. /* Routines dealing with mmap(). */
  1450. #if HAVE_MMAP
  1451. #if __STD_C
  1452. static mchunkptr mmap_chunk(size_t size)
  1453. #else
  1454. static mchunkptr mmap_chunk(size) size_t size;
  1455. #endif
  1456. {
  1457. size_t page_mask = malloc_getpagesize - 1;
  1458. mchunkptr p;
  1459. #ifndef MAP_ANONYMOUS
  1460. static int fd = -1;
  1461. #endif
  1462. if(n_mmaps >= n_mmaps_max) return 0; /* too many regions */
  1463. /* For mmapped chunks, the overhead is one SIZE_SZ unit larger, because
  1464. * there is no following chunk whose prev_size field could be used.
  1465. */
  1466. size = (size + SIZE_SZ + page_mask) & ~page_mask;
  1467. #ifdef MAP_ANONYMOUS
  1468. p = (mchunkptr)mmap(0, size, PROT_READ|PROT_WRITE,
  1469. MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  1470. #else /* !MAP_ANONYMOUS */
  1471. if (fd < 0)
  1472. {
  1473. fd = open("/dev/zero", O_RDWR);
  1474. if(fd < 0) return 0;
  1475. }
  1476. p = (mchunkptr)mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
  1477. #endif
  1478. if(p == (mchunkptr)-1) return 0;
  1479. n_mmaps++;
  1480. if (n_mmaps > max_n_mmaps) max_n_mmaps = n_mmaps;
  1481. /* We demand that eight bytes into a page must be 8-byte aligned. */
  1482. assert(aligned_OK(chunk2mem(p)));
  1483. /* The offset to the start of the mmapped region is stored
  1484. * in the prev_size field of the chunk; normally it is zero,
  1485. * but that can be changed in memalign().
  1486. */
  1487. p->prev_size = 0;
  1488. set_head(p, size|IS_MMAPPED);
  1489. mmapped_mem += size;
  1490. if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
  1491. max_mmapped_mem = mmapped_mem;
  1492. if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
  1493. max_total_mem = mmapped_mem + sbrked_mem;
  1494. return p;
  1495. }
  1496. #if __STD_C
  1497. static void munmap_chunk(mchunkptr p)
  1498. #else
  1499. static void munmap_chunk(p) mchunkptr p;
  1500. #endif
  1501. {
  1502. INTERNAL_SIZE_T size = chunksize(p);
  1503. int ret;
  1504. assert (chunk_is_mmapped(p));
  1505. assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
  1506. assert((n_mmaps > 0));
  1507. assert(((p->prev_size + size) & (malloc_getpagesize-1)) == 0);
  1508. n_mmaps--;
  1509. mmapped_mem -= (size + p->prev_size);
  1510. ret = munmap((char *)p - p->prev_size, size + p->prev_size);
  1511. /* munmap returns non-zero on failure */
  1512. assert(ret == 0);
  1513. }
  1514. #if HAVE_MREMAP
  1515. #if __STD_C
  1516. static mchunkptr mremap_chunk(mchunkptr p, size_t new_size)
  1517. #else
  1518. static mchunkptr mremap_chunk(p, new_size) mchunkptr p; size_t new_size;
  1519. #endif
  1520. {
  1521. size_t page_mask = malloc_getpagesize - 1;
  1522. INTERNAL_SIZE_T offset = p->prev_size;
  1523. INTERNAL_SIZE_T size = chunksize(p);
  1524. char *cp;
  1525. assert (chunk_is_mmapped(p));
  1526. assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
  1527. assert((n_mmaps > 0));
  1528. assert(((size + offset) & (malloc_getpagesize-1)) == 0);
  1529. /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
  1530. new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask;
  1531. cp = (char *)mremap((char *)p - offset, size + offset, new_size, 1);
  1532. if (cp == (char *)-1) return 0;
  1533. p = (mchunkptr)(cp + offset);
  1534. assert(aligned_OK(chunk2mem(p)));
  1535. assert((p->prev_size == offset));
  1536. set_head(p, (new_size - offset)|IS_MMAPPED);
  1537. mmapped_mem -= size + offset;
  1538. mmapped_mem += new_size;
  1539. if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
  1540. max_mmapped_mem = mmapped_mem;
  1541. if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
  1542. max_total_mem = mmapped_mem + sbrked_mem;
  1543. return p;
  1544. }
  1545. #endif /* HAVE_MREMAP */
  1546. #endif /* HAVE_MMAP */
  1547. /*
  1548. Extend the top-most chunk by obtaining memory from system.
  1549. Main interface to sbrk (but see also malloc_trim).
  1550. */
  1551. #if __STD_C
  1552. static void malloc_extend_top(INTERNAL_SIZE_T nb)
  1553. #else
  1554. static void malloc_extend_top(nb) INTERNAL_SIZE_T nb;
  1555. #endif
  1556. {
  1557. char* brk; /* return value from sbrk */
  1558. INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of sbrked space */
  1559. INTERNAL_SIZE_T correction; /* bytes for 2nd sbrk call */
  1560. char* new_brk; /* return of 2nd sbrk call */
  1561. INTERNAL_SIZE_T top_size; /* new size of top chunk */
  1562. mchunkptr old_top = top; /* Record state of old top */
  1563. INTERNAL_SIZE_T old_top_size = chunksize(old_top);
  1564. char* old_end = (char*)(chunk_at_offset(old_top, old_top_size));
  1565. /* Pad request with top_pad plus minimal overhead */
  1566. INTERNAL_SIZE_T sbrk_size = nb + top_pad + MINSIZE;
  1567. unsigned long pagesz = malloc_getpagesize;
  1568. /* If not the first time through, round to preserve page boundary */
  1569. /* Otherwise, we need to correct to a page size below anyway. */
  1570. /* (We also correct below if an intervening foreign sbrk call.) */
  1571. if (sbrk_base != (char*)(-1))
  1572. sbrk_size = (sbrk_size + (pagesz - 1)) & ~(pagesz - 1);
  1573. brk = (char*)(MORECORE (sbrk_size));
  1574. /* Fail if sbrk failed or if a foreign sbrk call killed our space */
  1575. if (brk == (char*)(MORECORE_FAILURE) ||
  1576. (brk < old_end && old_top != initial_top))
  1577. return;
  1578. sbrked_mem += sbrk_size;
  1579. if (brk == old_end) /* can just add bytes to current top */
  1580. {
  1581. top_size = sbrk_size + old_top_size;
  1582. set_head(top, top_size | PREV_INUSE);
  1583. }
  1584. else
  1585. {
  1586. if (sbrk_base == (char*)(-1)) /* First time through. Record base */
  1587. sbrk_base = brk;
  1588. else /* Someone else called sbrk(). Count those bytes as sbrked_mem. */
  1589. sbrked_mem += brk - (char*)old_end;
  1590. /* Guarantee alignment of first new chunk made from this space */
  1591. front_misalign = (unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK;
  1592. if (front_misalign > 0)
  1593. {
  1594. correction = (MALLOC_ALIGNMENT) - front_misalign;
  1595. brk += correction;
  1596. }
  1597. else
  1598. correction = 0;
  1599. /* Guarantee the next brk will be at a page boundary */
  1600. correction += ((((unsigned long)(brk + sbrk_size))+(pagesz-1)) &
  1601. ~(pagesz - 1)) - ((unsigned long)(brk + sbrk_size));
  1602. /* Allocate correction */
  1603. new_brk = (char*)(MORECORE (correction));
  1604. if (new_brk == (char*)(MORECORE_FAILURE)) return;
  1605. sbrked_mem += correction;
  1606. top = (mchunkptr)brk;
  1607. top_size = new_brk - brk + correction;
  1608. set_head(top, top_size | PREV_INUSE);
  1609. if (old_top != initial_top)
  1610. {
  1611. /* There must have been an intervening foreign sbrk call. */
  1612. /* A double fencepost is necessary to prevent consolidation */
  1613. /* If not enough space to do this, then user did something very wrong */
  1614. if (old_top_size < MINSIZE)
  1615. {
  1616. set_head(top, PREV_INUSE); /* will force null return from malloc */
  1617. return;
  1618. }
  1619. /* Also keep size a multiple of MALLOC_ALIGNMENT */
  1620. old_top_size = (old_top_size - 3*SIZE_SZ) & ~MALLOC_ALIGN_MASK;
  1621. set_head_size(old_top, old_top_size);
  1622. chunk_at_offset(old_top, old_top_size )->size =
  1623. SIZE_SZ|PREV_INUSE;
  1624. chunk_at_offset(old_top, old_top_size + SIZE_SZ)->size =
  1625. SIZE_SZ|PREV_INUSE;
  1626. /* If possible, release the rest. */
  1627. if (old_top_size >= MINSIZE)
  1628. fREe(chunk2mem(old_top));
  1629. }
  1630. }
  1631. if ((unsigned long)sbrked_mem > (unsigned long)max_sbrked_mem)
  1632. max_sbrked_mem = sbrked_mem;
  1633. if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
  1634. max_total_mem = mmapped_mem + sbrked_mem;
  1635. /* We always land on a page boundary */
  1636. assert(((unsigned long)((char*)top + top_size) & (pagesz - 1)) == 0);
  1637. }
  1638. /* Main public routines */
  1639. /*
  1640. Malloc Algorthim:
  1641. The requested size is first converted into a usable form, `nb'.
  1642. This currently means to add 4 bytes overhead plus possibly more to
  1643. obtain 8-byte alignment and/or to obtain a size of at least
  1644. MINSIZE (currently 16 bytes), the smallest allocatable size.
  1645. (All fits are considered `exact' if they are within MINSIZE bytes.)
  1646. From there, the first successful of the following steps is taken:
  1647. 1. The bin corresponding to the request size is scanned, and if
  1648. a chunk of exactly the right size is found, it is taken.
  1649. 2. The most recently remaindered chunk is used if it is big
  1650. enough. This is a form of (roving) first fit, used only in
  1651. the absence of exact fits. Runs of consecutive requests use
  1652. the remainder of the chunk used for the previous such request
  1653. whenever possible. This limited use of a first-fit style
  1654. allocation strategy tends to give contiguous chunks
  1655. coextensive lifetimes, which improves locality and can reduce
  1656. fragmentation in the long run.
  1657. 3. Other bins are scanned in increasing size order, using a
  1658. chunk big enough to fulfill the request, and splitting off
  1659. any remainder. This search is strictly by best-fit; i.e.,
  1660. the smallest (with ties going to approximately the least
  1661. recently used) chunk that fits is selected.
  1662. 4. If large enough, the chunk bordering the end of memory
  1663. (`top') is split off. (This use of `top' is in accord with
  1664. the best-fit search rule. In effect, `top' is treated as
  1665. larger (and thus less well fitting) than any other available
  1666. chunk since it can be extended to be as large as necessary
  1667. (up to system limitations).
  1668. 5. If the request size meets the mmap threshold and the
  1669. system supports mmap, and there are few enough currently
  1670. allocated mmapped regions, and a call to mmap succeeds,
  1671. the request is allocated via direct memory mapping.
  1672. 6. Otherwise, the top of memory is extended by
  1673. obtaining more space from the system (normally using sbrk,
  1674. but definable to anything else via the MORECORE macro).
  1675. Memory is gathered from the system (in system page-sized
  1676. units) in a way that allows chunks obtained across different
  1677. sbrk calls to be consolidated, but does not require
  1678. contiguous memory. Thus, it should be safe to intersperse
  1679. mallocs with other sbrk calls.
  1680. All allocations are made from the the `lowest' part of any found
  1681. chunk. (The implementation invariant is that prev_inuse is
  1682. always true of any allocated chunk; i.e., that each allocated
  1683. chunk borders either a previously allocated and still in-use chunk,
  1684. or the base of its memory arena.)
  1685. */
  1686. #if __STD_C
  1687. Void_t* mALLOc(size_t bytes)
  1688. #else
  1689. Void_t* mALLOc(bytes) size_t bytes;
  1690. #endif
  1691. {
  1692. mchunkptr victim; /* inspected/selected chunk */
  1693. INTERNAL_SIZE_T victim_size; /* its size */
  1694. int idx; /* index for bin traversal */
  1695. mbinptr bin; /* associated bin */
  1696. mchunkptr remainder; /* remainder from a split */
  1697. long remainder_size; /* its size */
  1698. int remainder_index; /* its bin index */
  1699. unsigned long block; /* block traverser bit */
  1700. int startidx; /* first bin of a traversed block */
  1701. mchunkptr fwd; /* misc temp for linking */
  1702. mchunkptr bck; /* misc temp for linking */
  1703. mbinptr q; /* misc temp */
  1704. INTERNAL_SIZE_T nb;
  1705. /* check if mem_malloc_init() was run */
  1706. if ((mem_malloc_start == 0) && (mem_malloc_end == 0)) {
  1707. /* not initialized yet */
  1708. return NULL;
  1709. }
  1710. if ((long)bytes < 0) return NULL;
  1711. nb = request2size(bytes); /* padded request size; */
  1712. /* Check for exact match in a bin */
  1713. if (is_small_request(nb)) /* Faster version for small requests */
  1714. {
  1715. idx = smallbin_index(nb);
  1716. /* No traversal or size check necessary for small bins. */
  1717. q = bin_at(idx);
  1718. victim = last(q);
  1719. /* Also scan the next one, since it would have a remainder < MINSIZE */
  1720. if (victim == q)
  1721. {
  1722. q = next_bin(q);
  1723. victim = last(q);
  1724. }
  1725. if (victim != q)
  1726. {
  1727. victim_size = chunksize(victim);
  1728. unlink(victim, bck, fwd);
  1729. set_inuse_bit_at_offset(victim, victim_size);
  1730. check_malloced_chunk(victim, nb);
  1731. return chunk2mem(victim);
  1732. }
  1733. idx += 2; /* Set for bin scan below. We've already scanned 2 bins. */
  1734. }
  1735. else
  1736. {
  1737. idx = bin_index(nb);
  1738. bin = bin_at(idx);
  1739. for (victim = last(bin); victim != bin; victim = victim->bk)
  1740. {
  1741. victim_size = chunksize(victim);
  1742. remainder_size = victim_size - nb;
  1743. if (remainder_size >= (long)MINSIZE) /* too big */
  1744. {
  1745. --idx; /* adjust to rescan below after checking last remainder */
  1746. break;
  1747. }
  1748. else if (remainder_size >= 0) /* exact fit */
  1749. {
  1750. unlink(victim, bck, fwd);
  1751. set_inuse_bit_at_offset(victim, victim_size);
  1752. check_malloced_chunk(victim, nb);
  1753. return chunk2mem(victim);
  1754. }
  1755. }
  1756. ++idx;
  1757. }
  1758. /* Try to use the last split-off remainder */
  1759. if ( (victim = last_remainder->fd) != last_remainder)
  1760. {
  1761. victim_size = chunksize(victim);
  1762. remainder_size = victim_size - nb;
  1763. if (remainder_size >= (long)MINSIZE) /* re-split */
  1764. {
  1765. remainder = chunk_at_offset(victim, nb);
  1766. set_head(victim, nb | PREV_INUSE);
  1767. link_last_remainder(remainder);
  1768. set_head(remainder, remainder_size | PREV_INUSE);
  1769. set_foot(remainder, remainder_size);
  1770. check_malloced_chunk(victim, nb);
  1771. return chunk2mem(victim);
  1772. }
  1773. clear_last_remainder;
  1774. if (remainder_size >= 0) /* exhaust */
  1775. {
  1776. set_inuse_bit_at_offset(victim, victim_size);
  1777. check_malloced_chunk(victim, nb);
  1778. return chunk2mem(victim);
  1779. }
  1780. /* Else place in bin */
  1781. frontlink(victim, victim_size, remainder_index, bck, fwd);
  1782. }
  1783. /*
  1784. If there are any possibly nonempty big-enough blocks,
  1785. search for best fitting chunk by scanning bins in blockwidth units.
  1786. */
  1787. if ( (block = idx2binblock(idx)) <= binblocks_r)
  1788. {
  1789. /* Get to the first marked block */
  1790. if ( (block & binblocks_r) == 0)
  1791. {
  1792. /* force to an even block boundary */
  1793. idx = (idx & ~(BINBLOCKWIDTH - 1)) + BINBLOCKWIDTH;
  1794. block <<= 1;
  1795. while ((block & binblocks_r) == 0)
  1796. {
  1797. idx += BINBLOCKWIDTH;
  1798. block <<= 1;
  1799. }
  1800. }
  1801. /* For each possibly nonempty block ... */
  1802. for (;;)
  1803. {
  1804. startidx = idx; /* (track incomplete blocks) */
  1805. q = bin = bin_at(idx);
  1806. /* For each bin in this block ... */
  1807. do
  1808. {
  1809. /* Find and use first big enough chunk ... */
  1810. for (victim = last(bin); victim != bin; victim = victim->bk)
  1811. {
  1812. victim_size = chunksize(victim);
  1813. remainder_size = victim_size - nb;
  1814. if (remainder_size >= (long)MINSIZE) /* split */
  1815. {
  1816. remainder = chunk_at_offset(victim, nb);
  1817. set_head(victim, nb | PREV_INUSE);
  1818. unlink(victim, bck, fwd);
  1819. link_last_remainder(remainder);
  1820. set_head(remainder, remainder_size | PREV_INUSE);
  1821. set_foot(remainder, remainder_size);
  1822. check_malloced_chunk(victim, nb);
  1823. return chunk2mem(victim);
  1824. }
  1825. else if (remainder_size >= 0) /* take */
  1826. {
  1827. set_inuse_bit_at_offset(victim, victim_size);
  1828. unlink(victim, bck, fwd);
  1829. check_malloced_chunk(victim, nb);
  1830. return chunk2mem(victim);
  1831. }
  1832. }
  1833. bin = next_bin(bin);
  1834. } while ((++idx & (BINBLOCKWIDTH - 1)) != 0);
  1835. /* Clear out the block bit. */
  1836. do /* Possibly backtrack to try to clear a partial block */
  1837. {
  1838. if ((startidx & (BINBLOCKWIDTH - 1)) == 0)
  1839. {
  1840. av_[1] = (mbinptr)(binblocks_r & ~block);
  1841. break;
  1842. }
  1843. --startidx;
  1844. q = prev_bin(q);
  1845. } while (first(q) == q);
  1846. /* Get to the next possibly nonempty block */
  1847. if ( (block <<= 1) <= binblocks_r && (block != 0) )
  1848. {
  1849. while ((block & binblocks_r) == 0)
  1850. {
  1851. idx += BINBLOCKWIDTH;
  1852. block <<= 1;
  1853. }
  1854. }
  1855. else
  1856. break;
  1857. }
  1858. }
  1859. /* Try to use top chunk */
  1860. /* Require that there be a remainder, ensuring top always exists */
  1861. if ( (remainder_size = chunksize(top) - nb) < (long)MINSIZE)
  1862. {
  1863. #if HAVE_MMAP
  1864. /* If big and would otherwise need to extend, try to use mmap instead */
  1865. if ((unsigned long)nb >= (unsigned long)mmap_threshold &&
  1866. (victim = mmap_chunk(nb)) != 0)
  1867. return chunk2mem(victim);
  1868. #endif
  1869. /* Try to extend */
  1870. malloc_extend_top(nb);
  1871. if ( (remainder_size = chunksize(top) - nb) < (long)MINSIZE)
  1872. return NULL; /* propagate failure */
  1873. }
  1874. victim = top;
  1875. set_head(victim, nb | PREV_INUSE);
  1876. top = chunk_at_offset(victim, nb);
  1877. set_head(top, remainder_size | PREV_INUSE);
  1878. check_malloced_chunk(victim, nb);
  1879. return chunk2mem(victim);
  1880. }
  1881. /*
  1882. free() algorithm :
  1883. cases:
  1884. 1. free(0) has no effect.
  1885. 2. If the chunk was allocated via mmap, it is release via munmap().
  1886. 3. If a returned chunk borders the current high end of memory,
  1887. it is consolidated into the top, and if the total unused
  1888. topmost memory exceeds the trim threshold, malloc_trim is
  1889. called.
  1890. 4. Other chunks are consolidated as they arrive, and
  1891. placed in corresponding bins. (This includes the case of
  1892. consolidating with the current `last_remainder').
  1893. */
  1894. #if __STD_C
  1895. void fREe(Void_t* mem)
  1896. #else
  1897. void fREe(mem) Void_t* mem;
  1898. #endif
  1899. {
  1900. mchunkptr p; /* chunk corresponding to mem */
  1901. INTERNAL_SIZE_T hd; /* its head field */
  1902. INTERNAL_SIZE_T sz; /* its size */
  1903. int idx; /* its bin index */
  1904. mchunkptr next; /* next contiguous chunk */
  1905. INTERNAL_SIZE_T nextsz; /* its size */
  1906. INTERNAL_SIZE_T prevsz; /* size of previous contiguous chunk */
  1907. mchunkptr bck; /* misc temp for linking */
  1908. mchunkptr fwd; /* misc temp for linking */
  1909. int islr; /* track whether merging with last_remainder */
  1910. if (mem == NULL) /* free(0) has no effect */
  1911. return;
  1912. p = mem2chunk(mem);
  1913. hd = p->size;
  1914. #if HAVE_MMAP
  1915. if (hd & IS_MMAPPED) /* release mmapped memory. */
  1916. {
  1917. munmap_chunk(p);
  1918. return;
  1919. }
  1920. #endif
  1921. check_inuse_chunk(p);
  1922. sz = hd & ~PREV_INUSE;
  1923. next = chunk_at_offset(p, sz);
  1924. nextsz = chunksize(next);
  1925. if (next == top) /* merge with top */
  1926. {
  1927. sz += nextsz;
  1928. if (!(hd & PREV_INUSE)) /* consolidate backward */
  1929. {
  1930. prevsz = p->prev_size;
  1931. p = chunk_at_offset(p, -((long) prevsz));
  1932. sz += prevsz;
  1933. unlink(p, bck, fwd);
  1934. }
  1935. set_head(p, sz | PREV_INUSE);
  1936. top = p;
  1937. if ((unsigned long)(sz) >= (unsigned long)trim_threshold)
  1938. malloc_trim(top_pad);
  1939. return;
  1940. }
  1941. set_head(next, nextsz); /* clear inuse bit */
  1942. islr = 0;
  1943. if (!(hd & PREV_INUSE)) /* consolidate backward */
  1944. {
  1945. prevsz = p->prev_size;
  1946. p = chunk_at_offset(p, -((long) prevsz));
  1947. sz += prevsz;
  1948. if (p->fd == last_remainder) /* keep as last_remainder */
  1949. islr = 1;
  1950. else
  1951. unlink(p, bck, fwd);
  1952. }
  1953. if (!(inuse_bit_at_offset(next, nextsz))) /* consolidate forward */
  1954. {
  1955. sz += nextsz;
  1956. if (!islr && next->fd == last_remainder) /* re-insert last_remainder */
  1957. {
  1958. islr = 1;
  1959. link_last_remainder(p);
  1960. }
  1961. else
  1962. unlink(next, bck, fwd);
  1963. }
  1964. set_head(p, sz | PREV_INUSE);
  1965. set_foot(p, sz);
  1966. if (!islr)
  1967. frontlink(p, sz, idx, bck, fwd);
  1968. }
  1969. /*
  1970. Realloc algorithm:
  1971. Chunks that were obtained via mmap cannot be extended or shrunk
  1972. unless HAVE_MREMAP is defined, in which case mremap is used.
  1973. Otherwise, if their reallocation is for additional space, they are
  1974. copied. If for less, they are just left alone.
  1975. Otherwise, if the reallocation is for additional space, and the
  1976. chunk can be extended, it is, else a malloc-copy-free sequence is
  1977. taken. There are several different ways that a chunk could be
  1978. extended. All are tried:
  1979. * Extending forward into following adjacent free chunk.
  1980. * Shifting backwards, joining preceding adjacent space
  1981. * Both shifting backwards and extending forward.
  1982. * Extending into newly sbrked space
  1983. Unless the #define REALLOC_ZERO_BYTES_FREES is set, realloc with a
  1984. size argument of zero (re)allocates a minimum-sized chunk.
  1985. If the reallocation is for less space, and the new request is for
  1986. a `small' (<512 bytes) size, then the newly unused space is lopped
  1987. off and freed.
  1988. The old unix realloc convention of allowing the last-free'd chunk
  1989. to be used as an argument to realloc is no longer supported.
  1990. I don't know of any programs still relying on this feature,
  1991. and allowing it would also allow too many other incorrect
  1992. usages of realloc to be sensible.
  1993. */
  1994. #if __STD_C
  1995. Void_t* rEALLOc(Void_t* oldmem, size_t bytes)
  1996. #else
  1997. Void_t* rEALLOc(oldmem, bytes) Void_t* oldmem; size_t bytes;
  1998. #endif
  1999. {
  2000. INTERNAL_SIZE_T nb; /* padded request size */
  2001. mchunkptr oldp; /* chunk corresponding to oldmem */
  2002. INTERNAL_SIZE_T oldsize; /* its size */
  2003. mchunkptr newp; /* chunk to return */
  2004. INTERNAL_SIZE_T newsize; /* its size */
  2005. Void_t* newmem; /* corresponding user mem */
  2006. mchunkptr next; /* next contiguous chunk after oldp */
  2007. INTERNAL_SIZE_T nextsize; /* its size */
  2008. mchunkptr prev; /* previous contiguous chunk before oldp */
  2009. INTERNAL_SIZE_T prevsize; /* its size */
  2010. mchunkptr remainder; /* holds split off extra space from newp */
  2011. INTERNAL_SIZE_T remainder_size; /* its size */
  2012. mchunkptr bck; /* misc temp for linking */
  2013. mchunkptr fwd; /* misc temp for linking */
  2014. #ifdef REALLOC_ZERO_BYTES_FREES
  2015. if (bytes == 0) { fREe(oldmem); return 0; }
  2016. #endif
  2017. if ((long)bytes < 0) return NULL;
  2018. /* realloc of null is supposed to be same as malloc */
  2019. if (oldmem == NULL) return mALLOc(bytes);
  2020. newp = oldp = mem2chunk(oldmem);
  2021. newsize = oldsize = chunksize(oldp);
  2022. nb = request2size(bytes);
  2023. #if HAVE_MMAP
  2024. if (chunk_is_mmapped(oldp))
  2025. {
  2026. #if HAVE_MREMAP
  2027. newp = mremap_chunk(oldp, nb);
  2028. if(newp) return chunk2mem(newp);
  2029. #endif
  2030. /* Note the extra SIZE_SZ overhead. */
  2031. if(oldsize - SIZE_SZ >= nb) return oldmem; /* do nothing */
  2032. /* Must alloc, copy, free. */
  2033. newmem = mALLOc(bytes);
  2034. if (newmem == 0) return 0; /* propagate failure */
  2035. MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ);
  2036. munmap_chunk(oldp);
  2037. return newmem;
  2038. }
  2039. #endif
  2040. check_inuse_chunk(oldp);
  2041. if ((long)(oldsize) < (long)(nb))
  2042. {
  2043. /* Try expanding forward */
  2044. next = chunk_at_offset(oldp, oldsize);
  2045. if (next == top || !inuse(next))
  2046. {
  2047. nextsize = chunksize(next);
  2048. /* Forward into top only if a remainder */
  2049. if (next == top)
  2050. {
  2051. if ((long)(nextsize + newsize) >= (long)(nb + MINSIZE))
  2052. {
  2053. newsize += nextsize;
  2054. top = chunk_at_offset(oldp, nb);
  2055. set_head(top, (newsize - nb) | PREV_INUSE);
  2056. set_head_size(oldp, nb);
  2057. return chunk2mem(oldp);
  2058. }
  2059. }
  2060. /* Forward into next chunk */
  2061. else if (((long)(nextsize + newsize) >= (long)(nb)))
  2062. {
  2063. unlink(next, bck, fwd);
  2064. newsize += nextsize;
  2065. goto split;
  2066. }
  2067. }
  2068. else
  2069. {
  2070. next = NULL;
  2071. nextsize = 0;
  2072. }
  2073. /* Try shifting backwards. */
  2074. if (!prev_inuse(oldp))
  2075. {
  2076. prev = prev_chunk(oldp);
  2077. prevsize = chunksize(prev);
  2078. /* try forward + backward first to save a later consolidation */
  2079. if (next != NULL)
  2080. {
  2081. /* into top */
  2082. if (next == top)
  2083. {
  2084. if ((long)(nextsize + prevsize + newsize) >= (long)(nb + MINSIZE))
  2085. {
  2086. unlink(prev, bck, fwd);
  2087. newp = prev;
  2088. newsize += prevsize + nextsize;
  2089. newmem = chunk2mem(newp);
  2090. MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
  2091. top = chunk_at_offset(newp, nb);
  2092. set_head(top, (newsize - nb) | PREV_INUSE);
  2093. set_head_size(newp, nb);
  2094. return newmem;
  2095. }
  2096. }
  2097. /* into next chunk */
  2098. else if (((long)(nextsize + prevsize + newsize) >= (long)(nb)))
  2099. {
  2100. unlink(next, bck, fwd);
  2101. unlink(prev, bck, fwd);
  2102. newp = prev;
  2103. newsize += nextsize + prevsize;
  2104. newmem = chunk2mem(newp);
  2105. MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
  2106. goto split;
  2107. }
  2108. }
  2109. /* backward only */
  2110. if (prev != NULL && (long)(prevsize + newsize) >= (long)nb)
  2111. {
  2112. unlink(prev, bck, fwd);
  2113. newp = prev;
  2114. newsize += prevsize;
  2115. newmem = chunk2mem(newp);
  2116. MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
  2117. goto split;
  2118. }
  2119. }
  2120. /* Must allocate */
  2121. newmem = mALLOc (bytes);
  2122. if (newmem == NULL) /* propagate failure */
  2123. return NULL;
  2124. /* Avoid copy if newp is next chunk after oldp. */
  2125. /* (This can only happen when new chunk is sbrk'ed.) */
  2126. if ( (newp = mem2chunk(newmem)) == next_chunk(oldp))
  2127. {
  2128. newsize += chunksize(newp);
  2129. newp = oldp;
  2130. goto split;
  2131. }
  2132. /* Otherwise copy, free, and exit */
  2133. MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
  2134. fREe(oldmem);
  2135. return newmem;
  2136. }
  2137. split: /* split off extra room in old or expanded chunk */
  2138. if (newsize - nb >= MINSIZE) /* split off remainder */
  2139. {
  2140. remainder = chunk_at_offset(newp, nb);
  2141. remainder_size = newsize - nb;
  2142. set_head_size(newp, nb);
  2143. set_head(remainder, remainder_size | PREV_INUSE);
  2144. set_inuse_bit_at_offset(remainder, remainder_size);
  2145. fREe(chunk2mem(remainder)); /* let free() deal with it */
  2146. }
  2147. else
  2148. {
  2149. set_head_size(newp, newsize);
  2150. set_inuse_bit_at_offset(newp, newsize);
  2151. }
  2152. check_inuse_chunk(newp);
  2153. return chunk2mem(newp);
  2154. }
  2155. /*
  2156. memalign algorithm:
  2157. memalign requests more than enough space from malloc, finds a spot
  2158. within that chunk that meets the alignment request, and then
  2159. possibly frees the leading and trailing space.
  2160. The alignment argument must be a power of two. This property is not
  2161. checked by memalign, so misuse may result in random runtime errors.
  2162. 8-byte alignment is guaranteed by normal malloc calls, so don't
  2163. bother calling memalign with an argument of 8 or less.
  2164. Overreliance on memalign is a sure way to fragment space.
  2165. */
  2166. #if __STD_C
  2167. Void_t* mEMALIGn(size_t alignment, size_t bytes)
  2168. #else
  2169. Void_t* mEMALIGn(alignment, bytes) size_t alignment; size_t bytes;
  2170. #endif
  2171. {
  2172. INTERNAL_SIZE_T nb; /* padded request size */
  2173. char* m; /* memory returned by malloc call */
  2174. mchunkptr p; /* corresponding chunk */
  2175. char* brk; /* alignment point within p */
  2176. mchunkptr newp; /* chunk to return */
  2177. INTERNAL_SIZE_T newsize; /* its size */
  2178. INTERNAL_SIZE_T leadsize; /* leading space befor alignment point */
  2179. mchunkptr remainder; /* spare room at end to split off */
  2180. long remainder_size; /* its size */
  2181. if ((long)bytes < 0) return NULL;
  2182. /* If need less alignment than we give anyway, just relay to malloc */
  2183. if (alignment <= MALLOC_ALIGNMENT) return mALLOc(bytes);
  2184. /* Otherwise, ensure that it is at least a minimum chunk size */
  2185. if (alignment < MINSIZE) alignment = MINSIZE;
  2186. /* Call malloc with worst case padding to hit alignment. */
  2187. nb = request2size(bytes);
  2188. m = (char*)(mALLOc(nb + alignment + MINSIZE));
  2189. if (m == NULL) return NULL; /* propagate failure */
  2190. p = mem2chunk(m);
  2191. if ((((unsigned long)(m)) % alignment) == 0) /* aligned */
  2192. {
  2193. #if HAVE_MMAP
  2194. if(chunk_is_mmapped(p))
  2195. return chunk2mem(p); /* nothing more to do */
  2196. #endif
  2197. }
  2198. else /* misaligned */
  2199. {
  2200. /*
  2201. Find an aligned spot inside chunk.
  2202. Since we need to give back leading space in a chunk of at
  2203. least MINSIZE, if the first calculation places us at
  2204. a spot with less than MINSIZE leader, we can move to the
  2205. next aligned spot -- we've allocated enough total room so that
  2206. this is always possible.
  2207. */
  2208. brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) & -((signed) alignment));
  2209. if ((long)(brk - (char*)(p)) < MINSIZE) brk = brk + alignment;
  2210. newp = (mchunkptr)brk;
  2211. leadsize = brk - (char*)(p);
  2212. newsize = chunksize(p) - leadsize;
  2213. #if HAVE_MMAP
  2214. if(chunk_is_mmapped(p))
  2215. {
  2216. newp->prev_size = p->prev_size + leadsize;
  2217. set_head(newp, newsize|IS_MMAPPED);
  2218. return chunk2mem(newp);
  2219. }
  2220. #endif
  2221. /* give back leader, use the rest */
  2222. set_head(newp, newsize | PREV_INUSE);
  2223. set_inuse_bit_at_offset(newp, newsize);
  2224. set_head_size(p, leadsize);
  2225. fREe(chunk2mem(p));
  2226. p = newp;
  2227. assert (newsize >= nb && (((unsigned long)(chunk2mem(p))) % alignment) == 0);
  2228. }
  2229. /* Also give back spare room at the end */
  2230. remainder_size = chunksize(p) - nb;
  2231. if (remainder_size >= (long)MINSIZE)
  2232. {
  2233. remainder = chunk_at_offset(p, nb);
  2234. set_head(remainder, remainder_size | PREV_INUSE);
  2235. set_head_size(p, nb);
  2236. fREe(chunk2mem(remainder));
  2237. }
  2238. check_inuse_chunk(p);
  2239. return chunk2mem(p);
  2240. }
  2241. /*
  2242. valloc just invokes memalign with alignment argument equal
  2243. to the page size of the system (or as near to this as can
  2244. be figured out from all the includes/defines above.)
  2245. */
  2246. #if __STD_C
  2247. Void_t* vALLOc(size_t bytes)
  2248. #else
  2249. Void_t* vALLOc(bytes) size_t bytes;
  2250. #endif
  2251. {
  2252. return mEMALIGn (malloc_getpagesize, bytes);
  2253. }
  2254. /*
  2255. pvalloc just invokes valloc for the nearest pagesize
  2256. that will accommodate request
  2257. */
  2258. #if __STD_C
  2259. Void_t* pvALLOc(size_t bytes)
  2260. #else
  2261. Void_t* pvALLOc(bytes) size_t bytes;
  2262. #endif
  2263. {
  2264. size_t pagesize = malloc_getpagesize;
  2265. return mEMALIGn (pagesize, (bytes + pagesize - 1) & ~(pagesize - 1));
  2266. }
  2267. /*
  2268. calloc calls malloc, then zeroes out the allocated chunk.
  2269. */
  2270. #if __STD_C
  2271. Void_t* cALLOc(size_t n, size_t elem_size)
  2272. #else
  2273. Void_t* cALLOc(n, elem_size) size_t n; size_t elem_size;
  2274. #endif
  2275. {
  2276. mchunkptr p;
  2277. INTERNAL_SIZE_T csz;
  2278. INTERNAL_SIZE_T sz = n * elem_size;
  2279. /* check if expand_top called, in which case don't need to clear */
  2280. #if MORECORE_CLEARS
  2281. mchunkptr oldtop = top;
  2282. INTERNAL_SIZE_T oldtopsize = chunksize(top);
  2283. #endif
  2284. Void_t* mem = mALLOc (sz);
  2285. if ((long)n < 0) return NULL;
  2286. if (mem == NULL)
  2287. return NULL;
  2288. else
  2289. {
  2290. p = mem2chunk(mem);
  2291. /* Two optional cases in which clearing not necessary */
  2292. #if HAVE_MMAP
  2293. if (chunk_is_mmapped(p)) return mem;
  2294. #endif
  2295. csz = chunksize(p);
  2296. #if MORECORE_CLEARS
  2297. if (p == oldtop && csz > oldtopsize)
  2298. {
  2299. /* clear only the bytes from non-freshly-sbrked memory */
  2300. csz = oldtopsize;
  2301. }
  2302. #endif
  2303. MALLOC_ZERO(mem, csz - SIZE_SZ);
  2304. return mem;
  2305. }
  2306. }
  2307. /*
  2308. cfree just calls free. It is needed/defined on some systems
  2309. that pair it with calloc, presumably for odd historical reasons.
  2310. */
  2311. #if !defined(INTERNAL_LINUX_C_LIB) || !defined(__ELF__)
  2312. #if __STD_C
  2313. void cfree(Void_t *mem)
  2314. #else
  2315. void cfree(mem) Void_t *mem;
  2316. #endif
  2317. {
  2318. fREe(mem);
  2319. }
  2320. #endif
  2321. /*
  2322. Malloc_trim gives memory back to the system (via negative
  2323. arguments to sbrk) if there is unused memory at the `high' end of
  2324. the malloc pool. You can call this after freeing large blocks of
  2325. memory to potentially reduce the system-level memory requirements
  2326. of a program. However, it cannot guarantee to reduce memory. Under
  2327. some allocation patterns, some large free blocks of memory will be
  2328. locked between two used chunks, so they cannot be given back to
  2329. the system.
  2330. The `pad' argument to malloc_trim represents the amount of free
  2331. trailing space to leave untrimmed. If this argument is zero,
  2332. only the minimum amount of memory to maintain internal data
  2333. structures will be left (one page or less). Non-zero arguments
  2334. can be supplied to maintain enough trailing space to service
  2335. future expected allocations without having to re-obtain memory
  2336. from the system.
  2337. Malloc_trim returns 1 if it actually released any memory, else 0.
  2338. */
  2339. #if __STD_C
  2340. int malloc_trim(size_t pad)
  2341. #else
  2342. int malloc_trim(pad) size_t pad;
  2343. #endif
  2344. {
  2345. long top_size; /* Amount of top-most memory */
  2346. long extra; /* Amount to release */
  2347. char* current_brk; /* address returned by pre-check sbrk call */
  2348. char* new_brk; /* address returned by negative sbrk call */
  2349. unsigned long pagesz = malloc_getpagesize;
  2350. top_size = chunksize(top);
  2351. extra = ((top_size - pad - MINSIZE + (pagesz-1)) / pagesz - 1) * pagesz;
  2352. if (extra < (long)pagesz) /* Not enough memory to release */
  2353. return 0;
  2354. else
  2355. {
  2356. /* Test to make sure no one else called sbrk */
  2357. current_brk = (char*)(MORECORE (0));
  2358. if (current_brk != (char*)(top) + top_size)
  2359. return 0; /* Apparently we don't own memory; must fail */
  2360. else
  2361. {
  2362. new_brk = (char*)(MORECORE (-extra));
  2363. if (new_brk == (char*)(MORECORE_FAILURE)) /* sbrk failed? */
  2364. {
  2365. /* Try to figure out what we have */
  2366. current_brk = (char*)(MORECORE (0));
  2367. top_size = current_brk - (char*)top;
  2368. if (top_size >= (long)MINSIZE) /* if not, we are very very dead! */
  2369. {
  2370. sbrked_mem = current_brk - sbrk_base;
  2371. set_head(top, top_size | PREV_INUSE);
  2372. }
  2373. check_chunk(top);
  2374. return 0;
  2375. }
  2376. else
  2377. {
  2378. /* Success. Adjust top accordingly. */
  2379. set_head(top, (top_size - extra) | PREV_INUSE);
  2380. sbrked_mem -= extra;
  2381. check_chunk(top);
  2382. return 1;
  2383. }
  2384. }
  2385. }
  2386. }
  2387. /*
  2388. malloc_usable_size:
  2389. This routine tells you how many bytes you can actually use in an
  2390. allocated chunk, which may be more than you requested (although
  2391. often not). You can use this many bytes without worrying about
  2392. overwriting other allocated objects. Not a particularly great
  2393. programming practice, but still sometimes useful.
  2394. */
  2395. #if __STD_C
  2396. size_t malloc_usable_size(Void_t* mem)
  2397. #else
  2398. size_t malloc_usable_size(mem) Void_t* mem;
  2399. #endif
  2400. {
  2401. mchunkptr p;
  2402. if (mem == NULL)
  2403. return 0;
  2404. else
  2405. {
  2406. p = mem2chunk(mem);
  2407. if(!chunk_is_mmapped(p))
  2408. {
  2409. if (!inuse(p)) return 0;
  2410. check_inuse_chunk(p);
  2411. return chunksize(p) - SIZE_SZ;
  2412. }
  2413. return chunksize(p) - 2*SIZE_SZ;
  2414. }
  2415. }
  2416. /* Utility to update current_mallinfo for malloc_stats and mallinfo() */
  2417. #ifdef DEBUG
  2418. static void malloc_update_mallinfo()
  2419. {
  2420. int i;
  2421. mbinptr b;
  2422. mchunkptr p;
  2423. #ifdef DEBUG
  2424. mchunkptr q;
  2425. #endif
  2426. INTERNAL_SIZE_T avail = chunksize(top);
  2427. int navail = ((long)(avail) >= (long)MINSIZE)? 1 : 0;
  2428. for (i = 1; i < NAV; ++i)
  2429. {
  2430. b = bin_at(i);
  2431. for (p = last(b); p != b; p = p->bk)
  2432. {
  2433. #ifdef DEBUG
  2434. check_free_chunk(p);
  2435. for (q = next_chunk(p);
  2436. q < top && inuse(q) && (long)(chunksize(q)) >= (long)MINSIZE;
  2437. q = next_chunk(q))
  2438. check_inuse_chunk(q);
  2439. #endif
  2440. avail += chunksize(p);
  2441. navail++;
  2442. }
  2443. }
  2444. current_mallinfo.ordblks = navail;
  2445. current_mallinfo.uordblks = sbrked_mem - avail;
  2446. current_mallinfo.fordblks = avail;
  2447. current_mallinfo.hblks = n_mmaps;
  2448. current_mallinfo.hblkhd = mmapped_mem;
  2449. current_mallinfo.keepcost = chunksize(top);
  2450. }
  2451. #endif /* DEBUG */
  2452. /*
  2453. malloc_stats:
  2454. Prints on the amount of space obtain from the system (both
  2455. via sbrk and mmap), the maximum amount (which may be more than
  2456. current if malloc_trim and/or munmap got called), the maximum
  2457. number of simultaneous mmap regions used, and the current number
  2458. of bytes allocated via malloc (or realloc, etc) but not yet
  2459. freed. (Note that this is the number of bytes allocated, not the
  2460. number requested. It will be larger than the number requested
  2461. because of alignment and bookkeeping overhead.)
  2462. */
  2463. #ifdef DEBUG
  2464. void malloc_stats()
  2465. {
  2466. malloc_update_mallinfo();
  2467. printf("max system bytes = %10u\n",
  2468. (unsigned int)(max_total_mem));
  2469. printf("system bytes = %10u\n",
  2470. (unsigned int)(sbrked_mem + mmapped_mem));
  2471. printf("in use bytes = %10u\n",
  2472. (unsigned int)(current_mallinfo.uordblks + mmapped_mem));
  2473. #if HAVE_MMAP
  2474. printf("max mmap regions = %10u\n",
  2475. (unsigned int)max_n_mmaps);
  2476. #endif
  2477. }
  2478. #endif /* DEBUG */
  2479. /*
  2480. mallinfo returns a copy of updated current mallinfo.
  2481. */
  2482. #ifdef DEBUG
  2483. struct mallinfo mALLINFo()
  2484. {
  2485. malloc_update_mallinfo();
  2486. return current_mallinfo;
  2487. }
  2488. #endif /* DEBUG */
  2489. /*
  2490. mallopt:
  2491. mallopt is the general SVID/XPG interface to tunable parameters.
  2492. The format is to provide a (parameter-number, parameter-value) pair.
  2493. mallopt then sets the corresponding parameter to the argument
  2494. value if it can (i.e., so long as the value is meaningful),
  2495. and returns 1 if successful else 0.
  2496. See descriptions of tunable parameters above.
  2497. */
  2498. #if __STD_C
  2499. int mALLOPt(int param_number, int value)
  2500. #else
  2501. int mALLOPt(param_number, value) int param_number; int value;
  2502. #endif
  2503. {
  2504. switch(param_number)
  2505. {
  2506. case M_TRIM_THRESHOLD:
  2507. trim_threshold = value; return 1;
  2508. case M_TOP_PAD:
  2509. top_pad = value; return 1;
  2510. case M_MMAP_THRESHOLD:
  2511. mmap_threshold = value; return 1;
  2512. case M_MMAP_MAX:
  2513. #if HAVE_MMAP
  2514. n_mmaps_max = value; return 1;
  2515. #else
  2516. if (value != 0) return 0; else n_mmaps_max = value; return 1;
  2517. #endif
  2518. default:
  2519. return 0;
  2520. }
  2521. }
  2522. /*
  2523. History:
  2524. V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee)
  2525. * return null for negative arguments
  2526. * Added Several WIN32 cleanups from Martin C. Fong <mcfong@yahoo.com>
  2527. * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
  2528. (e.g. WIN32 platforms)
  2529. * Cleanup up header file inclusion for WIN32 platforms
  2530. * Cleanup code to avoid Microsoft Visual C++ compiler complaints
  2531. * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
  2532. memory allocation routines
  2533. * Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
  2534. * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
  2535. usage of 'assert' in non-WIN32 code
  2536. * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
  2537. avoid infinite loop
  2538. * Always call 'fREe()' rather than 'free()'
  2539. V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee)
  2540. * Fixed ordering problem with boundary-stamping
  2541. V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
  2542. * Added pvalloc, as recommended by H.J. Liu
  2543. * Added 64bit pointer support mainly from Wolfram Gloger
  2544. * Added anonymously donated WIN32 sbrk emulation
  2545. * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
  2546. * malloc_extend_top: fix mask error that caused wastage after
  2547. foreign sbrks
  2548. * Add linux mremap support code from HJ Liu
  2549. V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
  2550. * Integrated most documentation with the code.
  2551. * Add support for mmap, with help from
  2552. Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
  2553. * Use last_remainder in more cases.
  2554. * Pack bins using idea from colin@nyx10.cs.du.edu
  2555. * Use ordered bins instead of best-fit threshhold
  2556. * Eliminate block-local decls to simplify tracing and debugging.
  2557. * Support another case of realloc via move into top
  2558. * Fix error occuring when initial sbrk_base not word-aligned.
  2559. * Rely on page size for units instead of SBRK_UNIT to
  2560. avoid surprises about sbrk alignment conventions.
  2561. * Add mallinfo, mallopt. Thanks to Raymond Nijssen
  2562. (raymond@es.ele.tue.nl) for the suggestion.
  2563. * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
  2564. * More precautions for cases where other routines call sbrk,
  2565. courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
  2566. * Added macros etc., allowing use in linux libc from
  2567. H.J. Lu (hjl@gnu.ai.mit.edu)
  2568. * Inverted this history list
  2569. V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
  2570. * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
  2571. * Removed all preallocation code since under current scheme
  2572. the work required to undo bad preallocations exceeds
  2573. the work saved in good cases for most test programs.
  2574. * No longer use return list or unconsolidated bins since
  2575. no scheme using them consistently outperforms those that don't
  2576. given above changes.
  2577. * Use best fit for very large chunks to prevent some worst-cases.
  2578. * Added some support for debugging
  2579. V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
  2580. * Removed footers when chunks are in use. Thanks to
  2581. Paul Wilson (wilson@cs.texas.edu) for the suggestion.
  2582. V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
  2583. * Added malloc_trim, with help from Wolfram Gloger
  2584. (wmglo@Dent.MED.Uni-Muenchen.DE).
  2585. V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
  2586. V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
  2587. * realloc: try to expand in both directions
  2588. * malloc: swap order of clean-bin strategy;
  2589. * realloc: only conditionally expand backwards
  2590. * Try not to scavenge used bins
  2591. * Use bin counts as a guide to preallocation
  2592. * Occasionally bin return list chunks in first scan
  2593. * Add a few optimizations from colin@nyx10.cs.du.edu
  2594. V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
  2595. * faster bin computation & slightly different binning
  2596. * merged all consolidations to one part of malloc proper
  2597. (eliminating old malloc_find_space & malloc_clean_bin)
  2598. * Scan 2 returns chunks (not just 1)
  2599. * Propagate failure in realloc if malloc returns 0
  2600. * Add stuff to allow compilation on non-ANSI compilers
  2601. from kpv@research.att.com
  2602. V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
  2603. * removed potential for odd address access in prev_chunk
  2604. * removed dependency on getpagesize.h
  2605. * misc cosmetics and a bit more internal documentation
  2606. * anticosmetics: mangled names in macros to evade debugger strangeness
  2607. * tested on sparc, hp-700, dec-mips, rs6000
  2608. with gcc & native cc (hp, dec only) allowing
  2609. Detlefs & Zorn comparison study (in SIGPLAN Notices.)
  2610. Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
  2611. * Based loosely on libg++-1.2X malloc. (It retains some of the overall
  2612. structure of old version, but most details differ.)
  2613. */