dlmalloc.src 100 KB

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