dlmalloc.c 101 KB

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