SDL_malloc.c 188 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2016 Sam Lantinga <[email protected]>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #if defined(__clang_analyzer__) && !defined(SDL_DISABLE_ANALYZE_MACROS)
  19. #define SDL_DISABLE_ANALYZE_MACROS 1
  20. #endif
  21. #include "../SDL_internal.h"
  22. /* This file contains portable memory management functions for SDL */
  23. #include "SDL_stdinc.h"
  24. #if defined(HAVE_MALLOC)
  25. void *SDL_malloc(size_t size)
  26. {
  27. return malloc(size);
  28. }
  29. void *SDL_calloc(size_t nmemb, size_t size)
  30. {
  31. return calloc(nmemb, size);
  32. }
  33. void *SDL_realloc(void *ptr, size_t size)
  34. {
  35. return realloc(ptr, size);
  36. }
  37. void SDL_free(void *ptr)
  38. {
  39. free(ptr);
  40. }
  41. #else /* the rest of this is a LOT of tapdancing to implement malloc. :) */
  42. #define LACKS_SYS_TYPES_H
  43. #define LACKS_STDIO_H
  44. #define LACKS_STRINGS_H
  45. #define LACKS_STRING_H
  46. #define LACKS_STDLIB_H
  47. #define ABORT
  48. #define USE_LOCKS 1
  49. /*
  50. This is a version (aka dlmalloc) of malloc/free/realloc written by
  51. Doug Lea and released to the public domain, as explained at
  52. http://creativecommons.org/licenses/publicdomain. Send questions,
  53. comments, complaints, performance data, etc to [email protected]
  54. * Version 2.8.3 Thu Sep 22 11:16:15 2005 Doug Lea (dl at gee)
  55. Note: There may be an updated version of this malloc obtainable at
  56. ftp://gee.cs.oswego.edu/pub/misc/malloc.c
  57. Check before installing!
  58. * Quickstart
  59. This library is all in one file to simplify the most common usage:
  60. ftp it, compile it (-O3), and link it into another program. All of
  61. the compile-time options default to reasonable values for use on
  62. most platforms. You might later want to step through various
  63. compile-time and dynamic tuning options.
  64. For convenience, an include file for code using this malloc is at:
  65. ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.3.h
  66. You don't really need this .h file unless you call functions not
  67. defined in your system include files. The .h file contains only the
  68. excerpts from this file needed for using this malloc on ANSI C/C++
  69. systems, so long as you haven't changed compile-time options about
  70. naming and tuning parameters. If you do, then you can create your
  71. own malloc.h that does include all settings by cutting at the point
  72. indicated below. Note that you may already by default be using a C
  73. library containing a malloc that is based on some version of this
  74. malloc (for example in linux). You might still want to use the one
  75. in this file to customize settings or to avoid overheads associated
  76. with library versions.
  77. * Vital statistics:
  78. Supported pointer/size_t representation: 4 or 8 bytes
  79. size_t MUST be an unsigned type of the same width as
  80. pointers. (If you are using an ancient system that declares
  81. size_t as a signed type, or need it to be a different width
  82. than pointers, you can use a previous release of this malloc
  83. (e.g. 2.7.2) supporting these.)
  84. Alignment: 8 bytes (default)
  85. This suffices for nearly all current machines and C compilers.
  86. However, you can define MALLOC_ALIGNMENT to be wider than this
  87. if necessary (up to 128bytes), at the expense of using more space.
  88. Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes)
  89. 8 or 16 bytes (if 8byte sizes)
  90. Each malloced chunk has a hidden word of overhead holding size
  91. and status information, and additional cross-check word
  92. if FOOTERS is defined.
  93. Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead)
  94. 8-byte ptrs: 32 bytes (including overhead)
  95. Even a request for zero bytes (i.e., malloc(0)) returns a
  96. pointer to something of the minimum allocatable size.
  97. The maximum overhead wastage (i.e., number of extra bytes
  98. allocated than were requested in malloc) is less than or equal
  99. to the minimum size, except for requests >= mmap_threshold that
  100. are serviced via mmap(), where the worst case wastage is about
  101. 32 bytes plus the remainder from a system page (the minimal
  102. mmap unit); typically 4096 or 8192 bytes.
  103. Security: static-safe; optionally more or less
  104. The "security" of malloc refers to the ability of malicious
  105. code to accentuate the effects of errors (for example, freeing
  106. space that is not currently malloc'ed or overwriting past the
  107. ends of chunks) in code that calls malloc. This malloc
  108. guarantees not to modify any memory locations below the base of
  109. heap, i.e., static variables, even in the presence of usage
  110. errors. The routines additionally detect most improper frees
  111. and reallocs. All this holds as long as the static bookkeeping
  112. for malloc itself is not corrupted by some other means. This
  113. is only one aspect of security -- these checks do not, and
  114. cannot, detect all possible programming errors.
  115. If FOOTERS is defined nonzero, then each allocated chunk
  116. carries an additional check word to verify that it was malloced
  117. from its space. These check words are the same within each
  118. execution of a program using malloc, but differ across
  119. executions, so externally crafted fake chunks cannot be
  120. freed. This improves security by rejecting frees/reallocs that
  121. could corrupt heap memory, in addition to the checks preventing
  122. writes to statics that are always on. This may further improve
  123. security at the expense of time and space overhead. (Note that
  124. FOOTERS may also be worth using with MSPACES.)
  125. By default detected errors cause the program to abort (calling
  126. "abort()"). You can override this to instead proceed past
  127. errors by defining PROCEED_ON_ERROR. In this case, a bad free
  128. has no effect, and a malloc that encounters a bad address
  129. caused by user overwrites will ignore the bad address by
  130. dropping pointers and indices to all known memory. This may
  131. be appropriate for programs that should continue if at all
  132. possible in the face of programming errors, although they may
  133. run out of memory because dropped memory is never reclaimed.
  134. If you don't like either of these options, you can define
  135. CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything
  136. else. And if if you are sure that your program using malloc has
  137. no errors or vulnerabilities, you can define INSECURE to 1,
  138. which might (or might not) provide a small performance improvement.
  139. Thread-safety: NOT thread-safe unless USE_LOCKS defined
  140. When USE_LOCKS is defined, each public call to malloc, free,
  141. etc is surrounded with either a pthread mutex or a win32
  142. spinlock (depending on WIN32). This is not especially fast, and
  143. can be a major bottleneck. It is designed only to provide
  144. minimal protection in concurrent environments, and to provide a
  145. basis for extensions. If you are using malloc in a concurrent
  146. program, consider instead using ptmalloc, which is derived from
  147. a version of this malloc. (See http://www.malloc.de).
  148. System requirements: Any combination of MORECORE and/or MMAP/MUNMAP
  149. This malloc can use unix sbrk or any emulation (invoked using
  150. the CALL_MORECORE macro) and/or mmap/munmap or any emulation
  151. (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system
  152. memory. On most unix systems, it tends to work best if both
  153. MORECORE and MMAP are enabled. On Win32, it uses emulations
  154. based on VirtualAlloc. It also uses common C library functions
  155. like memset.
  156. Compliance: I believe it is compliant with the Single Unix Specification
  157. (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably
  158. others as well.
  159. * Overview of algorithms
  160. This is not the fastest, most space-conserving, most portable, or
  161. most tunable malloc ever written. However it is among the fastest
  162. while also being among the most space-conserving, portable and
  163. tunable. Consistent balance across these factors results in a good
  164. general-purpose allocator for malloc-intensive programs.
  165. In most ways, this malloc is a best-fit allocator. Generally, it
  166. chooses the best-fitting existing chunk for a request, with ties
  167. broken in approximately least-recently-used order. (This strategy
  168. normally maintains low fragmentation.) However, for requests less
  169. than 256bytes, it deviates from best-fit when there is not an
  170. exactly fitting available chunk by preferring to use space adjacent
  171. to that used for the previous small request, as well as by breaking
  172. ties in approximately most-recently-used order. (These enhance
  173. locality of series of small allocations.) And for very large requests
  174. (>= 256Kb by default), it relies on system memory mapping
  175. facilities, if supported. (This helps avoid carrying around and
  176. possibly fragmenting memory used only for large chunks.)
  177. All operations (except malloc_stats and mallinfo) have execution
  178. times that are bounded by a constant factor of the number of bits in
  179. a size_t, not counting any clearing in calloc or copying in realloc,
  180. or actions surrounding MORECORE and MMAP that have times
  181. proportional to the number of non-contiguous regions returned by
  182. system allocation routines, which is often just 1.
  183. The implementation is not very modular and seriously overuses
  184. macros. Perhaps someday all C compilers will do as good a job
  185. inlining modular code as can now be done by brute-force expansion,
  186. but now, enough of them seem not to.
  187. Some compilers issue a lot of warnings about code that is
  188. dead/unreachable only on some platforms, and also about intentional
  189. uses of negation on unsigned types. All known cases of each can be
  190. ignored.
  191. For a longer but out of date high-level description, see
  192. http://gee.cs.oswego.edu/dl/html/malloc.html
  193. * MSPACES
  194. If MSPACES is defined, then in addition to malloc, free, etc.,
  195. this file also defines mspace_malloc, mspace_free, etc. These
  196. are versions of malloc routines that take an "mspace" argument
  197. obtained using create_mspace, to control all internal bookkeeping.
  198. If ONLY_MSPACES is defined, only these versions are compiled.
  199. So if you would like to use this allocator for only some allocations,
  200. and your system malloc for others, you can compile with
  201. ONLY_MSPACES and then do something like...
  202. static mspace mymspace = create_mspace(0,0); // for example
  203. #define mymalloc(bytes) mspace_malloc(mymspace, bytes)
  204. (Note: If you only need one instance of an mspace, you can instead
  205. use "USE_DL_PREFIX" to relabel the global malloc.)
  206. You can similarly create thread-local allocators by storing
  207. mspaces as thread-locals. For example:
  208. static __thread mspace tlms = 0;
  209. void* tlmalloc(size_t bytes) {
  210. if (tlms == 0) tlms = create_mspace(0, 0);
  211. return mspace_malloc(tlms, bytes);
  212. }
  213. void tlfree(void* mem) { mspace_free(tlms, mem); }
  214. Unless FOOTERS is defined, each mspace is completely independent.
  215. You cannot allocate from one and free to another (although
  216. conformance is only weakly checked, so usage errors are not always
  217. caught). If FOOTERS is defined, then each chunk carries around a tag
  218. indicating its originating mspace, and frees are directed to their
  219. originating spaces.
  220. ------------------------- Compile-time options ---------------------------
  221. Be careful in setting #define values for numerical constants of type
  222. size_t. On some systems, literal values are not automatically extended
  223. to size_t precision unless they are explicitly casted.
  224. WIN32 default: defined if _WIN32 defined
  225. Defining WIN32 sets up defaults for MS environment and compilers.
  226. Otherwise defaults are for unix.
  227. MALLOC_ALIGNMENT default: (size_t)8
  228. Controls the minimum alignment for malloc'ed chunks. It must be a
  229. power of two and at least 8, even on machines for which smaller
  230. alignments would suffice. It may be defined as larger than this
  231. though. Note however that code and data structures are optimized for
  232. the case of 8-byte alignment.
  233. MSPACES default: 0 (false)
  234. If true, compile in support for independent allocation spaces.
  235. This is only supported if HAVE_MMAP is true.
  236. ONLY_MSPACES default: 0 (false)
  237. If true, only compile in mspace versions, not regular versions.
  238. USE_LOCKS default: 0 (false)
  239. Causes each call to each public routine to be surrounded with
  240. pthread or WIN32 mutex lock/unlock. (If set true, this can be
  241. overridden on a per-mspace basis for mspace versions.)
  242. FOOTERS default: 0
  243. If true, provide extra checking and dispatching by placing
  244. information in the footers of allocated chunks. This adds
  245. space and time overhead.
  246. INSECURE default: 0
  247. If true, omit checks for usage errors and heap space overwrites.
  248. USE_DL_PREFIX default: NOT defined
  249. Causes compiler to prefix all public routines with the string 'dl'.
  250. This can be useful when you only want to use this malloc in one part
  251. of a program, using your regular system malloc elsewhere.
  252. ABORT default: defined as abort()
  253. Defines how to abort on failed checks. On most systems, a failed
  254. check cannot die with an "assert" or even print an informative
  255. message, because the underlying print routines in turn call malloc,
  256. which will fail again. Generally, the best policy is to simply call
  257. abort(). It's not very useful to do more than this because many
  258. errors due to overwriting will show up as address faults (null, odd
  259. addresses etc) rather than malloc-triggered checks, so will also
  260. abort. Also, most compilers know that abort() does not return, so
  261. can better optimize code conditionally calling it.
  262. PROCEED_ON_ERROR default: defined as 0 (false)
  263. Controls whether detected bad addresses cause them to bypassed
  264. rather than aborting. If set, detected bad arguments to free and
  265. realloc are ignored. And all bookkeeping information is zeroed out
  266. upon a detected overwrite of freed heap space, thus losing the
  267. ability to ever return it from malloc again, but enabling the
  268. application to proceed. If PROCEED_ON_ERROR is defined, the
  269. static variable malloc_corruption_error_count is compiled in
  270. and can be examined to see if errors have occurred. This option
  271. generates slower code than the default abort policy.
  272. DEBUG default: NOT defined
  273. The DEBUG setting is mainly intended for people trying to modify
  274. this code or diagnose problems when porting to new platforms.
  275. However, it may also be able to better isolate user errors than just
  276. using runtime checks. The assertions in the check routines spell
  277. out in more detail the assumptions and invariants underlying the
  278. algorithms. The checking is fairly extensive, and will slow down
  279. execution noticeably. Calling malloc_stats or mallinfo with DEBUG
  280. set will attempt to check every non-mmapped allocated and free chunk
  281. in the course of computing the summaries.
  282. ABORT_ON_ASSERT_FAILURE default: defined as 1 (true)
  283. Debugging assertion failures can be nearly impossible if your
  284. version of the assert macro causes malloc to be called, which will
  285. lead to a cascade of further failures, blowing the runtime stack.
  286. ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),
  287. which will usually make debugging easier.
  288. MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32
  289. The action to take before "return 0" when malloc fails to be able to
  290. return memory because there is none available.
  291. HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES
  292. True if this system supports sbrk or an emulation of it.
  293. MORECORE default: sbrk
  294. The name of the sbrk-style system routine to call to obtain more
  295. memory. See below for guidance on writing custom MORECORE
  296. functions. The type of the argument to sbrk/MORECORE varies across
  297. systems. It cannot be size_t, because it supports negative
  298. arguments, so it is normally the signed type of the same width as
  299. size_t (sometimes declared as "intptr_t"). It doesn't much matter
  300. though. Internally, we only call it with arguments less than half
  301. the max value of a size_t, which should work across all reasonable
  302. possibilities, although sometimes generating compiler warnings. See
  303. near the end of this file for guidelines for creating a custom
  304. version of MORECORE.
  305. MORECORE_CONTIGUOUS default: 1 (true)
  306. If true, take advantage of fact that consecutive calls to MORECORE
  307. with positive arguments always return contiguous increasing
  308. addresses. This is true of unix sbrk. It does not hurt too much to
  309. set it true anyway, since malloc copes with non-contiguities.
  310. Setting it false when definitely non-contiguous saves time
  311. and possibly wasted space it would take to discover this though.
  312. MORECORE_CANNOT_TRIM default: NOT defined
  313. True if MORECORE cannot release space back to the system when given
  314. negative arguments. This is generally necessary only if you are
  315. using a hand-crafted MORECORE function that cannot handle negative
  316. arguments.
  317. HAVE_MMAP default: 1 (true)
  318. True if this system supports mmap or an emulation of it. If so, and
  319. HAVE_MORECORE is not true, MMAP is used for all system
  320. allocation. If set and HAVE_MORECORE is true as well, MMAP is
  321. primarily used to directly allocate very large blocks. It is also
  322. used as a backup strategy in cases where MORECORE fails to provide
  323. space from system. Note: A single call to MUNMAP is assumed to be
  324. able to unmap memory that may have be allocated using multiple calls
  325. to MMAP, so long as they are adjacent.
  326. HAVE_MREMAP default: 1 on linux, else 0
  327. If true realloc() uses mremap() to re-allocate large blocks and
  328. extend or shrink allocation spaces.
  329. MMAP_CLEARS default: 1 on unix
  330. True if mmap clears memory so calloc doesn't need to. This is true
  331. for standard unix mmap using /dev/zero.
  332. USE_BUILTIN_FFS default: 0 (i.e., not used)
  333. Causes malloc to use the builtin ffs() function to compute indices.
  334. Some compilers may recognize and intrinsify ffs to be faster than the
  335. supplied C version. Also, the case of x86 using gcc is special-cased
  336. to an asm instruction, so is already as fast as it can be, and so
  337. this setting has no effect. (On most x86s, the asm version is only
  338. slightly faster than the C version.)
  339. malloc_getpagesize default: derive from system includes, or 4096.
  340. The system page size. To the extent possible, this malloc manages
  341. memory from the system in page-size units. This may be (and
  342. usually is) a function rather than a constant. This is ignored
  343. if WIN32, where page size is determined using getSystemInfo during
  344. initialization.
  345. USE_DEV_RANDOM default: 0 (i.e., not used)
  346. Causes malloc to use /dev/random to initialize secure magic seed for
  347. stamping footers. Otherwise, the current time is used.
  348. NO_MALLINFO default: 0
  349. If defined, don't compile "mallinfo". This can be a simple way
  350. of dealing with mismatches between system declarations and
  351. those in this file.
  352. MALLINFO_FIELD_TYPE default: size_t
  353. The type of the fields in the mallinfo struct. This was originally
  354. defined as "int" in SVID etc, but is more usefully defined as
  355. size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set
  356. REALLOC_ZERO_BYTES_FREES default: not defined
  357. This should be set if a call to realloc with zero bytes should
  358. be the same as a call to free. Some people think it should. Otherwise,
  359. since this malloc returns a unique pointer for malloc(0), so does
  360. realloc(p, 0).
  361. LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H
  362. LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H
  363. LACKS_STDLIB_H default: NOT defined unless on WIN32
  364. Define these if your system does not have these header files.
  365. You might need to manually insert some of the declarations they provide.
  366. DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS,
  367. system_info.dwAllocationGranularity in WIN32,
  368. otherwise 64K.
  369. Also settable using mallopt(M_GRANULARITY, x)
  370. The unit for allocating and deallocating memory from the system. On
  371. most systems with contiguous MORECORE, there is no reason to
  372. make this more than a page. However, systems with MMAP tend to
  373. either require or encourage larger granularities. You can increase
  374. this value to prevent system allocation functions to be called so
  375. often, especially if they are slow. The value must be at least one
  376. page and must be a power of two. Setting to 0 causes initialization
  377. to either page size or win32 region size. (Note: In previous
  378. versions of malloc, the equivalent of this option was called
  379. "TOP_PAD")
  380. DEFAULT_TRIM_THRESHOLD default: 2MB
  381. Also settable using mallopt(M_TRIM_THRESHOLD, x)
  382. The maximum amount of unused top-most memory to keep before
  383. releasing via malloc_trim in free(). Automatic trimming is mainly
  384. useful in long-lived programs using contiguous MORECORE. Because
  385. trimming via sbrk can be slow on some systems, and can sometimes be
  386. wasteful (in cases where programs immediately afterward allocate
  387. more large chunks) the value should be high enough so that your
  388. overall system performance would improve by releasing this much
  389. memory. As a rough guide, you might set to a value close to the
  390. average size of a process (program) running on your system.
  391. Releasing this much memory would allow such a process to run in
  392. memory. Generally, it is worth tuning trim thresholds when a
  393. program undergoes phases where several large chunks are allocated
  394. and released in ways that can reuse each other's storage, perhaps
  395. mixed with phases where there are no such chunks at all. The trim
  396. value must be greater than page size to have any useful effect. To
  397. disable trimming completely, you can set to MAX_SIZE_T. Note that the trick
  398. some people use of mallocing a huge space and then freeing it at
  399. program startup, in an attempt to reserve system memory, doesn't
  400. have the intended effect under automatic trimming, since that memory
  401. will immediately be returned to the system.
  402. DEFAULT_MMAP_THRESHOLD default: 256K
  403. Also settable using mallopt(M_MMAP_THRESHOLD, x)
  404. The request size threshold for using MMAP to directly service a
  405. request. Requests of at least this size that cannot be allocated
  406. using already-existing space will be serviced via mmap. (If enough
  407. normal freed space already exists it is used instead.) Using mmap
  408. segregates relatively large chunks of memory so that they can be
  409. individually obtained and released from the host system. A request
  410. serviced through mmap is never reused by any other request (at least
  411. not directly; the system may just so happen to remap successive
  412. requests to the same locations). Segregating space in this way has
  413. the benefits that: Mmapped space can always be individually released
  414. back to the system, which helps keep the system level memory demands
  415. of a long-lived program low. Also, mapped memory doesn't become
  416. `locked' between other chunks, as can happen with normally allocated
  417. chunks, which means that even trimming via malloc_trim would not
  418. release them. However, it has the disadvantage that the space
  419. cannot be reclaimed, consolidated, and then used to service later
  420. requests, as happens with normal chunks. The advantages of mmap
  421. nearly always outweigh disadvantages for "large" chunks, but the
  422. value of "large" may vary across systems. The default is an
  423. empirically derived value that works well in most systems. You can
  424. disable mmap by setting to MAX_SIZE_T.
  425. */
  426. #ifndef WIN32
  427. #ifdef _WIN32
  428. #define WIN32 1
  429. #endif /* _WIN32 */
  430. #endif /* WIN32 */
  431. #ifdef WIN32
  432. #define WIN32_LEAN_AND_MEAN
  433. #include <windows.h>
  434. #define HAVE_MMAP 1
  435. #define HAVE_MORECORE 0
  436. #define LACKS_UNISTD_H
  437. #define LACKS_SYS_PARAM_H
  438. #define LACKS_SYS_MMAN_H
  439. #define LACKS_STRING_H
  440. #define LACKS_STRINGS_H
  441. #define LACKS_SYS_TYPES_H
  442. #define LACKS_ERRNO_H
  443. #define LACKS_FCNTL_H
  444. #define MALLOC_FAILURE_ACTION
  445. #define MMAP_CLEARS 0 /* WINCE and some others apparently don't clear */
  446. #endif /* WIN32 */
  447. #if defined(DARWIN) || defined(_DARWIN)
  448. /* Mac OSX docs advise not to use sbrk; it seems better to use mmap */
  449. #ifndef HAVE_MORECORE
  450. #define HAVE_MORECORE 0
  451. #define HAVE_MMAP 1
  452. #endif /* HAVE_MORECORE */
  453. #endif /* DARWIN */
  454. #ifndef LACKS_SYS_TYPES_H
  455. #include <sys/types.h> /* For size_t */
  456. #endif /* LACKS_SYS_TYPES_H */
  457. /* The maximum possible size_t value has all bits set */
  458. #define MAX_SIZE_T (~(size_t)0)
  459. #ifndef ONLY_MSPACES
  460. #define ONLY_MSPACES 0
  461. #endif /* ONLY_MSPACES */
  462. #ifndef MSPACES
  463. #if ONLY_MSPACES
  464. #define MSPACES 1
  465. #else /* ONLY_MSPACES */
  466. #define MSPACES 0
  467. #endif /* ONLY_MSPACES */
  468. #endif /* MSPACES */
  469. #ifndef MALLOC_ALIGNMENT
  470. #define MALLOC_ALIGNMENT ((size_t)8U)
  471. #endif /* MALLOC_ALIGNMENT */
  472. #ifndef FOOTERS
  473. #define FOOTERS 0
  474. #endif /* FOOTERS */
  475. #ifndef ABORT
  476. #define ABORT abort()
  477. #endif /* ABORT */
  478. #ifndef ABORT_ON_ASSERT_FAILURE
  479. #define ABORT_ON_ASSERT_FAILURE 1
  480. #endif /* ABORT_ON_ASSERT_FAILURE */
  481. #ifndef PROCEED_ON_ERROR
  482. #define PROCEED_ON_ERROR 0
  483. #endif /* PROCEED_ON_ERROR */
  484. #ifndef USE_LOCKS
  485. #define USE_LOCKS 0
  486. #endif /* USE_LOCKS */
  487. #ifndef INSECURE
  488. #define INSECURE 0
  489. #endif /* INSECURE */
  490. #ifndef HAVE_MMAP
  491. #define HAVE_MMAP 1
  492. #endif /* HAVE_MMAP */
  493. #ifndef MMAP_CLEARS
  494. #define MMAP_CLEARS 1
  495. #endif /* MMAP_CLEARS */
  496. #ifndef HAVE_MREMAP
  497. #ifdef linux
  498. #define HAVE_MREMAP 1
  499. #else /* linux */
  500. #define HAVE_MREMAP 0
  501. #endif /* linux */
  502. #endif /* HAVE_MREMAP */
  503. #ifndef MALLOC_FAILURE_ACTION
  504. #define MALLOC_FAILURE_ACTION errno = ENOMEM;
  505. #endif /* MALLOC_FAILURE_ACTION */
  506. #ifndef HAVE_MORECORE
  507. #if ONLY_MSPACES
  508. #define HAVE_MORECORE 0
  509. #else /* ONLY_MSPACES */
  510. #define HAVE_MORECORE 1
  511. #endif /* ONLY_MSPACES */
  512. #endif /* HAVE_MORECORE */
  513. #if !HAVE_MORECORE
  514. #define MORECORE_CONTIGUOUS 0
  515. #else /* !HAVE_MORECORE */
  516. #ifndef MORECORE
  517. #define MORECORE sbrk
  518. #endif /* MORECORE */
  519. #ifndef MORECORE_CONTIGUOUS
  520. #define MORECORE_CONTIGUOUS 1
  521. #endif /* MORECORE_CONTIGUOUS */
  522. #endif /* HAVE_MORECORE */
  523. #ifndef DEFAULT_GRANULARITY
  524. #if MORECORE_CONTIGUOUS
  525. #define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */
  526. #else /* MORECORE_CONTIGUOUS */
  527. #define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)
  528. #endif /* MORECORE_CONTIGUOUS */
  529. #endif /* DEFAULT_GRANULARITY */
  530. #ifndef DEFAULT_TRIM_THRESHOLD
  531. #ifndef MORECORE_CANNOT_TRIM
  532. #define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)
  533. #else /* MORECORE_CANNOT_TRIM */
  534. #define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T
  535. #endif /* MORECORE_CANNOT_TRIM */
  536. #endif /* DEFAULT_TRIM_THRESHOLD */
  537. #ifndef DEFAULT_MMAP_THRESHOLD
  538. #if HAVE_MMAP
  539. #define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)
  540. #else /* HAVE_MMAP */
  541. #define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
  542. #endif /* HAVE_MMAP */
  543. #endif /* DEFAULT_MMAP_THRESHOLD */
  544. #ifndef USE_BUILTIN_FFS
  545. #define USE_BUILTIN_FFS 0
  546. #endif /* USE_BUILTIN_FFS */
  547. #ifndef USE_DEV_RANDOM
  548. #define USE_DEV_RANDOM 0
  549. #endif /* USE_DEV_RANDOM */
  550. #ifndef NO_MALLINFO
  551. #define NO_MALLINFO 0
  552. #endif /* NO_MALLINFO */
  553. #ifndef MALLINFO_FIELD_TYPE
  554. #define MALLINFO_FIELD_TYPE size_t
  555. #endif /* MALLINFO_FIELD_TYPE */
  556. #define memset SDL_memset
  557. #define memcpy SDL_memcpy
  558. #define malloc SDL_malloc
  559. #define calloc SDL_calloc
  560. #define realloc SDL_realloc
  561. #define free SDL_free
  562. /*
  563. mallopt tuning options. SVID/XPG defines four standard parameter
  564. numbers for mallopt, normally defined in malloc.h. None of these
  565. are used in this malloc, so setting them has no effect. But this
  566. malloc does support the following options.
  567. */
  568. #define M_TRIM_THRESHOLD (-1)
  569. #define M_GRANULARITY (-2)
  570. #define M_MMAP_THRESHOLD (-3)
  571. /* ------------------------ Mallinfo declarations ------------------------ */
  572. #if !NO_MALLINFO
  573. /*
  574. This version of malloc supports the standard SVID/XPG mallinfo
  575. routine that returns a struct containing usage properties and
  576. statistics. It should work on any system that has a
  577. /usr/include/malloc.h defining struct mallinfo. The main
  578. declaration needed is the mallinfo struct that is returned (by-copy)
  579. by mallinfo(). The malloinfo struct contains a bunch of fields that
  580. are not even meaningful in this version of malloc. These fields are
  581. are instead filled by mallinfo() with other numbers that might be of
  582. interest.
  583. HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
  584. /usr/include/malloc.h file that includes a declaration of struct
  585. mallinfo. If so, it is included; else a compliant version is
  586. declared below. These must be precisely the same for mallinfo() to
  587. work. The original SVID version of this struct, defined on most
  588. systems with mallinfo, declares all fields as ints. But some others
  589. define as unsigned long. If your system defines the fields using a
  590. type of different width than listed here, you MUST #include your
  591. system version and #define HAVE_USR_INCLUDE_MALLOC_H.
  592. */
  593. /* #define HAVE_USR_INCLUDE_MALLOC_H */
  594. #ifdef HAVE_USR_INCLUDE_MALLOC_H
  595. #include "/usr/include/malloc.h"
  596. #else /* HAVE_USR_INCLUDE_MALLOC_H */
  597. struct mallinfo
  598. {
  599. MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */
  600. MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */
  601. MALLINFO_FIELD_TYPE smblks; /* always 0 */
  602. MALLINFO_FIELD_TYPE hblks; /* always 0 */
  603. MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */
  604. MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */
  605. MALLINFO_FIELD_TYPE fsmblks; /* always 0 */
  606. MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
  607. MALLINFO_FIELD_TYPE fordblks; /* total free space */
  608. MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */
  609. };
  610. #endif /* HAVE_USR_INCLUDE_MALLOC_H */
  611. #endif /* NO_MALLINFO */
  612. #ifdef __cplusplus
  613. extern "C"
  614. {
  615. #endif /* __cplusplus */
  616. #if !ONLY_MSPACES
  617. /* ------------------- Declarations of public routines ------------------- */
  618. #ifndef USE_DL_PREFIX
  619. #define dlcalloc calloc
  620. #define dlfree free
  621. #define dlmalloc malloc
  622. #define dlmemalign memalign
  623. #define dlrealloc realloc
  624. #define dlvalloc valloc
  625. #define dlpvalloc pvalloc
  626. #define dlmallinfo mallinfo
  627. #define dlmallopt mallopt
  628. #define dlmalloc_trim malloc_trim
  629. #define dlmalloc_stats malloc_stats
  630. #define dlmalloc_usable_size malloc_usable_size
  631. #define dlmalloc_footprint malloc_footprint
  632. #define dlmalloc_max_footprint malloc_max_footprint
  633. #define dlindependent_calloc independent_calloc
  634. #define dlindependent_comalloc independent_comalloc
  635. #endif /* USE_DL_PREFIX */
  636. /*
  637. malloc(size_t n)
  638. Returns a pointer to a newly allocated chunk of at least n bytes, or
  639. null if no space is available, in which case errno is set to ENOMEM
  640. on ANSI C systems.
  641. If n is zero, malloc returns a minimum-sized chunk. (The minimum
  642. size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
  643. systems.) Note that size_t is an unsigned type, so calls with
  644. arguments that would be negative if signed are interpreted as
  645. requests for huge amounts of space, which will often fail. The
  646. maximum supported value of n differs across systems, but is in all
  647. cases less than the maximum representable value of a size_t.
  648. */
  649. void *dlmalloc(size_t);
  650. /*
  651. free(void* p)
  652. Releases the chunk of memory pointed to by p, that had been previously
  653. allocated using malloc or a related routine such as realloc.
  654. It has no effect if p is null. If p was not malloced or already
  655. freed, free(p) will by default cause the current program to abort.
  656. */
  657. void dlfree(void *);
  658. /*
  659. calloc(size_t n_elements, size_t element_size);
  660. Returns a pointer to n_elements * element_size bytes, with all locations
  661. set to zero.
  662. */
  663. void *dlcalloc(size_t, size_t);
  664. /*
  665. realloc(void* p, size_t n)
  666. Returns a pointer to a chunk of size n that contains the same data
  667. as does chunk p up to the minimum of (n, p's size) bytes, or null
  668. if no space is available.
  669. The returned pointer may or may not be the same as p. The algorithm
  670. prefers extending p in most cases when possible, otherwise it
  671. employs the equivalent of a malloc-copy-free sequence.
  672. If p is null, realloc is equivalent to malloc.
  673. If space is not available, realloc returns null, errno is set (if on
  674. ANSI) and p is NOT freed.
  675. if n is for fewer bytes than already held by p, the newly unused
  676. space is lopped off and freed if possible. realloc with a size
  677. argument of zero (re)allocates a minimum-sized chunk.
  678. The old unix realloc convention of allowing the last-free'd chunk
  679. to be used as an argument to realloc is not supported.
  680. */
  681. void *dlrealloc(void *, size_t);
  682. /*
  683. memalign(size_t alignment, size_t n);
  684. Returns a pointer to a newly allocated chunk of n bytes, aligned
  685. in accord with the alignment argument.
  686. The alignment argument should be a power of two. If the argument is
  687. not a power of two, the nearest greater power is used.
  688. 8-byte alignment is guaranteed by normal malloc calls, so don't
  689. bother calling memalign with an argument of 8 or less.
  690. Overreliance on memalign is a sure way to fragment space.
  691. */
  692. void *dlmemalign(size_t, size_t);
  693. /*
  694. valloc(size_t n);
  695. Equivalent to memalign(pagesize, n), where pagesize is the page
  696. size of the system. If the pagesize is unknown, 4096 is used.
  697. */
  698. void *dlvalloc(size_t);
  699. /*
  700. mallopt(int parameter_number, int parameter_value)
  701. Sets tunable parameters The format is to provide a
  702. (parameter-number, parameter-value) pair. mallopt then sets the
  703. corresponding parameter to the argument value if it can (i.e., so
  704. long as the value is meaningful), and returns 1 if successful else
  705. 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
  706. normally defined in malloc.h. None of these are use in this malloc,
  707. so setting them has no effect. But this malloc also supports other
  708. options in mallopt. See below for details. Briefly, supported
  709. parameters are as follows (listed defaults are for "typical"
  710. configurations).
  711. Symbol param # default allowed param values
  712. M_TRIM_THRESHOLD -1 2*1024*1024 any (MAX_SIZE_T disables)
  713. M_GRANULARITY -2 page size any power of 2 >= page size
  714. M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support)
  715. */
  716. int dlmallopt(int, int);
  717. /*
  718. malloc_footprint();
  719. Returns the number of bytes obtained from the system. The total
  720. number of bytes allocated by malloc, realloc etc., is less than this
  721. value. Unlike mallinfo, this function returns only a precomputed
  722. result, so can be called frequently to monitor memory consumption.
  723. Even if locks are otherwise defined, this function does not use them,
  724. so results might not be up to date.
  725. */
  726. size_t dlmalloc_footprint(void);
  727. /*
  728. malloc_max_footprint();
  729. Returns the maximum number of bytes obtained from the system. This
  730. value will be greater than current footprint if deallocated space
  731. has been reclaimed by the system. The peak number of bytes allocated
  732. by malloc, realloc etc., is less than this value. Unlike mallinfo,
  733. this function returns only a precomputed result, so can be called
  734. frequently to monitor memory consumption. Even if locks are
  735. otherwise defined, this function does not use them, so results might
  736. not be up to date.
  737. */
  738. size_t dlmalloc_max_footprint(void);
  739. #if !NO_MALLINFO
  740. /*
  741. mallinfo()
  742. Returns (by copy) a struct containing various summary statistics:
  743. arena: current total non-mmapped bytes allocated from system
  744. ordblks: the number of free chunks
  745. smblks: always zero.
  746. hblks: current number of mmapped regions
  747. hblkhd: total bytes held in mmapped regions
  748. usmblks: the maximum total allocated space. This will be greater
  749. than current total if trimming has occurred.
  750. fsmblks: always zero
  751. uordblks: current total allocated space (normal or mmapped)
  752. fordblks: total free space
  753. keepcost: the maximum number of bytes that could ideally be released
  754. back to system via malloc_trim. ("ideally" means that
  755. it ignores page restrictions etc.)
  756. Because these fields are ints, but internal bookkeeping may
  757. be kept as longs, the reported values may wrap around zero and
  758. thus be inaccurate.
  759. */
  760. struct mallinfo dlmallinfo(void);
  761. #endif /* NO_MALLINFO */
  762. /*
  763. independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
  764. independent_calloc is similar to calloc, but instead of returning a
  765. single cleared space, it returns an array of pointers to n_elements
  766. independent elements that can hold contents of size elem_size, each
  767. of which starts out cleared, and can be independently freed,
  768. realloc'ed etc. The elements are guaranteed to be adjacently
  769. allocated (this is not guaranteed to occur with multiple callocs or
  770. mallocs), which may also improve cache locality in some
  771. applications.
  772. The "chunks" argument is optional (i.e., may be null, which is
  773. probably the most typical usage). If it is null, the returned array
  774. is itself dynamically allocated and should also be freed when it is
  775. no longer needed. Otherwise, the chunks array must be of at least
  776. n_elements in length. It is filled in with the pointers to the
  777. chunks.
  778. In either case, independent_calloc returns this pointer array, or
  779. null if the allocation failed. If n_elements is zero and "chunks"
  780. is null, it returns a chunk representing an array with zero elements
  781. (which should be freed if not wanted).
  782. Each element must be individually freed when it is no longer
  783. needed. If you'd like to instead be able to free all at once, you
  784. should instead use regular calloc and assign pointers into this
  785. space to represent elements. (In this case though, you cannot
  786. independently free elements.)
  787. independent_calloc simplifies and speeds up implementations of many
  788. kinds of pools. It may also be useful when constructing large data
  789. structures that initially have a fixed number of fixed-sized nodes,
  790. but the number is not known at compile time, and some of the nodes
  791. may later need to be freed. For example:
  792. struct Node { int item; struct Node* next; };
  793. struct Node* build_list() {
  794. struct Node** pool;
  795. int n = read_number_of_nodes_needed();
  796. if (n <= 0) return 0;
  797. pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
  798. if (pool == 0) die();
  799. // organize into a linked list...
  800. struct Node* first = pool[0];
  801. for (i = 0; i < n-1; ++i)
  802. pool[i]->next = pool[i+1];
  803. free(pool); // Can now free the array (or not, if it is needed later)
  804. return first;
  805. }
  806. */
  807. void **dlindependent_calloc(size_t, size_t, void **);
  808. /*
  809. independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
  810. independent_comalloc allocates, all at once, a set of n_elements
  811. chunks with sizes indicated in the "sizes" array. It returns
  812. an array of pointers to these elements, each of which can be
  813. independently freed, realloc'ed etc. The elements are guaranteed to
  814. be adjacently allocated (this is not guaranteed to occur with
  815. multiple callocs or mallocs), which may also improve cache locality
  816. in some applications.
  817. The "chunks" argument is optional (i.e., may be null). If it is null
  818. the returned array is itself dynamically allocated and should also
  819. be freed when it is no longer needed. Otherwise, the chunks array
  820. must be of at least n_elements in length. It is filled in with the
  821. pointers to the chunks.
  822. In either case, independent_comalloc returns this pointer array, or
  823. null if the allocation failed. If n_elements is zero and chunks is
  824. null, it returns a chunk representing an array with zero elements
  825. (which should be freed if not wanted).
  826. Each element must be individually freed when it is no longer
  827. needed. If you'd like to instead be able to free all at once, you
  828. should instead use a single regular malloc, and assign pointers at
  829. particular offsets in the aggregate space. (In this case though, you
  830. cannot independently free elements.)
  831. independent_comallac differs from independent_calloc in that each
  832. element may have a different size, and also that it does not
  833. automatically clear elements.
  834. independent_comalloc can be used to speed up allocation in cases
  835. where several structs or objects must always be allocated at the
  836. same time. For example:
  837. struct Head { ... }
  838. struct Foot { ... }
  839. void send_message(char* msg) {
  840. int msglen = strlen(msg);
  841. size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
  842. void* chunks[3];
  843. if (independent_comalloc(3, sizes, chunks) == 0)
  844. die();
  845. struct Head* head = (struct Head*)(chunks[0]);
  846. char* body = (char*)(chunks[1]);
  847. struct Foot* foot = (struct Foot*)(chunks[2]);
  848. // ...
  849. }
  850. In general though, independent_comalloc is worth using only for
  851. larger values of n_elements. For small values, you probably won't
  852. detect enough difference from series of malloc calls to bother.
  853. Overuse of independent_comalloc can increase overall memory usage,
  854. since it cannot reuse existing noncontiguous small chunks that
  855. might be available for some of the elements.
  856. */
  857. void **dlindependent_comalloc(size_t, size_t *, void **);
  858. /*
  859. pvalloc(size_t n);
  860. Equivalent to valloc(minimum-page-that-holds(n)), that is,
  861. round up n to nearest pagesize.
  862. */
  863. void *dlpvalloc(size_t);
  864. /*
  865. malloc_trim(size_t pad);
  866. If possible, gives memory back to the system (via negative arguments
  867. to sbrk) if there is unused memory at the `high' end of the malloc
  868. pool or in unused MMAP segments. You can call this after freeing
  869. large blocks of memory to potentially reduce the system-level memory
  870. requirements of a program. However, it cannot guarantee to reduce
  871. memory. Under some allocation patterns, some large free blocks of
  872. memory will be locked between two used chunks, so they cannot be
  873. given back to the system.
  874. The `pad' argument to malloc_trim represents the amount of free
  875. trailing space to leave untrimmed. If this argument is zero, only
  876. the minimum amount of memory to maintain internal data structures
  877. will be left. Non-zero arguments can be supplied to maintain enough
  878. trailing space to service future expected allocations without having
  879. to re-obtain memory from the system.
  880. Malloc_trim returns 1 if it actually released any memory, else 0.
  881. */
  882. int dlmalloc_trim(size_t);
  883. /*
  884. malloc_usable_size(void* p);
  885. Returns the number of bytes you can actually use in
  886. an allocated chunk, which may be more than you requested (although
  887. often not) due to alignment and minimum size constraints.
  888. You can use this many bytes without worrying about
  889. overwriting other allocated objects. This is not a particularly great
  890. programming practice. malloc_usable_size can be more useful in
  891. debugging and assertions, for example:
  892. p = malloc(n);
  893. assert(malloc_usable_size(p) >= 256);
  894. */
  895. size_t dlmalloc_usable_size(void *);
  896. /*
  897. malloc_stats();
  898. Prints on stderr the amount of space obtained from the system (both
  899. via sbrk and mmap), the maximum amount (which may be more than
  900. current if malloc_trim and/or munmap got called), and the current
  901. number of bytes allocated via malloc (or realloc, etc) but not yet
  902. freed. Note that this is the number of bytes allocated, not the
  903. number requested. It will be larger than the number requested
  904. because of alignment and bookkeeping overhead. Because it includes
  905. alignment wastage as being in use, this figure may be greater than
  906. zero even when no user-level chunks are allocated.
  907. The reported current and maximum system memory can be inaccurate if
  908. a program makes other calls to system memory allocation functions
  909. (normally sbrk) outside of malloc.
  910. malloc_stats prints only the most commonly interesting statistics.
  911. More information can be obtained by calling mallinfo.
  912. */
  913. void dlmalloc_stats(void);
  914. #endif /* ONLY_MSPACES */
  915. #if MSPACES
  916. /*
  917. mspace is an opaque type representing an independent
  918. region of space that supports mspace_malloc, etc.
  919. */
  920. typedef void *mspace;
  921. /*
  922. create_mspace creates and returns a new independent space with the
  923. given initial capacity, or, if 0, the default granularity size. It
  924. returns null if there is no system memory available to create the
  925. space. If argument locked is non-zero, the space uses a separate
  926. lock to control access. The capacity of the space will grow
  927. dynamically as needed to service mspace_malloc requests. You can
  928. control the sizes of incremental increases of this space by
  929. compiling with a different DEFAULT_GRANULARITY or dynamically
  930. setting with mallopt(M_GRANULARITY, value).
  931. */
  932. mspace create_mspace(size_t capacity, int locked);
  933. /*
  934. destroy_mspace destroys the given space, and attempts to return all
  935. of its memory back to the system, returning the total number of
  936. bytes freed. After destruction, the results of access to all memory
  937. used by the space become undefined.
  938. */
  939. size_t destroy_mspace(mspace msp);
  940. /*
  941. create_mspace_with_base uses the memory supplied as the initial base
  942. of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this
  943. space is used for bookkeeping, so the capacity must be at least this
  944. large. (Otherwise 0 is returned.) When this initial space is
  945. exhausted, additional memory will be obtained from the system.
  946. Destroying this space will deallocate all additionally allocated
  947. space (if possible) but not the initial base.
  948. */
  949. mspace create_mspace_with_base(void *base, size_t capacity, int locked);
  950. /*
  951. mspace_malloc behaves as malloc, but operates within
  952. the given space.
  953. */
  954. void *mspace_malloc(mspace msp, size_t bytes);
  955. /*
  956. mspace_free behaves as free, but operates within
  957. the given space.
  958. If compiled with FOOTERS==1, mspace_free is not actually needed.
  959. free may be called instead of mspace_free because freed chunks from
  960. any space are handled by their originating spaces.
  961. */
  962. void mspace_free(mspace msp, void *mem);
  963. /*
  964. mspace_realloc behaves as realloc, but operates within
  965. the given space.
  966. If compiled with FOOTERS==1, mspace_realloc is not actually
  967. needed. realloc may be called instead of mspace_realloc because
  968. realloced chunks from any space are handled by their originating
  969. spaces.
  970. */
  971. void *mspace_realloc(mspace msp, void *mem, size_t newsize);
  972. /*
  973. mspace_calloc behaves as calloc, but operates within
  974. the given space.
  975. */
  976. void *mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
  977. /*
  978. mspace_memalign behaves as memalign, but operates within
  979. the given space.
  980. */
  981. void *mspace_memalign(mspace msp, size_t alignment, size_t bytes);
  982. /*
  983. mspace_independent_calloc behaves as independent_calloc, but
  984. operates within the given space.
  985. */
  986. void **mspace_independent_calloc(mspace msp, size_t n_elements,
  987. size_t elem_size, void *chunks[]);
  988. /*
  989. mspace_independent_comalloc behaves as independent_comalloc, but
  990. operates within the given space.
  991. */
  992. void **mspace_independent_comalloc(mspace msp, size_t n_elements,
  993. size_t sizes[], void *chunks[]);
  994. /*
  995. mspace_footprint() returns the number of bytes obtained from the
  996. system for this space.
  997. */
  998. size_t mspace_footprint(mspace msp);
  999. /*
  1000. mspace_max_footprint() returns the peak number of bytes obtained from the
  1001. system for this space.
  1002. */
  1003. size_t mspace_max_footprint(mspace msp);
  1004. #if !NO_MALLINFO
  1005. /*
  1006. mspace_mallinfo behaves as mallinfo, but reports properties of
  1007. the given space.
  1008. */
  1009. struct mallinfo mspace_mallinfo(mspace msp);
  1010. #endif /* NO_MALLINFO */
  1011. /*
  1012. mspace_malloc_stats behaves as malloc_stats, but reports
  1013. properties of the given space.
  1014. */
  1015. void mspace_malloc_stats(mspace msp);
  1016. /*
  1017. mspace_trim behaves as malloc_trim, but
  1018. operates within the given space.
  1019. */
  1020. int mspace_trim(mspace msp, size_t pad);
  1021. /*
  1022. An alias for mallopt.
  1023. */
  1024. int mspace_mallopt(int, int);
  1025. #endif /* MSPACES */
  1026. #ifdef __cplusplus
  1027. }; /* end of extern "C" */
  1028. #endif /* __cplusplus */
  1029. /*
  1030. ========================================================================
  1031. To make a fully customizable malloc.h header file, cut everything
  1032. above this line, put into file malloc.h, edit to suit, and #include it
  1033. on the next line, as well as in programs that use this malloc.
  1034. ========================================================================
  1035. */
  1036. /* #include "malloc.h" */
  1037. /*------------------------------ internal #includes ---------------------- */
  1038. #ifdef _MSC_VER
  1039. #pragma warning( disable : 4146 ) /* no "unsigned" warnings */
  1040. #endif /* _MSC_VER */
  1041. #ifndef LACKS_STDIO_H
  1042. #include <stdio.h> /* for printing in malloc_stats */
  1043. #endif
  1044. #ifndef LACKS_ERRNO_H
  1045. #include <errno.h> /* for MALLOC_FAILURE_ACTION */
  1046. #endif /* LACKS_ERRNO_H */
  1047. #if FOOTERS
  1048. #include <time.h> /* for magic initialization */
  1049. #endif /* FOOTERS */
  1050. #ifndef LACKS_STDLIB_H
  1051. #include <stdlib.h> /* for abort() */
  1052. #endif /* LACKS_STDLIB_H */
  1053. #ifdef DEBUG
  1054. #if ABORT_ON_ASSERT_FAILURE
  1055. #define assert(x) if(!(x)) ABORT
  1056. #else /* ABORT_ON_ASSERT_FAILURE */
  1057. #include <assert.h>
  1058. #endif /* ABORT_ON_ASSERT_FAILURE */
  1059. #else /* DEBUG */
  1060. #define assert(x)
  1061. #endif /* DEBUG */
  1062. #ifndef LACKS_STRING_H
  1063. #include <string.h> /* for memset etc */
  1064. #endif /* LACKS_STRING_H */
  1065. #if USE_BUILTIN_FFS
  1066. #ifndef LACKS_STRINGS_H
  1067. #include <strings.h> /* for ffs */
  1068. #endif /* LACKS_STRINGS_H */
  1069. #endif /* USE_BUILTIN_FFS */
  1070. #if HAVE_MMAP
  1071. #ifndef LACKS_SYS_MMAN_H
  1072. #include <sys/mman.h> /* for mmap */
  1073. #endif /* LACKS_SYS_MMAN_H */
  1074. #ifndef LACKS_FCNTL_H
  1075. #include <fcntl.h>
  1076. #endif /* LACKS_FCNTL_H */
  1077. #endif /* HAVE_MMAP */
  1078. #if HAVE_MORECORE
  1079. #ifndef LACKS_UNISTD_H
  1080. #include <unistd.h> /* for sbrk */
  1081. #else /* LACKS_UNISTD_H */
  1082. #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
  1083. extern void *sbrk(ptrdiff_t);
  1084. #endif /* FreeBSD etc */
  1085. #endif /* LACKS_UNISTD_H */
  1086. #endif /* HAVE_MMAP */
  1087. #ifndef WIN32
  1088. #ifndef malloc_getpagesize
  1089. # ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
  1090. # ifndef _SC_PAGE_SIZE
  1091. # define _SC_PAGE_SIZE _SC_PAGESIZE
  1092. # endif
  1093. # endif
  1094. # ifdef _SC_PAGE_SIZE
  1095. # define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
  1096. # else
  1097. # if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
  1098. extern size_t getpagesize();
  1099. # define malloc_getpagesize getpagesize()
  1100. # else
  1101. # ifdef WIN32 /* use supplied emulation of getpagesize */
  1102. # define malloc_getpagesize getpagesize()
  1103. # else
  1104. # ifndef LACKS_SYS_PARAM_H
  1105. # include <sys/param.h>
  1106. # endif
  1107. # ifdef EXEC_PAGESIZE
  1108. # define malloc_getpagesize EXEC_PAGESIZE
  1109. # else
  1110. # ifdef NBPG
  1111. # ifndef CLSIZE
  1112. # define malloc_getpagesize NBPG
  1113. # else
  1114. # define malloc_getpagesize (NBPG * CLSIZE)
  1115. # endif
  1116. # else
  1117. # ifdef NBPC
  1118. # define malloc_getpagesize NBPC
  1119. # else
  1120. # ifdef PAGESIZE
  1121. # define malloc_getpagesize PAGESIZE
  1122. # else /* just guess */
  1123. # define malloc_getpagesize ((size_t)4096U)
  1124. # endif
  1125. # endif
  1126. # endif
  1127. # endif
  1128. # endif
  1129. # endif
  1130. # endif
  1131. #endif
  1132. #endif
  1133. /* ------------------- size_t and alignment properties -------------------- */
  1134. /* The byte and bit size of a size_t */
  1135. #define SIZE_T_SIZE (sizeof(size_t))
  1136. #define SIZE_T_BITSIZE (sizeof(size_t) << 3)
  1137. /* Some constants coerced to size_t */
  1138. /* Annoying but necessary to avoid errors on some plaftorms */
  1139. #define SIZE_T_ZERO ((size_t)0)
  1140. #define SIZE_T_ONE ((size_t)1)
  1141. #define SIZE_T_TWO ((size_t)2)
  1142. #define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1)
  1143. #define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2)
  1144. #define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)
  1145. #define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U)
  1146. /* The bit mask value corresponding to MALLOC_ALIGNMENT */
  1147. #define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE)
  1148. /* True if address a has acceptable alignment */
  1149. #define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0)
  1150. /* the number of bytes to offset an address to align it */
  1151. #define align_offset(A)\
  1152. ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\
  1153. ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))
  1154. /* -------------------------- MMAP preliminaries ------------------------- */
  1155. /*
  1156. If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and
  1157. checks to fail so compiler optimizer can delete code rather than
  1158. using so many "#if"s.
  1159. */
  1160. /* MORECORE and MMAP must return MFAIL on failure */
  1161. #define MFAIL ((void*)(MAX_SIZE_T))
  1162. #define CMFAIL ((char*)(MFAIL)) /* defined for convenience */
  1163. #if !HAVE_MMAP
  1164. #define IS_MMAPPED_BIT (SIZE_T_ZERO)
  1165. #define USE_MMAP_BIT (SIZE_T_ZERO)
  1166. #define CALL_MMAP(s) MFAIL
  1167. #define CALL_MUNMAP(a, s) (-1)
  1168. #define DIRECT_MMAP(s) MFAIL
  1169. #else /* HAVE_MMAP */
  1170. #define IS_MMAPPED_BIT (SIZE_T_ONE)
  1171. #define USE_MMAP_BIT (SIZE_T_ONE)
  1172. #ifndef WIN32
  1173. #define CALL_MUNMAP(a, s) munmap((a), (s))
  1174. #define MMAP_PROT (PROT_READ|PROT_WRITE)
  1175. #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
  1176. #define MAP_ANONYMOUS MAP_ANON
  1177. #endif /* MAP_ANON */
  1178. #ifdef MAP_ANONYMOUS
  1179. #define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS)
  1180. #define CALL_MMAP(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)
  1181. #else /* MAP_ANONYMOUS */
  1182. /*
  1183. Nearly all versions of mmap support MAP_ANONYMOUS, so the following
  1184. is unlikely to be needed, but is supplied just in case.
  1185. */
  1186. #define MMAP_FLAGS (MAP_PRIVATE)
  1187. static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
  1188. #define CALL_MMAP(s) ((dev_zero_fd < 0) ? \
  1189. (dev_zero_fd = open("/dev/zero", O_RDWR), \
  1190. mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \
  1191. mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0))
  1192. #endif /* MAP_ANONYMOUS */
  1193. #define DIRECT_MMAP(s) CALL_MMAP(s)
  1194. #else /* WIN32 */
  1195. /* Win32 MMAP via VirtualAlloc */
  1196. static void *
  1197. win32mmap(size_t size)
  1198. {
  1199. void *ptr =
  1200. VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
  1201. return (ptr != 0) ? ptr : MFAIL;
  1202. }
  1203. /* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
  1204. static void *
  1205. win32direct_mmap(size_t size)
  1206. {
  1207. void *ptr = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN,
  1208. PAGE_READWRITE);
  1209. return (ptr != 0) ? ptr : MFAIL;
  1210. }
  1211. /* This function supports releasing coalesed segments */
  1212. static int
  1213. win32munmap(void *ptr, size_t size)
  1214. {
  1215. MEMORY_BASIC_INFORMATION minfo;
  1216. char *cptr = ptr;
  1217. while (size) {
  1218. if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)
  1219. return -1;
  1220. if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr ||
  1221. minfo.State != MEM_COMMIT || minfo.RegionSize > size)
  1222. return -1;
  1223. if (VirtualFree(cptr, 0, MEM_RELEASE) == 0)
  1224. return -1;
  1225. cptr += minfo.RegionSize;
  1226. size -= minfo.RegionSize;
  1227. }
  1228. return 0;
  1229. }
  1230. #define CALL_MMAP(s) win32mmap(s)
  1231. #define CALL_MUNMAP(a, s) win32munmap((a), (s))
  1232. #define DIRECT_MMAP(s) win32direct_mmap(s)
  1233. #endif /* WIN32 */
  1234. #endif /* HAVE_MMAP */
  1235. #if HAVE_MMAP && HAVE_MREMAP
  1236. #define CALL_MREMAP(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv))
  1237. #else /* HAVE_MMAP && HAVE_MREMAP */
  1238. #define CALL_MREMAP(addr, osz, nsz, mv) MFAIL
  1239. #endif /* HAVE_MMAP && HAVE_MREMAP */
  1240. #if HAVE_MORECORE
  1241. #define CALL_MORECORE(S) MORECORE(S)
  1242. #else /* HAVE_MORECORE */
  1243. #define CALL_MORECORE(S) MFAIL
  1244. #endif /* HAVE_MORECORE */
  1245. /* mstate bit set if continguous morecore disabled or failed */
  1246. #define USE_NONCONTIGUOUS_BIT (4U)
  1247. /* segment bit set in create_mspace_with_base */
  1248. #define EXTERN_BIT (8U)
  1249. /* --------------------------- Lock preliminaries ------------------------ */
  1250. #if USE_LOCKS
  1251. /*
  1252. When locks are defined, there are up to two global locks:
  1253. * If HAVE_MORECORE, morecore_mutex protects sequences of calls to
  1254. MORECORE. In many cases sys_alloc requires two calls, that should
  1255. not be interleaved with calls by other threads. This does not
  1256. protect against direct calls to MORECORE by other threads not
  1257. using this lock, so there is still code to cope the best we can on
  1258. interference.
  1259. * magic_init_mutex ensures that mparams.magic and other
  1260. unique mparams values are initialized only once.
  1261. */
  1262. #ifndef WIN32
  1263. /* By default use posix locks */
  1264. #include <pthread.h>
  1265. #define MLOCK_T pthread_mutex_t
  1266. #define INITIAL_LOCK(l) pthread_mutex_init(l, NULL)
  1267. #define ACQUIRE_LOCK(l) pthread_mutex_lock(l)
  1268. #define RELEASE_LOCK(l) pthread_mutex_unlock(l)
  1269. #if HAVE_MORECORE
  1270. static MLOCK_T morecore_mutex = PTHREAD_MUTEX_INITIALIZER;
  1271. #endif /* HAVE_MORECORE */
  1272. static MLOCK_T magic_init_mutex = PTHREAD_MUTEX_INITIALIZER;
  1273. #else /* WIN32 */
  1274. /*
  1275. Because lock-protected regions have bounded times, and there
  1276. are no recursive lock calls, we can use simple spinlocks.
  1277. */
  1278. #define MLOCK_T long
  1279. static int
  1280. win32_acquire_lock(MLOCK_T * sl)
  1281. {
  1282. for (;;) {
  1283. #ifdef InterlockedCompareExchangePointer
  1284. if (!InterlockedCompareExchange(sl, 1, 0))
  1285. return 0;
  1286. #else /* Use older void* version */
  1287. if (!InterlockedCompareExchange((void **) sl, (void *) 1, (void *) 0))
  1288. return 0;
  1289. #endif /* InterlockedCompareExchangePointer */
  1290. Sleep(0);
  1291. }
  1292. }
  1293. static void
  1294. win32_release_lock(MLOCK_T * sl)
  1295. {
  1296. InterlockedExchange(sl, 0);
  1297. }
  1298. #define INITIAL_LOCK(l) *(l)=0
  1299. #define ACQUIRE_LOCK(l) win32_acquire_lock(l)
  1300. #define RELEASE_LOCK(l) win32_release_lock(l)
  1301. #if HAVE_MORECORE
  1302. static MLOCK_T morecore_mutex;
  1303. #endif /* HAVE_MORECORE */
  1304. static MLOCK_T magic_init_mutex;
  1305. #endif /* WIN32 */
  1306. #define USE_LOCK_BIT (2U)
  1307. #else /* USE_LOCKS */
  1308. #define USE_LOCK_BIT (0U)
  1309. #define INITIAL_LOCK(l)
  1310. #endif /* USE_LOCKS */
  1311. #if USE_LOCKS && HAVE_MORECORE
  1312. #define ACQUIRE_MORECORE_LOCK() ACQUIRE_LOCK(&morecore_mutex);
  1313. #define RELEASE_MORECORE_LOCK() RELEASE_LOCK(&morecore_mutex);
  1314. #else /* USE_LOCKS && HAVE_MORECORE */
  1315. #define ACQUIRE_MORECORE_LOCK()
  1316. #define RELEASE_MORECORE_LOCK()
  1317. #endif /* USE_LOCKS && HAVE_MORECORE */
  1318. #if USE_LOCKS
  1319. #define ACQUIRE_MAGIC_INIT_LOCK() ACQUIRE_LOCK(&magic_init_mutex);
  1320. #define RELEASE_MAGIC_INIT_LOCK() RELEASE_LOCK(&magic_init_mutex);
  1321. #else /* USE_LOCKS */
  1322. #define ACQUIRE_MAGIC_INIT_LOCK()
  1323. #define RELEASE_MAGIC_INIT_LOCK()
  1324. #endif /* USE_LOCKS */
  1325. /* ----------------------- Chunk representations ------------------------ */
  1326. /*
  1327. (The following includes lightly edited explanations by Colin Plumb.)
  1328. The malloc_chunk declaration below is misleading (but accurate and
  1329. necessary). It declares a "view" into memory allowing access to
  1330. necessary fields at known offsets from a given base.
  1331. Chunks of memory are maintained using a `boundary tag' method as
  1332. originally described by Knuth. (See the paper by Paul Wilson
  1333. ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such
  1334. techniques.) Sizes of free chunks are stored both in the front of
  1335. each chunk and at the end. This makes consolidating fragmented
  1336. chunks into bigger chunks fast. The head fields also hold bits
  1337. representing whether chunks are free or in use.
  1338. Here are some pictures to make it clearer. They are "exploded" to
  1339. show that the state of a chunk can be thought of as extending from
  1340. the high 31 bits of the head field of its header through the
  1341. prev_foot and PINUSE_BIT bit of the following chunk header.
  1342. A chunk that's in use looks like:
  1343. chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1344. | Size of previous chunk (if P = 1) |
  1345. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1346. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
  1347. | Size of this chunk 1| +-+
  1348. mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1349. | |
  1350. +- -+
  1351. | |
  1352. +- -+
  1353. | :
  1354. +- size - sizeof(size_t) available payload bytes -+
  1355. : |
  1356. chunk-> +- -+
  1357. | |
  1358. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1359. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|
  1360. | Size of next chunk (may or may not be in use) | +-+
  1361. mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1362. And if it's free, it looks like this:
  1363. chunk-> +- -+
  1364. | User payload (must be in use, or we would have merged!) |
  1365. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1366. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
  1367. | Size of this chunk 0| +-+
  1368. mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1369. | Next pointer |
  1370. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1371. | Prev pointer |
  1372. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1373. | :
  1374. +- size - sizeof(struct chunk) unused bytes -+
  1375. : |
  1376. chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1377. | Size of this chunk |
  1378. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1379. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|
  1380. | Size of next chunk (must be in use, or we would have merged)| +-+
  1381. mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1382. | :
  1383. +- User payload -+
  1384. : |
  1385. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1386. |0|
  1387. +-+
  1388. Note that since we always merge adjacent free chunks, the chunks
  1389. adjacent to a free chunk must be in use.
  1390. Given a pointer to a chunk (which can be derived trivially from the
  1391. payload pointer) we can, in O(1) time, find out whether the adjacent
  1392. chunks are free, and if so, unlink them from the lists that they
  1393. are on and merge them with the current chunk.
  1394. Chunks always begin on even word boundaries, so the mem portion
  1395. (which is returned to the user) is also on an even word boundary, and
  1396. thus at least double-word aligned.
  1397. The P (PINUSE_BIT) bit, stored in the unused low-order bit of the
  1398. chunk size (which is always a multiple of two words), is an in-use
  1399. bit for the *previous* chunk. If that bit is *clear*, then the
  1400. word before the current chunk size contains the previous chunk
  1401. size, and can be used to find the front of the previous chunk.
  1402. The very first chunk allocated always has this bit set, preventing
  1403. access to non-existent (or non-owned) memory. If pinuse is set for
  1404. any given chunk, then you CANNOT determine the size of the
  1405. previous chunk, and might even get a memory addressing fault when
  1406. trying to do so.
  1407. The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of
  1408. the chunk size redundantly records whether the current chunk is
  1409. inuse. This redundancy enables usage checks within free and realloc,
  1410. and reduces indirection when freeing and consolidating chunks.
  1411. Each freshly allocated chunk must have both cinuse and pinuse set.
  1412. That is, each allocated chunk borders either a previously allocated
  1413. and still in-use chunk, or the base of its memory arena. This is
  1414. ensured by making all allocations from the the `lowest' part of any
  1415. found chunk. Further, no free chunk physically borders another one,
  1416. so each free chunk is known to be preceded and followed by either
  1417. inuse chunks or the ends of memory.
  1418. Note that the `foot' of the current chunk is actually represented
  1419. as the prev_foot of the NEXT chunk. This makes it easier to
  1420. deal with alignments etc but can be very confusing when trying
  1421. to extend or adapt this code.
  1422. The exceptions to all this are
  1423. 1. The special chunk `top' is the top-most available chunk (i.e.,
  1424. the one bordering the end of available memory). It is treated
  1425. specially. Top is never included in any bin, is used only if
  1426. no other chunk is available, and is released back to the
  1427. system if it is very large (see M_TRIM_THRESHOLD). In effect,
  1428. the top chunk is treated as larger (and thus less well
  1429. fitting) than any other available chunk. The top chunk
  1430. doesn't update its trailing size field since there is no next
  1431. contiguous chunk that would have to index off it. However,
  1432. space is still allocated for it (TOP_FOOT_SIZE) to enable
  1433. separation or merging when space is extended.
  1434. 3. Chunks allocated via mmap, which have the lowest-order bit
  1435. (IS_MMAPPED_BIT) set in their prev_foot fields, and do not set
  1436. PINUSE_BIT in their head fields. Because they are allocated
  1437. one-by-one, each must carry its own prev_foot field, which is
  1438. also used to hold the offset this chunk has within its mmapped
  1439. region, which is needed to preserve alignment. Each mmapped
  1440. chunk is trailed by the first two fields of a fake next-chunk
  1441. for sake of usage checks.
  1442. */
  1443. struct malloc_chunk
  1444. {
  1445. size_t prev_foot; /* Size of previous chunk (if free). */
  1446. size_t head; /* Size and inuse bits. */
  1447. struct malloc_chunk *fd; /* double links -- used only if free. */
  1448. struct malloc_chunk *bk;
  1449. };
  1450. typedef struct malloc_chunk mchunk;
  1451. typedef struct malloc_chunk *mchunkptr;
  1452. typedef struct malloc_chunk *sbinptr; /* The type of bins of chunks */
  1453. typedef size_t bindex_t; /* Described below */
  1454. typedef unsigned int binmap_t; /* Described below */
  1455. typedef unsigned int flag_t; /* The type of various bit flag sets */
  1456. /* ------------------- Chunks sizes and alignments ----------------------- */
  1457. #define MCHUNK_SIZE (sizeof(mchunk))
  1458. #if FOOTERS
  1459. #define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
  1460. #else /* FOOTERS */
  1461. #define CHUNK_OVERHEAD (SIZE_T_SIZE)
  1462. #endif /* FOOTERS */
  1463. /* MMapped chunks need a second word of overhead ... */
  1464. #define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
  1465. /* ... and additional padding for fake next-chunk at foot */
  1466. #define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES)
  1467. /* The smallest size we can malloc is an aligned minimal chunk */
  1468. #define MIN_CHUNK_SIZE\
  1469. ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
  1470. /* conversion from malloc headers to user pointers, and back */
  1471. #define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES))
  1472. #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES))
  1473. /* chunk associated with aligned address A */
  1474. #define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A)))
  1475. /* Bounds on request (not chunk) sizes. */
  1476. #define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2)
  1477. #define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)
  1478. /* pad request bytes into a usable size */
  1479. #define pad_request(req) \
  1480. (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
  1481. /* pad request, checking for minimum (but not maximum) */
  1482. #define request2size(req) \
  1483. (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))
  1484. /* ------------------ Operations on head and foot fields ----------------- */
  1485. /*
  1486. The head field of a chunk is or'ed with PINUSE_BIT when previous
  1487. adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in
  1488. use. If the chunk was obtained with mmap, the prev_foot field has
  1489. IS_MMAPPED_BIT set, otherwise holding the offset of the base of the
  1490. mmapped region to the base of the chunk.
  1491. */
  1492. #define PINUSE_BIT (SIZE_T_ONE)
  1493. #define CINUSE_BIT (SIZE_T_TWO)
  1494. #define INUSE_BITS (PINUSE_BIT|CINUSE_BIT)
  1495. /* Head value for fenceposts */
  1496. #define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE)
  1497. /* extraction of fields from head words */
  1498. #define cinuse(p) ((p)->head & CINUSE_BIT)
  1499. #define pinuse(p) ((p)->head & PINUSE_BIT)
  1500. #define chunksize(p) ((p)->head & ~(INUSE_BITS))
  1501. #define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT)
  1502. #define clear_cinuse(p) ((p)->head &= ~CINUSE_BIT)
  1503. /* Treat space at ptr +/- offset as a chunk */
  1504. #define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
  1505. #define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))
  1506. /* Ptr to next or previous physical malloc_chunk. */
  1507. #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~INUSE_BITS)))
  1508. #define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))
  1509. /* extract next chunk's pinuse bit */
  1510. #define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT)
  1511. /* Get/set size at footer */
  1512. #define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot)
  1513. #define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))
  1514. /* Set size, pinuse bit, and foot */
  1515. #define set_size_and_pinuse_of_free_chunk(p, s)\
  1516. ((p)->head = (s|PINUSE_BIT), set_foot(p, s))
  1517. /* Set size, pinuse bit, foot, and clear next pinuse */
  1518. #define set_free_with_pinuse(p, s, n)\
  1519. (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s))
  1520. #define is_mmapped(p)\
  1521. (!((p)->head & PINUSE_BIT) && ((p)->prev_foot & IS_MMAPPED_BIT))
  1522. /* Get the internal overhead associated with chunk p */
  1523. #define overhead_for(p)\
  1524. (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)
  1525. /* Return true if malloced space is not necessarily cleared */
  1526. #if MMAP_CLEARS
  1527. #define calloc_must_clear(p) (!is_mmapped(p))
  1528. #else /* MMAP_CLEARS */
  1529. #define calloc_must_clear(p) (1)
  1530. #endif /* MMAP_CLEARS */
  1531. /* ---------------------- Overlaid data structures ----------------------- */
  1532. /*
  1533. When chunks are not in use, they are treated as nodes of either
  1534. lists or trees.
  1535. "Small" chunks are stored in circular doubly-linked lists, and look
  1536. like this:
  1537. chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1538. | Size of previous chunk |
  1539. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1540. `head:' | Size of chunk, in bytes |P|
  1541. mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1542. | Forward pointer to next chunk in list |
  1543. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1544. | Back pointer to previous chunk in list |
  1545. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1546. | Unused space (may be 0 bytes long) .
  1547. . .
  1548. . |
  1549. nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1550. `foot:' | Size of chunk, in bytes |
  1551. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1552. Larger chunks are kept in a form of bitwise digital trees (aka
  1553. tries) keyed on chunksizes. Because malloc_tree_chunks are only for
  1554. free chunks greater than 256 bytes, their size doesn't impose any
  1555. constraints on user chunk sizes. Each node looks like:
  1556. chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1557. | Size of previous chunk |
  1558. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1559. `head:' | Size of chunk, in bytes |P|
  1560. mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1561. | Forward pointer to next chunk of same size |
  1562. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1563. | Back pointer to previous chunk of same size |
  1564. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1565. | Pointer to left child (child[0]) |
  1566. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1567. | Pointer to right child (child[1]) |
  1568. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1569. | Pointer to parent |
  1570. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1571. | bin index of this chunk |
  1572. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1573. | Unused space .
  1574. . |
  1575. nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1576. `foot:' | Size of chunk, in bytes |
  1577. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1578. Each tree holding treenodes is a tree of unique chunk sizes. Chunks
  1579. of the same size are arranged in a circularly-linked list, with only
  1580. the oldest chunk (the next to be used, in our FIFO ordering)
  1581. actually in the tree. (Tree members are distinguished by a non-null
  1582. parent pointer.) If a chunk with the same size an an existing node
  1583. is inserted, it is linked off the existing node using pointers that
  1584. work in the same way as fd/bk pointers of small chunks.
  1585. Each tree contains a power of 2 sized range of chunk sizes (the
  1586. smallest is 0x100 <= x < 0x180), which is is divided in half at each
  1587. tree level, with the chunks in the smaller half of the range (0x100
  1588. <= x < 0x140 for the top nose) in the left subtree and the larger
  1589. half (0x140 <= x < 0x180) in the right subtree. This is, of course,
  1590. done by inspecting individual bits.
  1591. Using these rules, each node's left subtree contains all smaller
  1592. sizes than its right subtree. However, the node at the root of each
  1593. subtree has no particular ordering relationship to either. (The
  1594. dividing line between the subtree sizes is based on trie relation.)
  1595. If we remove the last chunk of a given size from the interior of the
  1596. tree, we need to replace it with a leaf node. The tree ordering
  1597. rules permit a node to be replaced by any leaf below it.
  1598. The smallest chunk in a tree (a common operation in a best-fit
  1599. allocator) can be found by walking a path to the leftmost leaf in
  1600. the tree. Unlike a usual binary tree, where we follow left child
  1601. pointers until we reach a null, here we follow the right child
  1602. pointer any time the left one is null, until we reach a leaf with
  1603. both child pointers null. The smallest chunk in the tree will be
  1604. somewhere along that path.
  1605. The worst case number of steps to add, find, or remove a node is
  1606. bounded by the number of bits differentiating chunks within
  1607. bins. Under current bin calculations, this ranges from 6 up to 21
  1608. (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case
  1609. is of course much better.
  1610. */
  1611. struct malloc_tree_chunk
  1612. {
  1613. /* The first four fields must be compatible with malloc_chunk */
  1614. size_t prev_foot;
  1615. size_t head;
  1616. struct malloc_tree_chunk *fd;
  1617. struct malloc_tree_chunk *bk;
  1618. struct malloc_tree_chunk *child[2];
  1619. struct malloc_tree_chunk *parent;
  1620. bindex_t index;
  1621. };
  1622. typedef struct malloc_tree_chunk tchunk;
  1623. typedef struct malloc_tree_chunk *tchunkptr;
  1624. typedef struct malloc_tree_chunk *tbinptr; /* The type of bins of trees */
  1625. /* A little helper macro for trees */
  1626. #define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])
  1627. /* ----------------------------- Segments -------------------------------- */
  1628. /*
  1629. Each malloc space may include non-contiguous segments, held in a
  1630. list headed by an embedded malloc_segment record representing the
  1631. top-most space. Segments also include flags holding properties of
  1632. the space. Large chunks that are directly allocated by mmap are not
  1633. included in this list. They are instead independently created and
  1634. destroyed without otherwise keeping track of them.
  1635. Segment management mainly comes into play for spaces allocated by
  1636. MMAP. Any call to MMAP might or might not return memory that is
  1637. adjacent to an existing segment. MORECORE normally contiguously
  1638. extends the current space, so this space is almost always adjacent,
  1639. which is simpler and faster to deal with. (This is why MORECORE is
  1640. used preferentially to MMAP when both are available -- see
  1641. sys_alloc.) When allocating using MMAP, we don't use any of the
  1642. hinting mechanisms (inconsistently) supported in various
  1643. implementations of unix mmap, or distinguish reserving from
  1644. committing memory. Instead, we just ask for space, and exploit
  1645. contiguity when we get it. It is probably possible to do
  1646. better than this on some systems, but no general scheme seems
  1647. to be significantly better.
  1648. Management entails a simpler variant of the consolidation scheme
  1649. used for chunks to reduce fragmentation -- new adjacent memory is
  1650. normally prepended or appended to an existing segment. However,
  1651. there are limitations compared to chunk consolidation that mostly
  1652. reflect the fact that segment processing is relatively infrequent
  1653. (occurring only when getting memory from system) and that we
  1654. don't expect to have huge numbers of segments:
  1655. * Segments are not indexed, so traversal requires linear scans. (It
  1656. would be possible to index these, but is not worth the extra
  1657. overhead and complexity for most programs on most platforms.)
  1658. * New segments are only appended to old ones when holding top-most
  1659. memory; if they cannot be prepended to others, they are held in
  1660. different segments.
  1661. Except for the top-most segment of an mstate, each segment record
  1662. is kept at the tail of its segment. Segments are added by pushing
  1663. segment records onto the list headed by &mstate.seg for the
  1664. containing mstate.
  1665. Segment flags control allocation/merge/deallocation policies:
  1666. * If EXTERN_BIT set, then we did not allocate this segment,
  1667. and so should not try to deallocate or merge with others.
  1668. (This currently holds only for the initial segment passed
  1669. into create_mspace_with_base.)
  1670. * If IS_MMAPPED_BIT set, the segment may be merged with
  1671. other surrounding mmapped segments and trimmed/de-allocated
  1672. using munmap.
  1673. * If neither bit is set, then the segment was obtained using
  1674. MORECORE so can be merged with surrounding MORECORE'd segments
  1675. and deallocated/trimmed using MORECORE with negative arguments.
  1676. */
  1677. struct malloc_segment
  1678. {
  1679. char *base; /* base address */
  1680. size_t size; /* allocated size */
  1681. struct malloc_segment *next; /* ptr to next segment */
  1682. flag_t sflags; /* mmap and extern flag */
  1683. };
  1684. #define is_mmapped_segment(S) ((S)->sflags & IS_MMAPPED_BIT)
  1685. #define is_extern_segment(S) ((S)->sflags & EXTERN_BIT)
  1686. typedef struct malloc_segment msegment;
  1687. typedef struct malloc_segment *msegmentptr;
  1688. /* ---------------------------- malloc_state ----------------------------- */
  1689. /*
  1690. A malloc_state holds all of the bookkeeping for a space.
  1691. The main fields are:
  1692. Top
  1693. The topmost chunk of the currently active segment. Its size is
  1694. cached in topsize. The actual size of topmost space is
  1695. topsize+TOP_FOOT_SIZE, which includes space reserved for adding
  1696. fenceposts and segment records if necessary when getting more
  1697. space from the system. The size at which to autotrim top is
  1698. cached from mparams in trim_check, except that it is disabled if
  1699. an autotrim fails.
  1700. Designated victim (dv)
  1701. This is the preferred chunk for servicing small requests that
  1702. don't have exact fits. It is normally the chunk split off most
  1703. recently to service another small request. Its size is cached in
  1704. dvsize. The link fields of this chunk are not maintained since it
  1705. is not kept in a bin.
  1706. SmallBins
  1707. An array of bin headers for free chunks. These bins hold chunks
  1708. with sizes less than MIN_LARGE_SIZE bytes. Each bin contains
  1709. chunks of all the same size, spaced 8 bytes apart. To simplify
  1710. use in double-linked lists, each bin header acts as a malloc_chunk
  1711. pointing to the real first node, if it exists (else pointing to
  1712. itself). This avoids special-casing for headers. But to avoid
  1713. waste, we allocate only the fd/bk pointers of bins, and then use
  1714. repositioning tricks to treat these as the fields of a chunk.
  1715. TreeBins
  1716. Treebins are pointers to the roots of trees holding a range of
  1717. sizes. There are 2 equally spaced treebins for each power of two
  1718. from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything
  1719. larger.
  1720. Bin maps
  1721. There is one bit map for small bins ("smallmap") and one for
  1722. treebins ("treemap). Each bin sets its bit when non-empty, and
  1723. clears the bit when empty. Bit operations are then used to avoid
  1724. bin-by-bin searching -- nearly all "search" is done without ever
  1725. looking at bins that won't be selected. The bit maps
  1726. conservatively use 32 bits per map word, even if on 64bit system.
  1727. For a good description of some of the bit-based techniques used
  1728. here, see Henry S. Warren Jr's book "Hacker's Delight" (and
  1729. supplement at http://hackersdelight.org/). Many of these are
  1730. intended to reduce the branchiness of paths through malloc etc, as
  1731. well as to reduce the number of memory locations read or written.
  1732. Segments
  1733. A list of segments headed by an embedded malloc_segment record
  1734. representing the initial space.
  1735. Address check support
  1736. The least_addr field is the least address ever obtained from
  1737. MORECORE or MMAP. Attempted frees and reallocs of any address less
  1738. than this are trapped (unless INSECURE is defined).
  1739. Magic tag
  1740. A cross-check field that should always hold same value as mparams.magic.
  1741. Flags
  1742. Bits recording whether to use MMAP, locks, or contiguous MORECORE
  1743. Statistics
  1744. Each space keeps track of current and maximum system memory
  1745. obtained via MORECORE or MMAP.
  1746. Locking
  1747. If USE_LOCKS is defined, the "mutex" lock is acquired and released
  1748. around every public call using this mspace.
  1749. */
  1750. /* Bin types, widths and sizes */
  1751. #define NSMALLBINS (32U)
  1752. #define NTREEBINS (32U)
  1753. #define SMALLBIN_SHIFT (3U)
  1754. #define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT)
  1755. #define TREEBIN_SHIFT (8U)
  1756. #define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT)
  1757. #define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE)
  1758. #define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)
  1759. struct malloc_state
  1760. {
  1761. binmap_t smallmap;
  1762. binmap_t treemap;
  1763. size_t dvsize;
  1764. size_t topsize;
  1765. char *least_addr;
  1766. mchunkptr dv;
  1767. mchunkptr top;
  1768. size_t trim_check;
  1769. size_t magic;
  1770. mchunkptr smallbins[(NSMALLBINS + 1) * 2];
  1771. tbinptr treebins[NTREEBINS];
  1772. size_t footprint;
  1773. size_t max_footprint;
  1774. flag_t mflags;
  1775. #if USE_LOCKS
  1776. MLOCK_T mutex; /* locate lock among fields that rarely change */
  1777. #endif /* USE_LOCKS */
  1778. msegment seg;
  1779. };
  1780. typedef struct malloc_state *mstate;
  1781. /* ------------- Global malloc_state and malloc_params ------------------- */
  1782. /*
  1783. malloc_params holds global properties, including those that can be
  1784. dynamically set using mallopt. There is a single instance, mparams,
  1785. initialized in init_mparams.
  1786. */
  1787. struct malloc_params
  1788. {
  1789. size_t magic;
  1790. size_t page_size;
  1791. size_t granularity;
  1792. size_t mmap_threshold;
  1793. size_t trim_threshold;
  1794. flag_t default_mflags;
  1795. };
  1796. static struct malloc_params mparams;
  1797. /* The global malloc_state used for all non-"mspace" calls */
  1798. static struct malloc_state _gm_;
  1799. #define gm (&_gm_)
  1800. #define is_global(M) ((M) == &_gm_)
  1801. #define is_initialized(M) ((M)->top != 0)
  1802. /* -------------------------- system alloc setup ------------------------- */
  1803. /* Operations on mflags */
  1804. #define use_lock(M) ((M)->mflags & USE_LOCK_BIT)
  1805. #define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT)
  1806. #define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT)
  1807. #define use_mmap(M) ((M)->mflags & USE_MMAP_BIT)
  1808. #define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT)
  1809. #define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT)
  1810. #define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT)
  1811. #define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT)
  1812. #define set_lock(M,L)\
  1813. ((M)->mflags = (L)?\
  1814. ((M)->mflags | USE_LOCK_BIT) :\
  1815. ((M)->mflags & ~USE_LOCK_BIT))
  1816. /* page-align a size */
  1817. #define page_align(S)\
  1818. (((S) + (mparams.page_size)) & ~(mparams.page_size - SIZE_T_ONE))
  1819. /* granularity-align a size */
  1820. #define granularity_align(S)\
  1821. (((S) + (mparams.granularity)) & ~(mparams.granularity - SIZE_T_ONE))
  1822. #define is_page_aligned(S)\
  1823. (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0)
  1824. #define is_granularity_aligned(S)\
  1825. (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0)
  1826. /* True if segment S holds address A */
  1827. #define segment_holds(S, A)\
  1828. ((char*)(A) >= S->base && (char*)(A) < S->base + S->size)
  1829. /* Return segment holding given address */
  1830. static msegmentptr
  1831. segment_holding(mstate m, char *addr)
  1832. {
  1833. msegmentptr sp = &m->seg;
  1834. for (;;) {
  1835. if (addr >= sp->base && addr < sp->base + sp->size)
  1836. return sp;
  1837. if ((sp = sp->next) == 0)
  1838. return 0;
  1839. }
  1840. }
  1841. /* Return true if segment contains a segment link */
  1842. static int
  1843. has_segment_link(mstate m, msegmentptr ss)
  1844. {
  1845. msegmentptr sp = &m->seg;
  1846. for (;;) {
  1847. if ((char *) sp >= ss->base && (char *) sp < ss->base + ss->size)
  1848. return 1;
  1849. if ((sp = sp->next) == 0)
  1850. return 0;
  1851. }
  1852. }
  1853. #ifndef MORECORE_CANNOT_TRIM
  1854. #define should_trim(M,s) ((s) > (M)->trim_check)
  1855. #else /* MORECORE_CANNOT_TRIM */
  1856. #define should_trim(M,s) (0)
  1857. #endif /* MORECORE_CANNOT_TRIM */
  1858. /*
  1859. TOP_FOOT_SIZE is padding at the end of a segment, including space
  1860. that may be needed to place segment records and fenceposts when new
  1861. noncontiguous segments are added.
  1862. */
  1863. #define TOP_FOOT_SIZE\
  1864. (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)
  1865. /* ------------------------------- Hooks -------------------------------- */
  1866. /*
  1867. PREACTION should be defined to return 0 on success, and nonzero on
  1868. failure. If you are not using locking, you can redefine these to do
  1869. anything you like.
  1870. */
  1871. #if USE_LOCKS
  1872. /* Ensure locks are initialized */
  1873. #define GLOBALLY_INITIALIZE() (mparams.page_size == 0 && init_mparams())
  1874. #define PREACTION(M) ((GLOBALLY_INITIALIZE() || use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)
  1875. #define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }
  1876. #else /* USE_LOCKS */
  1877. #ifndef PREACTION
  1878. #define PREACTION(M) (0)
  1879. #endif /* PREACTION */
  1880. #ifndef POSTACTION
  1881. #define POSTACTION(M)
  1882. #endif /* POSTACTION */
  1883. #endif /* USE_LOCKS */
  1884. /*
  1885. CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.
  1886. USAGE_ERROR_ACTION is triggered on detected bad frees and
  1887. reallocs. The argument p is an address that might have triggered the
  1888. fault. It is ignored by the two predefined actions, but might be
  1889. useful in custom actions that try to help diagnose errors.
  1890. */
  1891. #if PROCEED_ON_ERROR
  1892. /* A count of the number of corruption errors causing resets */
  1893. int malloc_corruption_error_count;
  1894. /* default corruption action */
  1895. static void reset_on_error(mstate m);
  1896. #define CORRUPTION_ERROR_ACTION(m) reset_on_error(m)
  1897. #define USAGE_ERROR_ACTION(m, p)
  1898. #else /* PROCEED_ON_ERROR */
  1899. #ifndef CORRUPTION_ERROR_ACTION
  1900. #define CORRUPTION_ERROR_ACTION(m) ABORT
  1901. #endif /* CORRUPTION_ERROR_ACTION */
  1902. #ifndef USAGE_ERROR_ACTION
  1903. #define USAGE_ERROR_ACTION(m,p) ABORT
  1904. #endif /* USAGE_ERROR_ACTION */
  1905. #endif /* PROCEED_ON_ERROR */
  1906. /* -------------------------- Debugging setup ---------------------------- */
  1907. #if ! DEBUG
  1908. #define check_free_chunk(M,P)
  1909. #define check_inuse_chunk(M,P)
  1910. #define check_malloced_chunk(M,P,N)
  1911. #define check_mmapped_chunk(M,P)
  1912. #define check_malloc_state(M)
  1913. #define check_top_chunk(M,P)
  1914. #else /* DEBUG */
  1915. #define check_free_chunk(M,P) do_check_free_chunk(M,P)
  1916. #define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P)
  1917. #define check_top_chunk(M,P) do_check_top_chunk(M,P)
  1918. #define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)
  1919. #define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P)
  1920. #define check_malloc_state(M) do_check_malloc_state(M)
  1921. static void do_check_any_chunk(mstate m, mchunkptr p);
  1922. static void do_check_top_chunk(mstate m, mchunkptr p);
  1923. static void do_check_mmapped_chunk(mstate m, mchunkptr p);
  1924. static void do_check_inuse_chunk(mstate m, mchunkptr p);
  1925. static void do_check_free_chunk(mstate m, mchunkptr p);
  1926. static void do_check_malloced_chunk(mstate m, void *mem, size_t s);
  1927. static void do_check_tree(mstate m, tchunkptr t);
  1928. static void do_check_treebin(mstate m, bindex_t i);
  1929. static void do_check_smallbin(mstate m, bindex_t i);
  1930. static void do_check_malloc_state(mstate m);
  1931. static int bin_find(mstate m, mchunkptr x);
  1932. static size_t traverse_and_check(mstate m);
  1933. #endif /* DEBUG */
  1934. /* ---------------------------- Indexing Bins ---------------------------- */
  1935. #define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)
  1936. #define small_index(s) ((s) >> SMALLBIN_SHIFT)
  1937. #define small_index2size(i) ((i) << SMALLBIN_SHIFT)
  1938. #define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE))
  1939. /* addressing by index. See above about smallbin repositioning */
  1940. #define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))
  1941. #define treebin_at(M,i) (&((M)->treebins[i]))
  1942. /* assign tree index for size S to variable I */
  1943. #if defined(__GNUC__) && defined(i386)
  1944. #define compute_tree_index(S, I)\
  1945. {\
  1946. size_t X = S >> TREEBIN_SHIFT;\
  1947. if (X == 0)\
  1948. I = 0;\
  1949. else if (X > 0xFFFF)\
  1950. I = NTREEBINS-1;\
  1951. else {\
  1952. unsigned int K;\
  1953. __asm__("bsrl %1,%0\n\t" : "=r" (K) : "rm" (X));\
  1954. I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
  1955. }\
  1956. }
  1957. #else /* GNUC */
  1958. #define compute_tree_index(S, I)\
  1959. {\
  1960. size_t X = S >> TREEBIN_SHIFT;\
  1961. if (X == 0)\
  1962. I = 0;\
  1963. else if (X > 0xFFFF)\
  1964. I = NTREEBINS-1;\
  1965. else {\
  1966. unsigned int Y = (unsigned int)X;\
  1967. unsigned int N = ((Y - 0x100) >> 16) & 8;\
  1968. unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\
  1969. N += K;\
  1970. N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\
  1971. K = 14 - N + ((Y <<= K) >> 15);\
  1972. I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\
  1973. }\
  1974. }
  1975. #endif /* GNUC */
  1976. /* Bit representing maximum resolved size in a treebin at i */
  1977. #define bit_for_tree_index(i) \
  1978. (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)
  1979. /* Shift placing maximum resolved bit in a treebin at i as sign bit */
  1980. #define leftshift_for_tree_index(i) \
  1981. ((i == NTREEBINS-1)? 0 : \
  1982. ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))
  1983. /* The size of the smallest chunk held in bin with index i */
  1984. #define minsize_for_tree_index(i) \
  1985. ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \
  1986. (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))
  1987. /* ------------------------ Operations on bin maps ----------------------- */
  1988. /* bit corresponding to given index */
  1989. #define idx2bit(i) ((binmap_t)(1) << (i))
  1990. /* Mark/Clear bits with given index */
  1991. #define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i))
  1992. #define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i))
  1993. #define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i))
  1994. #define mark_treemap(M,i) ((M)->treemap |= idx2bit(i))
  1995. #define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i))
  1996. #define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i))
  1997. /* index corresponding to given bit */
  1998. #if defined(__GNUC__) && defined(i386)
  1999. #define compute_bit2idx(X, I)\
  2000. {\
  2001. unsigned int J;\
  2002. __asm__("bsfl %1,%0\n\t" : "=r" (J) : "rm" (X));\
  2003. I = (bindex_t)J;\
  2004. }
  2005. #else /* GNUC */
  2006. #if USE_BUILTIN_FFS
  2007. #define compute_bit2idx(X, I) I = ffs(X)-1
  2008. #else /* USE_BUILTIN_FFS */
  2009. #define compute_bit2idx(X, I)\
  2010. {\
  2011. unsigned int Y = X - 1;\
  2012. unsigned int K = Y >> (16-4) & 16;\
  2013. unsigned int N = K; Y >>= K;\
  2014. N += K = Y >> (8-3) & 8; Y >>= K;\
  2015. N += K = Y >> (4-2) & 4; Y >>= K;\
  2016. N += K = Y >> (2-1) & 2; Y >>= K;\
  2017. N += K = Y >> (1-0) & 1; Y >>= K;\
  2018. I = (bindex_t)(N + Y);\
  2019. }
  2020. #endif /* USE_BUILTIN_FFS */
  2021. #endif /* GNUC */
  2022. /* isolate the least set bit of a bitmap */
  2023. #define least_bit(x) ((x) & -(x))
  2024. /* mask with all bits to left of least bit of x on */
  2025. #define left_bits(x) ((x<<1) | -(x<<1))
  2026. /* mask with all bits to left of or equal to least bit of x on */
  2027. #define same_or_left_bits(x) ((x) | -(x))
  2028. /* ----------------------- Runtime Check Support ------------------------- */
  2029. /*
  2030. For security, the main invariant is that malloc/free/etc never
  2031. writes to a static address other than malloc_state, unless static
  2032. malloc_state itself has been corrupted, which cannot occur via
  2033. malloc (because of these checks). In essence this means that we
  2034. believe all pointers, sizes, maps etc held in malloc_state, but
  2035. check all of those linked or offsetted from other embedded data
  2036. structures. These checks are interspersed with main code in a way
  2037. that tends to minimize their run-time cost.
  2038. When FOOTERS is defined, in addition to range checking, we also
  2039. verify footer fields of inuse chunks, which can be used guarantee
  2040. that the mstate controlling malloc/free is intact. This is a
  2041. streamlined version of the approach described by William Robertson
  2042. et al in "Run-time Detection of Heap-based Overflows" LISA'03
  2043. http://www.usenix.org/events/lisa03/tech/robertson.html The footer
  2044. of an inuse chunk holds the xor of its mstate and a random seed,
  2045. that is checked upon calls to free() and realloc(). This is
  2046. (probablistically) unguessable from outside the program, but can be
  2047. computed by any code successfully malloc'ing any chunk, so does not
  2048. itself provide protection against code that has already broken
  2049. security through some other means. Unlike Robertson et al, we
  2050. always dynamically check addresses of all offset chunks (previous,
  2051. next, etc). This turns out to be cheaper than relying on hashes.
  2052. */
  2053. #if !INSECURE
  2054. /* Check if address a is at least as high as any from MORECORE or MMAP */
  2055. #define ok_address(M, a) ((char*)(a) >= (M)->least_addr)
  2056. /* Check if address of next chunk n is higher than base chunk p */
  2057. #define ok_next(p, n) ((char*)(p) < (char*)(n))
  2058. /* Check if p has its cinuse bit on */
  2059. #define ok_cinuse(p) cinuse(p)
  2060. /* Check if p has its pinuse bit on */
  2061. #define ok_pinuse(p) pinuse(p)
  2062. #else /* !INSECURE */
  2063. #define ok_address(M, a) (1)
  2064. #define ok_next(b, n) (1)
  2065. #define ok_cinuse(p) (1)
  2066. #define ok_pinuse(p) (1)
  2067. #endif /* !INSECURE */
  2068. #if (FOOTERS && !INSECURE)
  2069. /* Check if (alleged) mstate m has expected magic field */
  2070. #define ok_magic(M) ((M)->magic == mparams.magic)
  2071. #else /* (FOOTERS && !INSECURE) */
  2072. #define ok_magic(M) (1)
  2073. #endif /* (FOOTERS && !INSECURE) */
  2074. /* In gcc, use __builtin_expect to minimize impact of checks */
  2075. #if !INSECURE
  2076. #if defined(__GNUC__) && __GNUC__ >= 3
  2077. #define RTCHECK(e) __builtin_expect(e, 1)
  2078. #else /* GNUC */
  2079. #define RTCHECK(e) (e)
  2080. #endif /* GNUC */
  2081. #else /* !INSECURE */
  2082. #define RTCHECK(e) (1)
  2083. #endif /* !INSECURE */
  2084. /* macros to set up inuse chunks with or without footers */
  2085. #if !FOOTERS
  2086. #define mark_inuse_foot(M,p,s)
  2087. /* Set cinuse bit and pinuse bit of next chunk */
  2088. #define set_inuse(M,p,s)\
  2089. ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
  2090. ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
  2091. /* Set cinuse and pinuse of this chunk and pinuse of next chunk */
  2092. #define set_inuse_and_pinuse(M,p,s)\
  2093. ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
  2094. ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
  2095. /* Set size, cinuse and pinuse bit of this chunk */
  2096. #define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
  2097. ((p)->head = (s|PINUSE_BIT|CINUSE_BIT))
  2098. #else /* FOOTERS */
  2099. /* Set foot of inuse chunk to be xor of mstate and seed */
  2100. #define mark_inuse_foot(M,p,s)\
  2101. (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic))
  2102. #define get_mstate_for(p)\
  2103. ((mstate)(((mchunkptr)((char*)(p) +\
  2104. (chunksize(p))))->prev_foot ^ mparams.magic))
  2105. #define set_inuse(M,p,s)\
  2106. ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
  2107. (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \
  2108. mark_inuse_foot(M,p,s))
  2109. #define set_inuse_and_pinuse(M,p,s)\
  2110. ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
  2111. (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\
  2112. mark_inuse_foot(M,p,s))
  2113. #define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
  2114. ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
  2115. mark_inuse_foot(M, p, s))
  2116. #endif /* !FOOTERS */
  2117. /* ---------------------------- setting mparams -------------------------- */
  2118. /* Initialize mparams */
  2119. static int
  2120. init_mparams(void)
  2121. {
  2122. if (mparams.page_size == 0) {
  2123. size_t s;
  2124. mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
  2125. mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;
  2126. #if MORECORE_CONTIGUOUS
  2127. mparams.default_mflags = USE_LOCK_BIT | USE_MMAP_BIT;
  2128. #else /* MORECORE_CONTIGUOUS */
  2129. mparams.default_mflags =
  2130. USE_LOCK_BIT | USE_MMAP_BIT | USE_NONCONTIGUOUS_BIT;
  2131. #endif /* MORECORE_CONTIGUOUS */
  2132. #if (FOOTERS && !INSECURE)
  2133. {
  2134. #if USE_DEV_RANDOM
  2135. int fd;
  2136. unsigned char buf[sizeof(size_t)];
  2137. /* Try to use /dev/urandom, else fall back on using time */
  2138. if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&
  2139. read(fd, buf, sizeof(buf)) == sizeof(buf)) {
  2140. s = *((size_t *) buf);
  2141. close(fd);
  2142. } else
  2143. #endif /* USE_DEV_RANDOM */
  2144. s = (size_t) (time(0) ^ (size_t) 0x55555555U);
  2145. s |= (size_t) 8U; /* ensure nonzero */
  2146. s &= ~(size_t) 7U; /* improve chances of fault for bad values */
  2147. }
  2148. #else /* (FOOTERS && !INSECURE) */
  2149. s = (size_t) 0x58585858U;
  2150. #endif /* (FOOTERS && !INSECURE) */
  2151. ACQUIRE_MAGIC_INIT_LOCK();
  2152. if (mparams.magic == 0) {
  2153. mparams.magic = s;
  2154. /* Set up lock for main malloc area */
  2155. INITIAL_LOCK(&gm->mutex);
  2156. gm->mflags = mparams.default_mflags;
  2157. }
  2158. RELEASE_MAGIC_INIT_LOCK();
  2159. #ifndef WIN32
  2160. mparams.page_size = malloc_getpagesize;
  2161. mparams.granularity = ((DEFAULT_GRANULARITY != 0) ?
  2162. DEFAULT_GRANULARITY : mparams.page_size);
  2163. #else /* WIN32 */
  2164. {
  2165. SYSTEM_INFO system_info;
  2166. GetSystemInfo(&system_info);
  2167. mparams.page_size = system_info.dwPageSize;
  2168. mparams.granularity = system_info.dwAllocationGranularity;
  2169. }
  2170. #endif /* WIN32 */
  2171. /* Sanity-check configuration:
  2172. size_t must be unsigned and as wide as pointer type.
  2173. ints must be at least 4 bytes.
  2174. alignment must be at least 8.
  2175. Alignment, min chunk size, and page size must all be powers of 2.
  2176. */
  2177. if ((sizeof(size_t) != sizeof(char *)) ||
  2178. (MAX_SIZE_T < MIN_CHUNK_SIZE) ||
  2179. (sizeof(int) < 4) ||
  2180. (MALLOC_ALIGNMENT < (size_t) 8U) ||
  2181. ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - SIZE_T_ONE)) != 0) ||
  2182. ((MCHUNK_SIZE & (MCHUNK_SIZE - SIZE_T_ONE)) != 0) ||
  2183. ((mparams.granularity & (mparams.granularity - SIZE_T_ONE)) != 0)
  2184. || ((mparams.page_size & (mparams.page_size - SIZE_T_ONE)) != 0))
  2185. ABORT;
  2186. }
  2187. return 0;
  2188. }
  2189. /* support for mallopt */
  2190. static int
  2191. change_mparam(int param_number, int value)
  2192. {
  2193. size_t val = (size_t) value;
  2194. init_mparams();
  2195. switch (param_number) {
  2196. case M_TRIM_THRESHOLD:
  2197. mparams.trim_threshold = val;
  2198. return 1;
  2199. case M_GRANULARITY:
  2200. if (val >= mparams.page_size && ((val & (val - 1)) == 0)) {
  2201. mparams.granularity = val;
  2202. return 1;
  2203. } else
  2204. return 0;
  2205. case M_MMAP_THRESHOLD:
  2206. mparams.mmap_threshold = val;
  2207. return 1;
  2208. default:
  2209. return 0;
  2210. }
  2211. }
  2212. #if DEBUG
  2213. /* ------------------------- Debugging Support --------------------------- */
  2214. /* Check properties of any chunk, whether free, inuse, mmapped etc */
  2215. static void
  2216. do_check_any_chunk(mstate m, mchunkptr p)
  2217. {
  2218. assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
  2219. assert(ok_address(m, p));
  2220. }
  2221. /* Check properties of top chunk */
  2222. static void
  2223. do_check_top_chunk(mstate m, mchunkptr p)
  2224. {
  2225. msegmentptr sp = segment_holding(m, (char *) p);
  2226. size_t sz = chunksize(p);
  2227. assert(sp != 0);
  2228. assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
  2229. assert(ok_address(m, p));
  2230. assert(sz == m->topsize);
  2231. assert(sz > 0);
  2232. assert(sz == ((sp->base + sp->size) - (char *) p) - TOP_FOOT_SIZE);
  2233. assert(pinuse(p));
  2234. assert(!next_pinuse(p));
  2235. }
  2236. /* Check properties of (inuse) mmapped chunks */
  2237. static void
  2238. do_check_mmapped_chunk(mstate m, mchunkptr p)
  2239. {
  2240. size_t sz = chunksize(p);
  2241. size_t len = (sz + (p->prev_foot & ~IS_MMAPPED_BIT) + MMAP_FOOT_PAD);
  2242. assert(is_mmapped(p));
  2243. assert(use_mmap(m));
  2244. assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
  2245. assert(ok_address(m, p));
  2246. assert(!is_small(sz));
  2247. assert((len & (mparams.page_size - SIZE_T_ONE)) == 0);
  2248. assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);
  2249. assert(chunk_plus_offset(p, sz + SIZE_T_SIZE)->head == 0);
  2250. }
  2251. /* Check properties of inuse chunks */
  2252. static void
  2253. do_check_inuse_chunk(mstate m, mchunkptr p)
  2254. {
  2255. do_check_any_chunk(m, p);
  2256. assert(cinuse(p));
  2257. assert(next_pinuse(p));
  2258. /* If not pinuse and not mmapped, previous chunk has OK offset */
  2259. assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);
  2260. if (is_mmapped(p))
  2261. do_check_mmapped_chunk(m, p);
  2262. }
  2263. /* Check properties of free chunks */
  2264. static void
  2265. do_check_free_chunk(mstate m, mchunkptr p)
  2266. {
  2267. size_t sz = p->head & ~(PINUSE_BIT | CINUSE_BIT);
  2268. mchunkptr next = chunk_plus_offset(p, sz);
  2269. do_check_any_chunk(m, p);
  2270. assert(!cinuse(p));
  2271. assert(!next_pinuse(p));
  2272. assert(!is_mmapped(p));
  2273. if (p != m->dv && p != m->top) {
  2274. if (sz >= MIN_CHUNK_SIZE) {
  2275. assert((sz & CHUNK_ALIGN_MASK) == 0);
  2276. assert(is_aligned(chunk2mem(p)));
  2277. assert(next->prev_foot == sz);
  2278. assert(pinuse(p));
  2279. assert(next == m->top || cinuse(next));
  2280. assert(p->fd->bk == p);
  2281. assert(p->bk->fd == p);
  2282. } else /* markers are always of size SIZE_T_SIZE */
  2283. assert(sz == SIZE_T_SIZE);
  2284. }
  2285. }
  2286. /* Check properties of malloced chunks at the point they are malloced */
  2287. static void
  2288. do_check_malloced_chunk(mstate m, void *mem, size_t s)
  2289. {
  2290. if (mem != 0) {
  2291. mchunkptr p = mem2chunk(mem);
  2292. size_t sz = p->head & ~(PINUSE_BIT | CINUSE_BIT);
  2293. do_check_inuse_chunk(m, p);
  2294. assert((sz & CHUNK_ALIGN_MASK) == 0);
  2295. assert(sz >= MIN_CHUNK_SIZE);
  2296. assert(sz >= s);
  2297. /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */
  2298. assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));
  2299. }
  2300. }
  2301. /* Check a tree and its subtrees. */
  2302. static void
  2303. do_check_tree(mstate m, tchunkptr t)
  2304. {
  2305. tchunkptr head = 0;
  2306. tchunkptr u = t;
  2307. bindex_t tindex = t->index;
  2308. size_t tsize = chunksize(t);
  2309. bindex_t idx;
  2310. compute_tree_index(tsize, idx);
  2311. assert(tindex == idx);
  2312. assert(tsize >= MIN_LARGE_SIZE);
  2313. assert(tsize >= minsize_for_tree_index(idx));
  2314. assert((idx == NTREEBINS - 1)
  2315. || (tsize < minsize_for_tree_index((idx + 1))));
  2316. do { /* traverse through chain of same-sized nodes */
  2317. do_check_any_chunk(m, ((mchunkptr) u));
  2318. assert(u->index == tindex);
  2319. assert(chunksize(u) == tsize);
  2320. assert(!cinuse(u));
  2321. assert(!next_pinuse(u));
  2322. assert(u->fd->bk == u);
  2323. assert(u->bk->fd == u);
  2324. if (u->parent == 0) {
  2325. assert(u->child[0] == 0);
  2326. assert(u->child[1] == 0);
  2327. } else {
  2328. assert(head == 0); /* only one node on chain has parent */
  2329. head = u;
  2330. assert(u->parent != u);
  2331. assert(u->parent->child[0] == u ||
  2332. u->parent->child[1] == u ||
  2333. *((tbinptr *) (u->parent)) == u);
  2334. if (u->child[0] != 0) {
  2335. assert(u->child[0]->parent == u);
  2336. assert(u->child[0] != u);
  2337. do_check_tree(m, u->child[0]);
  2338. }
  2339. if (u->child[1] != 0) {
  2340. assert(u->child[1]->parent == u);
  2341. assert(u->child[1] != u);
  2342. do_check_tree(m, u->child[1]);
  2343. }
  2344. if (u->child[0] != 0 && u->child[1] != 0) {
  2345. assert(chunksize(u->child[0]) < chunksize(u->child[1]));
  2346. }
  2347. }
  2348. u = u->fd;
  2349. } while (u != t);
  2350. assert(head != 0);
  2351. }
  2352. /* Check all the chunks in a treebin. */
  2353. static void
  2354. do_check_treebin(mstate m, bindex_t i)
  2355. {
  2356. tbinptr *tb = treebin_at(m, i);
  2357. tchunkptr t = *tb;
  2358. int empty = (m->treemap & (1U << i)) == 0;
  2359. if (t == 0)
  2360. assert(empty);
  2361. if (!empty)
  2362. do_check_tree(m, t);
  2363. }
  2364. /* Check all the chunks in a smallbin. */
  2365. static void
  2366. do_check_smallbin(mstate m, bindex_t i)
  2367. {
  2368. sbinptr b = smallbin_at(m, i);
  2369. mchunkptr p = b->bk;
  2370. unsigned int empty = (m->smallmap & (1U << i)) == 0;
  2371. if (p == b)
  2372. assert(empty);
  2373. if (!empty) {
  2374. for (; p != b; p = p->bk) {
  2375. size_t size = chunksize(p);
  2376. mchunkptr q;
  2377. /* each chunk claims to be free */
  2378. do_check_free_chunk(m, p);
  2379. /* chunk belongs in bin */
  2380. assert(small_index(size) == i);
  2381. assert(p->bk == b || chunksize(p->bk) == chunksize(p));
  2382. /* chunk is followed by an inuse chunk */
  2383. q = next_chunk(p);
  2384. if (q->head != FENCEPOST_HEAD)
  2385. do_check_inuse_chunk(m, q);
  2386. }
  2387. }
  2388. }
  2389. /* Find x in a bin. Used in other check functions. */
  2390. static int
  2391. bin_find(mstate m, mchunkptr x)
  2392. {
  2393. size_t size = chunksize(x);
  2394. if (is_small(size)) {
  2395. bindex_t sidx = small_index(size);
  2396. sbinptr b = smallbin_at(m, sidx);
  2397. if (smallmap_is_marked(m, sidx)) {
  2398. mchunkptr p = b;
  2399. do {
  2400. if (p == x)
  2401. return 1;
  2402. } while ((p = p->fd) != b);
  2403. }
  2404. } else {
  2405. bindex_t tidx;
  2406. compute_tree_index(size, tidx);
  2407. if (treemap_is_marked(m, tidx)) {
  2408. tchunkptr t = *treebin_at(m, tidx);
  2409. size_t sizebits = size << leftshift_for_tree_index(tidx);
  2410. while (t != 0 && chunksize(t) != size) {
  2411. t = t->child[(sizebits >> (SIZE_T_BITSIZE - SIZE_T_ONE)) & 1];
  2412. sizebits <<= 1;
  2413. }
  2414. if (t != 0) {
  2415. tchunkptr u = t;
  2416. do {
  2417. if (u == (tchunkptr) x)
  2418. return 1;
  2419. } while ((u = u->fd) != t);
  2420. }
  2421. }
  2422. }
  2423. return 0;
  2424. }
  2425. /* Traverse each chunk and check it; return total */
  2426. static size_t
  2427. traverse_and_check(mstate m)
  2428. {
  2429. size_t sum = 0;
  2430. if (is_initialized(m)) {
  2431. msegmentptr s = &m->seg;
  2432. sum += m->topsize + TOP_FOOT_SIZE;
  2433. while (s != 0) {
  2434. mchunkptr q = align_as_chunk(s->base);
  2435. mchunkptr lastq = 0;
  2436. assert(pinuse(q));
  2437. while (segment_holds(s, q) &&
  2438. q != m->top && q->head != FENCEPOST_HEAD) {
  2439. sum += chunksize(q);
  2440. if (cinuse(q)) {
  2441. assert(!bin_find(m, q));
  2442. do_check_inuse_chunk(m, q);
  2443. } else {
  2444. assert(q == m->dv || bin_find(m, q));
  2445. assert(lastq == 0 || cinuse(lastq)); /* Not 2 consecutive free */
  2446. do_check_free_chunk(m, q);
  2447. }
  2448. lastq = q;
  2449. q = next_chunk(q);
  2450. }
  2451. s = s->next;
  2452. }
  2453. }
  2454. return sum;
  2455. }
  2456. /* Check all properties of malloc_state. */
  2457. static void
  2458. do_check_malloc_state(mstate m)
  2459. {
  2460. bindex_t i;
  2461. size_t total;
  2462. /* check bins */
  2463. for (i = 0; i < NSMALLBINS; ++i)
  2464. do_check_smallbin(m, i);
  2465. for (i = 0; i < NTREEBINS; ++i)
  2466. do_check_treebin(m, i);
  2467. if (m->dvsize != 0) { /* check dv chunk */
  2468. do_check_any_chunk(m, m->dv);
  2469. assert(m->dvsize == chunksize(m->dv));
  2470. assert(m->dvsize >= MIN_CHUNK_SIZE);
  2471. assert(bin_find(m, m->dv) == 0);
  2472. }
  2473. if (m->top != 0) { /* check top chunk */
  2474. do_check_top_chunk(m, m->top);
  2475. assert(m->topsize == chunksize(m->top));
  2476. assert(m->topsize > 0);
  2477. assert(bin_find(m, m->top) == 0);
  2478. }
  2479. total = traverse_and_check(m);
  2480. assert(total <= m->footprint);
  2481. assert(m->footprint <= m->max_footprint);
  2482. }
  2483. #endif /* DEBUG */
  2484. /* ----------------------------- statistics ------------------------------ */
  2485. #if !NO_MALLINFO
  2486. static struct mallinfo
  2487. internal_mallinfo(mstate m)
  2488. {
  2489. struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  2490. if (!PREACTION(m)) {
  2491. check_malloc_state(m);
  2492. if (is_initialized(m)) {
  2493. size_t nfree = SIZE_T_ONE; /* top always free */
  2494. size_t mfree = m->topsize + TOP_FOOT_SIZE;
  2495. size_t sum = mfree;
  2496. msegmentptr s = &m->seg;
  2497. while (s != 0) {
  2498. mchunkptr q = align_as_chunk(s->base);
  2499. while (segment_holds(s, q) &&
  2500. q != m->top && q->head != FENCEPOST_HEAD) {
  2501. size_t sz = chunksize(q);
  2502. sum += sz;
  2503. if (!cinuse(q)) {
  2504. mfree += sz;
  2505. ++nfree;
  2506. }
  2507. q = next_chunk(q);
  2508. }
  2509. s = s->next;
  2510. }
  2511. nm.arena = sum;
  2512. nm.ordblks = nfree;
  2513. nm.hblkhd = m->footprint - sum;
  2514. nm.usmblks = m->max_footprint;
  2515. nm.uordblks = m->footprint - mfree;
  2516. nm.fordblks = mfree;
  2517. nm.keepcost = m->topsize;
  2518. }
  2519. POSTACTION(m);
  2520. }
  2521. return nm;
  2522. }
  2523. #endif /* !NO_MALLINFO */
  2524. static void
  2525. internal_malloc_stats(mstate m)
  2526. {
  2527. if (!PREACTION(m)) {
  2528. size_t maxfp = 0;
  2529. size_t fp = 0;
  2530. size_t used = 0;
  2531. check_malloc_state(m);
  2532. if (is_initialized(m)) {
  2533. msegmentptr s = &m->seg;
  2534. maxfp = m->max_footprint;
  2535. fp = m->footprint;
  2536. used = fp - (m->topsize + TOP_FOOT_SIZE);
  2537. while (s != 0) {
  2538. mchunkptr q = align_as_chunk(s->base);
  2539. while (segment_holds(s, q) &&
  2540. q != m->top && q->head != FENCEPOST_HEAD) {
  2541. if (!cinuse(q))
  2542. used -= chunksize(q);
  2543. q = next_chunk(q);
  2544. }
  2545. s = s->next;
  2546. }
  2547. }
  2548. #ifndef LACKS_STDIO_H
  2549. fprintf(stderr, "max system bytes = %10lu\n",
  2550. (unsigned long) (maxfp));
  2551. fprintf(stderr, "system bytes = %10lu\n", (unsigned long) (fp));
  2552. fprintf(stderr, "in use bytes = %10lu\n", (unsigned long) (used));
  2553. #endif
  2554. POSTACTION(m);
  2555. }
  2556. }
  2557. /* ----------------------- Operations on smallbins ----------------------- */
  2558. /*
  2559. Various forms of linking and unlinking are defined as macros. Even
  2560. the ones for trees, which are very long but have very short typical
  2561. paths. This is ugly but reduces reliance on inlining support of
  2562. compilers.
  2563. */
  2564. /* Link a free chunk into a smallbin */
  2565. #define insert_small_chunk(M, P, S) {\
  2566. bindex_t I = small_index(S);\
  2567. mchunkptr B = smallbin_at(M, I);\
  2568. mchunkptr F = B;\
  2569. assert(S >= MIN_CHUNK_SIZE);\
  2570. if (!smallmap_is_marked(M, I))\
  2571. mark_smallmap(M, I);\
  2572. else if (RTCHECK(ok_address(M, B->fd)))\
  2573. F = B->fd;\
  2574. else {\
  2575. CORRUPTION_ERROR_ACTION(M);\
  2576. }\
  2577. B->fd = P;\
  2578. F->bk = P;\
  2579. P->fd = F;\
  2580. P->bk = B;\
  2581. }
  2582. /* Unlink a chunk from a smallbin */
  2583. #define unlink_small_chunk(M, P, S) {\
  2584. mchunkptr F = P->fd;\
  2585. mchunkptr B = P->bk;\
  2586. bindex_t I = small_index(S);\
  2587. assert(P != B);\
  2588. assert(P != F);\
  2589. assert(chunksize(P) == small_index2size(I));\
  2590. if (F == B)\
  2591. clear_smallmap(M, I);\
  2592. else if (RTCHECK((F == smallbin_at(M,I) || ok_address(M, F)) &&\
  2593. (B == smallbin_at(M,I) || ok_address(M, B)))) {\
  2594. F->bk = B;\
  2595. B->fd = F;\
  2596. }\
  2597. else {\
  2598. CORRUPTION_ERROR_ACTION(M);\
  2599. }\
  2600. }
  2601. /* Unlink the first chunk from a smallbin */
  2602. #define unlink_first_small_chunk(M, B, P, I) {\
  2603. mchunkptr F = P->fd;\
  2604. assert(P != B);\
  2605. assert(P != F);\
  2606. assert(chunksize(P) == small_index2size(I));\
  2607. if (B == F)\
  2608. clear_smallmap(M, I);\
  2609. else if (RTCHECK(ok_address(M, F))) {\
  2610. B->fd = F;\
  2611. F->bk = B;\
  2612. }\
  2613. else {\
  2614. CORRUPTION_ERROR_ACTION(M);\
  2615. }\
  2616. }
  2617. /* Replace dv node, binning the old one */
  2618. /* Used only when dvsize known to be small */
  2619. #define replace_dv(M, P, S) {\
  2620. size_t DVS = M->dvsize;\
  2621. if (DVS != 0) {\
  2622. mchunkptr DV = M->dv;\
  2623. assert(is_small(DVS));\
  2624. insert_small_chunk(M, DV, DVS);\
  2625. }\
  2626. M->dvsize = S;\
  2627. M->dv = P;\
  2628. }
  2629. /* ------------------------- Operations on trees ------------------------- */
  2630. /* Insert chunk into tree */
  2631. #define insert_large_chunk(M, X, S) {\
  2632. tbinptr* H;\
  2633. bindex_t I;\
  2634. compute_tree_index(S, I);\
  2635. H = treebin_at(M, I);\
  2636. X->index = I;\
  2637. X->child[0] = X->child[1] = 0;\
  2638. if (!treemap_is_marked(M, I)) {\
  2639. mark_treemap(M, I);\
  2640. *H = X;\
  2641. X->parent = (tchunkptr)H;\
  2642. X->fd = X->bk = X;\
  2643. }\
  2644. else {\
  2645. tchunkptr T = *H;\
  2646. size_t K = S << leftshift_for_tree_index(I);\
  2647. for (;;) {\
  2648. if (chunksize(T) != S) {\
  2649. tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\
  2650. K <<= 1;\
  2651. if (*C != 0)\
  2652. T = *C;\
  2653. else if (RTCHECK(ok_address(M, C))) {\
  2654. *C = X;\
  2655. X->parent = T;\
  2656. X->fd = X->bk = X;\
  2657. break;\
  2658. }\
  2659. else {\
  2660. CORRUPTION_ERROR_ACTION(M);\
  2661. break;\
  2662. }\
  2663. }\
  2664. else {\
  2665. tchunkptr F = T->fd;\
  2666. if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\
  2667. T->fd = F->bk = X;\
  2668. X->fd = F;\
  2669. X->bk = T;\
  2670. X->parent = 0;\
  2671. break;\
  2672. }\
  2673. else {\
  2674. CORRUPTION_ERROR_ACTION(M);\
  2675. break;\
  2676. }\
  2677. }\
  2678. }\
  2679. }\
  2680. }
  2681. /*
  2682. Unlink steps:
  2683. 1. If x is a chained node, unlink it from its same-sized fd/bk links
  2684. and choose its bk node as its replacement.
  2685. 2. If x was the last node of its size, but not a leaf node, it must
  2686. be replaced with a leaf node (not merely one with an open left or
  2687. right), to make sure that lefts and rights of descendents
  2688. correspond properly to bit masks. We use the rightmost descendent
  2689. of x. We could use any other leaf, but this is easy to locate and
  2690. tends to counteract removal of leftmosts elsewhere, and so keeps
  2691. paths shorter than minimally guaranteed. This doesn't loop much
  2692. because on average a node in a tree is near the bottom.
  2693. 3. If x is the base of a chain (i.e., has parent links) relink
  2694. x's parent and children to x's replacement (or null if none).
  2695. */
  2696. #define unlink_large_chunk(M, X) {\
  2697. tchunkptr XP = X->parent;\
  2698. tchunkptr R;\
  2699. if (X->bk != X) {\
  2700. tchunkptr F = X->fd;\
  2701. R = X->bk;\
  2702. if (RTCHECK(ok_address(M, F))) {\
  2703. F->bk = R;\
  2704. R->fd = F;\
  2705. }\
  2706. else {\
  2707. CORRUPTION_ERROR_ACTION(M);\
  2708. }\
  2709. }\
  2710. else {\
  2711. tchunkptr* RP;\
  2712. if (((R = *(RP = &(X->child[1]))) != 0) ||\
  2713. ((R = *(RP = &(X->child[0]))) != 0)) {\
  2714. tchunkptr* CP;\
  2715. while ((*(CP = &(R->child[1])) != 0) ||\
  2716. (*(CP = &(R->child[0])) != 0)) {\
  2717. R = *(RP = CP);\
  2718. }\
  2719. if (RTCHECK(ok_address(M, RP)))\
  2720. *RP = 0;\
  2721. else {\
  2722. CORRUPTION_ERROR_ACTION(M);\
  2723. }\
  2724. }\
  2725. }\
  2726. if (XP != 0) {\
  2727. tbinptr* H = treebin_at(M, X->index);\
  2728. if (X == *H) {\
  2729. if ((*H = R) == 0) \
  2730. clear_treemap(M, X->index);\
  2731. }\
  2732. else if (RTCHECK(ok_address(M, XP))) {\
  2733. if (XP->child[0] == X) \
  2734. XP->child[0] = R;\
  2735. else \
  2736. XP->child[1] = R;\
  2737. }\
  2738. else\
  2739. CORRUPTION_ERROR_ACTION(M);\
  2740. if (R != 0) {\
  2741. if (RTCHECK(ok_address(M, R))) {\
  2742. tchunkptr C0, C1;\
  2743. R->parent = XP;\
  2744. if ((C0 = X->child[0]) != 0) {\
  2745. if (RTCHECK(ok_address(M, C0))) {\
  2746. R->child[0] = C0;\
  2747. C0->parent = R;\
  2748. }\
  2749. else\
  2750. CORRUPTION_ERROR_ACTION(M);\
  2751. }\
  2752. if ((C1 = X->child[1]) != 0) {\
  2753. if (RTCHECK(ok_address(M, C1))) {\
  2754. R->child[1] = C1;\
  2755. C1->parent = R;\
  2756. }\
  2757. else\
  2758. CORRUPTION_ERROR_ACTION(M);\
  2759. }\
  2760. }\
  2761. else\
  2762. CORRUPTION_ERROR_ACTION(M);\
  2763. }\
  2764. }\
  2765. }
  2766. /* Relays to large vs small bin operations */
  2767. #define insert_chunk(M, P, S)\
  2768. if (is_small(S)) insert_small_chunk(M, P, S)\
  2769. else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); }
  2770. #define unlink_chunk(M, P, S)\
  2771. if (is_small(S)) unlink_small_chunk(M, P, S)\
  2772. else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); }
  2773. /* Relays to internal calls to malloc/free from realloc, memalign etc */
  2774. #if ONLY_MSPACES
  2775. #define internal_malloc(m, b) mspace_malloc(m, b)
  2776. #define internal_free(m, mem) mspace_free(m,mem);
  2777. #else /* ONLY_MSPACES */
  2778. #if MSPACES
  2779. #define internal_malloc(m, b)\
  2780. (m == gm)? dlmalloc(b) : mspace_malloc(m, b)
  2781. #define internal_free(m, mem)\
  2782. if (m == gm) dlfree(mem); else mspace_free(m,mem);
  2783. #else /* MSPACES */
  2784. #define internal_malloc(m, b) dlmalloc(b)
  2785. #define internal_free(m, mem) dlfree(mem)
  2786. #endif /* MSPACES */
  2787. #endif /* ONLY_MSPACES */
  2788. /* ----------------------- Direct-mmapping chunks ----------------------- */
  2789. /*
  2790. Directly mmapped chunks are set up with an offset to the start of
  2791. the mmapped region stored in the prev_foot field of the chunk. This
  2792. allows reconstruction of the required argument to MUNMAP when freed,
  2793. and also allows adjustment of the returned chunk to meet alignment
  2794. requirements (especially in memalign). There is also enough space
  2795. allocated to hold a fake next chunk of size SIZE_T_SIZE to maintain
  2796. the PINUSE bit so frees can be checked.
  2797. */
  2798. /* Malloc using mmap */
  2799. static void *
  2800. mmap_alloc(mstate m, size_t nb)
  2801. {
  2802. size_t mmsize =
  2803. granularity_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
  2804. if (mmsize > nb) { /* Check for wrap around 0 */
  2805. char *mm = (char *) (DIRECT_MMAP(mmsize));
  2806. if (mm != CMFAIL) {
  2807. size_t offset = align_offset(chunk2mem(mm));
  2808. size_t psize = mmsize - offset - MMAP_FOOT_PAD;
  2809. mchunkptr p = (mchunkptr) (mm + offset);
  2810. p->prev_foot = offset | IS_MMAPPED_BIT;
  2811. (p)->head = (psize | CINUSE_BIT);
  2812. mark_inuse_foot(m, p, psize);
  2813. chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;
  2814. chunk_plus_offset(p, psize + SIZE_T_SIZE)->head = 0;
  2815. if (mm < m->least_addr)
  2816. m->least_addr = mm;
  2817. if ((m->footprint += mmsize) > m->max_footprint)
  2818. m->max_footprint = m->footprint;
  2819. assert(is_aligned(chunk2mem(p)));
  2820. check_mmapped_chunk(m, p);
  2821. return chunk2mem(p);
  2822. }
  2823. }
  2824. return 0;
  2825. }
  2826. /* Realloc using mmap */
  2827. static mchunkptr
  2828. mmap_resize(mstate m, mchunkptr oldp, size_t nb)
  2829. {
  2830. size_t oldsize = chunksize(oldp);
  2831. if (is_small(nb)) /* Can't shrink mmap regions below small size */
  2832. return 0;
  2833. /* Keep old chunk if big enough but not too big */
  2834. if (oldsize >= nb + SIZE_T_SIZE &&
  2835. (oldsize - nb) <= (mparams.granularity << 1))
  2836. return oldp;
  2837. else {
  2838. size_t offset = oldp->prev_foot & ~IS_MMAPPED_BIT;
  2839. size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD;
  2840. size_t newmmsize = granularity_align(nb + SIX_SIZE_T_SIZES +
  2841. CHUNK_ALIGN_MASK);
  2842. char *cp = (char *) CALL_MREMAP((char *) oldp - offset,
  2843. oldmmsize, newmmsize, 1);
  2844. if (cp != CMFAIL) {
  2845. mchunkptr newp = (mchunkptr) (cp + offset);
  2846. size_t psize = newmmsize - offset - MMAP_FOOT_PAD;
  2847. newp->head = (psize | CINUSE_BIT);
  2848. mark_inuse_foot(m, newp, psize);
  2849. chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD;
  2850. chunk_plus_offset(newp, psize + SIZE_T_SIZE)->head = 0;
  2851. if (cp < m->least_addr)
  2852. m->least_addr = cp;
  2853. if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint)
  2854. m->max_footprint = m->footprint;
  2855. check_mmapped_chunk(m, newp);
  2856. return newp;
  2857. }
  2858. }
  2859. return 0;
  2860. }
  2861. /* -------------------------- mspace management -------------------------- */
  2862. /* Initialize top chunk and its size */
  2863. static void
  2864. init_top(mstate m, mchunkptr p, size_t psize)
  2865. {
  2866. /* Ensure alignment */
  2867. size_t offset = align_offset(chunk2mem(p));
  2868. p = (mchunkptr) ((char *) p + offset);
  2869. psize -= offset;
  2870. m->top = p;
  2871. m->topsize = psize;
  2872. p->head = psize | PINUSE_BIT;
  2873. /* set size of fake trailing chunk holding overhead space only once */
  2874. chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE;
  2875. m->trim_check = mparams.trim_threshold; /* reset on each update */
  2876. }
  2877. /* Initialize bins for a new mstate that is otherwise zeroed out */
  2878. static void
  2879. init_bins(mstate m)
  2880. {
  2881. /* Establish circular links for smallbins */
  2882. bindex_t i;
  2883. for (i = 0; i < NSMALLBINS; ++i) {
  2884. sbinptr bin = smallbin_at(m, i);
  2885. bin->fd = bin->bk = bin;
  2886. }
  2887. }
  2888. #if PROCEED_ON_ERROR
  2889. /* default corruption action */
  2890. static void
  2891. reset_on_error(mstate m)
  2892. {
  2893. int i;
  2894. ++malloc_corruption_error_count;
  2895. /* Reinitialize fields to forget about all memory */
  2896. m->smallbins = m->treebins = 0;
  2897. m->dvsize = m->topsize = 0;
  2898. m->seg.base = 0;
  2899. m->seg.size = 0;
  2900. m->seg.next = 0;
  2901. m->top = m->dv = 0;
  2902. for (i = 0; i < NTREEBINS; ++i)
  2903. *treebin_at(m, i) = 0;
  2904. init_bins(m);
  2905. }
  2906. #endif /* PROCEED_ON_ERROR */
  2907. /* Allocate chunk and prepend remainder with chunk in successor base. */
  2908. static void *
  2909. prepend_alloc(mstate m, char *newbase, char *oldbase, size_t nb)
  2910. {
  2911. mchunkptr p = align_as_chunk(newbase);
  2912. mchunkptr oldfirst = align_as_chunk(oldbase);
  2913. size_t psize = (char *) oldfirst - (char *) p;
  2914. mchunkptr q = chunk_plus_offset(p, nb);
  2915. size_t qsize = psize - nb;
  2916. set_size_and_pinuse_of_inuse_chunk(m, p, nb);
  2917. assert((char *) oldfirst > (char *) q);
  2918. assert(pinuse(oldfirst));
  2919. assert(qsize >= MIN_CHUNK_SIZE);
  2920. /* consolidate remainder with first chunk of old base */
  2921. if (oldfirst == m->top) {
  2922. size_t tsize = m->topsize += qsize;
  2923. m->top = q;
  2924. q->head = tsize | PINUSE_BIT;
  2925. check_top_chunk(m, q);
  2926. } else if (oldfirst == m->dv) {
  2927. size_t dsize = m->dvsize += qsize;
  2928. m->dv = q;
  2929. set_size_and_pinuse_of_free_chunk(q, dsize);
  2930. } else {
  2931. if (!cinuse(oldfirst)) {
  2932. size_t nsize = chunksize(oldfirst);
  2933. unlink_chunk(m, oldfirst, nsize);
  2934. oldfirst = chunk_plus_offset(oldfirst, nsize);
  2935. qsize += nsize;
  2936. }
  2937. set_free_with_pinuse(q, qsize, oldfirst);
  2938. insert_chunk(m, q, qsize);
  2939. check_free_chunk(m, q);
  2940. }
  2941. check_malloced_chunk(m, chunk2mem(p), nb);
  2942. return chunk2mem(p);
  2943. }
  2944. /* Add a segment to hold a new noncontiguous region */
  2945. static void
  2946. add_segment(mstate m, char *tbase, size_t tsize, flag_t mmapped)
  2947. {
  2948. /* Determine locations and sizes of segment, fenceposts, old top */
  2949. char *old_top = (char *) m->top;
  2950. msegmentptr oldsp = segment_holding(m, old_top);
  2951. char *old_end = oldsp->base + oldsp->size;
  2952. size_t ssize = pad_request(sizeof(struct malloc_segment));
  2953. char *rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
  2954. size_t offset = align_offset(chunk2mem(rawsp));
  2955. char *asp = rawsp + offset;
  2956. char *csp = (asp < (old_top + MIN_CHUNK_SIZE)) ? old_top : asp;
  2957. mchunkptr sp = (mchunkptr) csp;
  2958. msegmentptr ss = (msegmentptr) (chunk2mem(sp));
  2959. mchunkptr tnext = chunk_plus_offset(sp, ssize);
  2960. mchunkptr p = tnext;
  2961. int nfences = 0;
  2962. /* reset top to new space */
  2963. init_top(m, (mchunkptr) tbase, tsize - TOP_FOOT_SIZE);
  2964. /* Set up segment record */
  2965. assert(is_aligned(ss));
  2966. set_size_and_pinuse_of_inuse_chunk(m, sp, ssize);
  2967. *ss = m->seg; /* Push current record */
  2968. m->seg.base = tbase;
  2969. m->seg.size = tsize;
  2970. m->seg.sflags = mmapped;
  2971. m->seg.next = ss;
  2972. /* Insert trailing fenceposts */
  2973. for (;;) {
  2974. mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE);
  2975. p->head = FENCEPOST_HEAD;
  2976. ++nfences;
  2977. if ((char *) (&(nextp->head)) < old_end)
  2978. p = nextp;
  2979. else
  2980. break;
  2981. }
  2982. assert(nfences >= 2);
  2983. /* Insert the rest of old top into a bin as an ordinary free chunk */
  2984. if (csp != old_top) {
  2985. mchunkptr q = (mchunkptr) old_top;
  2986. size_t psize = csp - old_top;
  2987. mchunkptr tn = chunk_plus_offset(q, psize);
  2988. set_free_with_pinuse(q, psize, tn);
  2989. insert_chunk(m, q, psize);
  2990. }
  2991. check_top_chunk(m, m->top);
  2992. }
  2993. /* -------------------------- System allocation -------------------------- */
  2994. /* Get memory from system using MORECORE or MMAP */
  2995. static void *
  2996. sys_alloc(mstate m, size_t nb)
  2997. {
  2998. char *tbase = CMFAIL;
  2999. size_t tsize = 0;
  3000. flag_t mmap_flag = 0;
  3001. init_mparams();
  3002. /* Directly map large chunks */
  3003. if (use_mmap(m) && nb >= mparams.mmap_threshold) {
  3004. void *mem = mmap_alloc(m, nb);
  3005. if (mem != 0)
  3006. return mem;
  3007. }
  3008. /*
  3009. Try getting memory in any of three ways (in most-preferred to
  3010. least-preferred order):
  3011. 1. A call to MORECORE that can normally contiguously extend memory.
  3012. (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or
  3013. or main space is mmapped or a previous contiguous call failed)
  3014. 2. A call to MMAP new space (disabled if not HAVE_MMAP).
  3015. Note that under the default settings, if MORECORE is unable to
  3016. fulfill a request, and HAVE_MMAP is true, then mmap is
  3017. used as a noncontiguous system allocator. This is a useful backup
  3018. strategy for systems with holes in address spaces -- in this case
  3019. sbrk cannot contiguously expand the heap, but mmap may be able to
  3020. find space.
  3021. 3. A call to MORECORE that cannot usually contiguously extend memory.
  3022. (disabled if not HAVE_MORECORE)
  3023. */
  3024. if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) {
  3025. char *br = CMFAIL;
  3026. msegmentptr ss =
  3027. (m->top == 0) ? 0 : segment_holding(m, (char *) m->top);
  3028. size_t asize = 0;
  3029. ACQUIRE_MORECORE_LOCK();
  3030. if (ss == 0) { /* First time through or recovery */
  3031. char *base = (char *) CALL_MORECORE(0);
  3032. if (base != CMFAIL) {
  3033. asize =
  3034. granularity_align(nb + TOP_FOOT_SIZE + MALLOC_ALIGNMENT +
  3035. SIZE_T_ONE);
  3036. /* Adjust to end on a page boundary */
  3037. if (!is_page_aligned(base))
  3038. asize += (page_align((size_t) base) - (size_t) base);
  3039. /* Can't call MORECORE if size is negative when treated as signed */
  3040. if (asize < HALF_MAX_SIZE_T &&
  3041. (br = (char *) (CALL_MORECORE(asize))) == base) {
  3042. tbase = base;
  3043. tsize = asize;
  3044. }
  3045. }
  3046. } else {
  3047. /* Subtract out existing available top space from MORECORE request. */
  3048. asize =
  3049. granularity_align(nb - m->topsize + TOP_FOOT_SIZE +
  3050. MALLOC_ALIGNMENT + SIZE_T_ONE);
  3051. /* Use mem here only if it did continuously extend old space */
  3052. if (asize < HALF_MAX_SIZE_T &&
  3053. (br =
  3054. (char *) (CALL_MORECORE(asize))) == ss->base + ss->size) {
  3055. tbase = br;
  3056. tsize = asize;
  3057. }
  3058. }
  3059. if (tbase == CMFAIL) { /* Cope with partial failure */
  3060. if (br != CMFAIL) { /* Try to use/extend the space we did get */
  3061. if (asize < HALF_MAX_SIZE_T &&
  3062. asize < nb + TOP_FOOT_SIZE + SIZE_T_ONE) {
  3063. size_t esize =
  3064. granularity_align(nb + TOP_FOOT_SIZE +
  3065. MALLOC_ALIGNMENT + SIZE_T_ONE -
  3066. asize);
  3067. if (esize < HALF_MAX_SIZE_T) {
  3068. char *end = (char *) CALL_MORECORE(esize);
  3069. if (end != CMFAIL)
  3070. asize += esize;
  3071. else { /* Can't use; try to release */
  3072. end = (char *) CALL_MORECORE(-asize);
  3073. br = CMFAIL;
  3074. }
  3075. }
  3076. }
  3077. }
  3078. if (br != CMFAIL) { /* Use the space we did get */
  3079. tbase = br;
  3080. tsize = asize;
  3081. } else
  3082. disable_contiguous(m); /* Don't try contiguous path in the future */
  3083. }
  3084. RELEASE_MORECORE_LOCK();
  3085. }
  3086. if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */
  3087. size_t req = nb + TOP_FOOT_SIZE + MALLOC_ALIGNMENT + SIZE_T_ONE;
  3088. size_t rsize = granularity_align(req);
  3089. if (rsize > nb) { /* Fail if wraps around zero */
  3090. char *mp = (char *) (CALL_MMAP(rsize));
  3091. if (mp != CMFAIL) {
  3092. tbase = mp;
  3093. tsize = rsize;
  3094. mmap_flag = IS_MMAPPED_BIT;
  3095. }
  3096. }
  3097. }
  3098. if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */
  3099. size_t asize =
  3100. granularity_align(nb + TOP_FOOT_SIZE + MALLOC_ALIGNMENT +
  3101. SIZE_T_ONE);
  3102. if (asize < HALF_MAX_SIZE_T) {
  3103. char *br = CMFAIL;
  3104. char *end = CMFAIL;
  3105. ACQUIRE_MORECORE_LOCK();
  3106. br = (char *) (CALL_MORECORE(asize));
  3107. end = (char *) (CALL_MORECORE(0));
  3108. RELEASE_MORECORE_LOCK();
  3109. if (br != CMFAIL && end != CMFAIL && br < end) {
  3110. size_t ssize = end - br;
  3111. if (ssize > nb + TOP_FOOT_SIZE) {
  3112. tbase = br;
  3113. tsize = ssize;
  3114. }
  3115. }
  3116. }
  3117. }
  3118. if (tbase != CMFAIL) {
  3119. if ((m->footprint += tsize) > m->max_footprint)
  3120. m->max_footprint = m->footprint;
  3121. if (!is_initialized(m)) { /* first-time initialization */
  3122. m->seg.base = m->least_addr = tbase;
  3123. m->seg.size = tsize;
  3124. m->seg.sflags = mmap_flag;
  3125. m->magic = mparams.magic;
  3126. init_bins(m);
  3127. if (is_global(m))
  3128. init_top(m, (mchunkptr) tbase, tsize - TOP_FOOT_SIZE);
  3129. else {
  3130. /* Offset top by embedded malloc_state */
  3131. mchunkptr mn = next_chunk(mem2chunk(m));
  3132. init_top(m, mn,
  3133. (size_t) ((tbase + tsize) - (char *) mn) -
  3134. TOP_FOOT_SIZE);
  3135. }
  3136. }
  3137. else {
  3138. /* Try to merge with an existing segment */
  3139. msegmentptr sp = &m->seg;
  3140. while (sp != 0 && tbase != sp->base + sp->size)
  3141. sp = sp->next;
  3142. if (sp != 0 && !is_extern_segment(sp) && (sp->sflags & IS_MMAPPED_BIT) == mmap_flag && segment_holds(sp, m->top)) { /* append */
  3143. sp->size += tsize;
  3144. init_top(m, m->top, m->topsize + tsize);
  3145. } else {
  3146. if (tbase < m->least_addr)
  3147. m->least_addr = tbase;
  3148. sp = &m->seg;
  3149. while (sp != 0 && sp->base != tbase + tsize)
  3150. sp = sp->next;
  3151. if (sp != 0 &&
  3152. !is_extern_segment(sp) &&
  3153. (sp->sflags & IS_MMAPPED_BIT) == mmap_flag) {
  3154. char *oldbase = sp->base;
  3155. sp->base = tbase;
  3156. sp->size += tsize;
  3157. return prepend_alloc(m, tbase, oldbase, nb);
  3158. } else
  3159. add_segment(m, tbase, tsize, mmap_flag);
  3160. }
  3161. }
  3162. if (nb < m->topsize) { /* Allocate from new or extended top space */
  3163. size_t rsize = m->topsize -= nb;
  3164. mchunkptr p = m->top;
  3165. mchunkptr r = m->top = chunk_plus_offset(p, nb);
  3166. r->head = rsize | PINUSE_BIT;
  3167. set_size_and_pinuse_of_inuse_chunk(m, p, nb);
  3168. check_top_chunk(m, m->top);
  3169. check_malloced_chunk(m, chunk2mem(p), nb);
  3170. return chunk2mem(p);
  3171. }
  3172. }
  3173. MALLOC_FAILURE_ACTION;
  3174. return 0;
  3175. }
  3176. /* ----------------------- system deallocation -------------------------- */
  3177. /* Unmap and unlink any mmapped segments that don't contain used chunks */
  3178. static size_t
  3179. release_unused_segments(mstate m)
  3180. {
  3181. size_t released = 0;
  3182. msegmentptr pred = &m->seg;
  3183. msegmentptr sp = pred->next;
  3184. while (sp != 0) {
  3185. char *base = sp->base;
  3186. size_t size = sp->size;
  3187. msegmentptr next = sp->next;
  3188. if (is_mmapped_segment(sp) && !is_extern_segment(sp)) {
  3189. mchunkptr p = align_as_chunk(base);
  3190. size_t psize = chunksize(p);
  3191. /* Can unmap if first chunk holds entire segment and not pinned */
  3192. if (!cinuse(p)
  3193. && (char *) p + psize >= base + size - TOP_FOOT_SIZE) {
  3194. tchunkptr tp = (tchunkptr) p;
  3195. assert(segment_holds(sp, (char *) sp));
  3196. if (p == m->dv) {
  3197. m->dv = 0;
  3198. m->dvsize = 0;
  3199. } else {
  3200. unlink_large_chunk(m, tp);
  3201. }
  3202. if (CALL_MUNMAP(base, size) == 0) {
  3203. released += size;
  3204. m->footprint -= size;
  3205. /* unlink obsoleted record */
  3206. sp = pred;
  3207. sp->next = next;
  3208. } else { /* back out if cannot unmap */
  3209. insert_large_chunk(m, tp, psize);
  3210. }
  3211. }
  3212. }
  3213. pred = sp;
  3214. sp = next;
  3215. }
  3216. return released;
  3217. }
  3218. static int
  3219. sys_trim(mstate m, size_t pad)
  3220. {
  3221. size_t released = 0;
  3222. if (pad < MAX_REQUEST && is_initialized(m)) {
  3223. pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */
  3224. if (m->topsize > pad) {
  3225. /* Shrink top space in granularity-size units, keeping at least one */
  3226. size_t unit = mparams.granularity;
  3227. size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit -
  3228. SIZE_T_ONE) * unit;
  3229. msegmentptr sp = segment_holding(m, (char *) m->top);
  3230. if (!is_extern_segment(sp)) {
  3231. if (is_mmapped_segment(sp)) {
  3232. if (HAVE_MMAP && sp->size >= extra && !has_segment_link(m, sp)) { /* can't shrink if pinned */
  3233. size_t newsize = sp->size - extra;
  3234. /* Prefer mremap, fall back to munmap */
  3235. if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) !=
  3236. MFAIL)
  3237. || (CALL_MUNMAP(sp->base + newsize, extra) == 0)) {
  3238. released = extra;
  3239. }
  3240. }
  3241. } else if (HAVE_MORECORE) {
  3242. if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */
  3243. extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit;
  3244. ACQUIRE_MORECORE_LOCK();
  3245. {
  3246. /* Make sure end of memory is where we last set it. */
  3247. char *old_br = (char *) (CALL_MORECORE(0));
  3248. if (old_br == sp->base + sp->size) {
  3249. char *rel_br = (char *) (CALL_MORECORE(-extra));
  3250. char *new_br = (char *) (CALL_MORECORE(0));
  3251. if (rel_br != CMFAIL && new_br < old_br)
  3252. released = old_br - new_br;
  3253. }
  3254. }
  3255. RELEASE_MORECORE_LOCK();
  3256. }
  3257. }
  3258. if (released != 0) {
  3259. sp->size -= released;
  3260. m->footprint -= released;
  3261. init_top(m, m->top, m->topsize - released);
  3262. check_top_chunk(m, m->top);
  3263. }
  3264. }
  3265. /* Unmap any unused mmapped segments */
  3266. if (HAVE_MMAP)
  3267. released += release_unused_segments(m);
  3268. /* On failure, disable autotrim to avoid repeated failed future calls */
  3269. if (released == 0)
  3270. m->trim_check = MAX_SIZE_T;
  3271. }
  3272. return (released != 0) ? 1 : 0;
  3273. }
  3274. /* ---------------------------- malloc support --------------------------- */
  3275. /* allocate a large request from the best fitting chunk in a treebin */
  3276. static void *
  3277. tmalloc_large(mstate m, size_t nb)
  3278. {
  3279. tchunkptr v = 0;
  3280. size_t rsize = -nb; /* Unsigned negation */
  3281. tchunkptr t;
  3282. bindex_t idx;
  3283. compute_tree_index(nb, idx);
  3284. if ((t = *treebin_at(m, idx)) != 0) {
  3285. /* Traverse tree for this bin looking for node with size == nb */
  3286. size_t sizebits = nb << leftshift_for_tree_index(idx);
  3287. tchunkptr rst = 0; /* The deepest untaken right subtree */
  3288. for (;;) {
  3289. tchunkptr rt;
  3290. size_t trem = chunksize(t) - nb;
  3291. if (trem < rsize) {
  3292. v = t;
  3293. if ((rsize = trem) == 0)
  3294. break;
  3295. }
  3296. rt = t->child[1];
  3297. t = t->child[(sizebits >> (SIZE_T_BITSIZE - SIZE_T_ONE)) & 1];
  3298. if (rt != 0 && rt != t)
  3299. rst = rt;
  3300. if (t == 0) {
  3301. t = rst; /* set t to least subtree holding sizes > nb */
  3302. break;
  3303. }
  3304. sizebits <<= 1;
  3305. }
  3306. }
  3307. if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */
  3308. binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap;
  3309. if (leftbits != 0) {
  3310. bindex_t i;
  3311. binmap_t leastbit = least_bit(leftbits);
  3312. compute_bit2idx(leastbit, i);
  3313. t = *treebin_at(m, i);
  3314. }
  3315. }
  3316. while (t != 0) { /* find smallest of tree or subtree */
  3317. size_t trem = chunksize(t) - nb;
  3318. if (trem < rsize) {
  3319. rsize = trem;
  3320. v = t;
  3321. }
  3322. t = leftmost_child(t);
  3323. }
  3324. /* If dv is a better fit, return 0 so malloc will use it */
  3325. if (v != 0 && rsize < (size_t) (m->dvsize - nb)) {
  3326. if (RTCHECK(ok_address(m, v))) { /* split */
  3327. mchunkptr r = chunk_plus_offset(v, nb);
  3328. assert(chunksize(v) == rsize + nb);
  3329. if (RTCHECK(ok_next(v, r))) {
  3330. unlink_large_chunk(m, v);
  3331. if (rsize < MIN_CHUNK_SIZE)
  3332. set_inuse_and_pinuse(m, v, (rsize + nb));
  3333. else {
  3334. set_size_and_pinuse_of_inuse_chunk(m, v, nb);
  3335. set_size_and_pinuse_of_free_chunk(r, rsize);
  3336. insert_chunk(m, r, rsize);
  3337. }
  3338. return chunk2mem(v);
  3339. }
  3340. }
  3341. CORRUPTION_ERROR_ACTION(m);
  3342. }
  3343. return 0;
  3344. }
  3345. /* allocate a small request from the best fitting chunk in a treebin */
  3346. static void *
  3347. tmalloc_small(mstate m, size_t nb)
  3348. {
  3349. tchunkptr t, v;
  3350. size_t rsize;
  3351. bindex_t i;
  3352. binmap_t leastbit = least_bit(m->treemap);
  3353. compute_bit2idx(leastbit, i);
  3354. v = t = *treebin_at(m, i);
  3355. rsize = chunksize(t) - nb;
  3356. while ((t = leftmost_child(t)) != 0) {
  3357. size_t trem = chunksize(t) - nb;
  3358. if (trem < rsize) {
  3359. rsize = trem;
  3360. v = t;
  3361. }
  3362. }
  3363. if (RTCHECK(ok_address(m, v))) {
  3364. mchunkptr r = chunk_plus_offset(v, nb);
  3365. assert(chunksize(v) == rsize + nb);
  3366. if (RTCHECK(ok_next(v, r))) {
  3367. unlink_large_chunk(m, v);
  3368. if (rsize < MIN_CHUNK_SIZE)
  3369. set_inuse_and_pinuse(m, v, (rsize + nb));
  3370. else {
  3371. set_size_and_pinuse_of_inuse_chunk(m, v, nb);
  3372. set_size_and_pinuse_of_free_chunk(r, rsize);
  3373. replace_dv(m, r, rsize);
  3374. }
  3375. return chunk2mem(v);
  3376. }
  3377. }
  3378. CORRUPTION_ERROR_ACTION(m);
  3379. return 0;
  3380. }
  3381. /* --------------------------- realloc support --------------------------- */
  3382. static void *
  3383. internal_realloc(mstate m, void *oldmem, size_t bytes)
  3384. {
  3385. if (bytes >= MAX_REQUEST) {
  3386. MALLOC_FAILURE_ACTION;
  3387. return 0;
  3388. }
  3389. if (!PREACTION(m)) {
  3390. mchunkptr oldp = mem2chunk(oldmem);
  3391. size_t oldsize = chunksize(oldp);
  3392. mchunkptr next = chunk_plus_offset(oldp, oldsize);
  3393. mchunkptr newp = 0;
  3394. void *extra = 0;
  3395. /* Try to either shrink or extend into top. Else malloc-copy-free */
  3396. if (RTCHECK(ok_address(m, oldp) && ok_cinuse(oldp) &&
  3397. ok_next(oldp, next) && ok_pinuse(next))) {
  3398. size_t nb = request2size(bytes);
  3399. if (is_mmapped(oldp))
  3400. newp = mmap_resize(m, oldp, nb);
  3401. else if (oldsize >= nb) { /* already big enough */
  3402. size_t rsize = oldsize - nb;
  3403. newp = oldp;
  3404. if (rsize >= MIN_CHUNK_SIZE) {
  3405. mchunkptr remainder = chunk_plus_offset(newp, nb);
  3406. set_inuse(m, newp, nb);
  3407. set_inuse(m, remainder, rsize);
  3408. extra = chunk2mem(remainder);
  3409. }
  3410. } else if (next == m->top && oldsize + m->topsize > nb) {
  3411. /* Expand into top */
  3412. size_t newsize = oldsize + m->topsize;
  3413. size_t newtopsize = newsize - nb;
  3414. mchunkptr newtop = chunk_plus_offset(oldp, nb);
  3415. set_inuse(m, oldp, nb);
  3416. newtop->head = newtopsize | PINUSE_BIT;
  3417. m->top = newtop;
  3418. m->topsize = newtopsize;
  3419. newp = oldp;
  3420. }
  3421. } else {
  3422. USAGE_ERROR_ACTION(m, oldmem);
  3423. POSTACTION(m);
  3424. return 0;
  3425. }
  3426. POSTACTION(m);
  3427. if (newp != 0) {
  3428. if (extra != 0) {
  3429. internal_free(m, extra);
  3430. }
  3431. check_inuse_chunk(m, newp);
  3432. return chunk2mem(newp);
  3433. } else {
  3434. void *newmem = internal_malloc(m, bytes);
  3435. if (newmem != 0) {
  3436. size_t oc = oldsize - overhead_for(oldp);
  3437. memcpy(newmem, oldmem, (oc < bytes) ? oc : bytes);
  3438. internal_free(m, oldmem);
  3439. }
  3440. return newmem;
  3441. }
  3442. }
  3443. return 0;
  3444. }
  3445. /* --------------------------- memalign support -------------------------- */
  3446. static void *
  3447. internal_memalign(mstate m, size_t alignment, size_t bytes)
  3448. {
  3449. if (alignment <= MALLOC_ALIGNMENT) /* Can just use malloc */
  3450. return internal_malloc(m, bytes);
  3451. if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */
  3452. alignment = MIN_CHUNK_SIZE;
  3453. if ((alignment & (alignment - SIZE_T_ONE)) != 0) { /* Ensure a power of 2 */
  3454. size_t a = MALLOC_ALIGNMENT << 1;
  3455. while (a < alignment)
  3456. a <<= 1;
  3457. alignment = a;
  3458. }
  3459. if (bytes >= MAX_REQUEST - alignment) {
  3460. if (m != 0) { /* Test isn't needed but avoids compiler warning */
  3461. MALLOC_FAILURE_ACTION;
  3462. }
  3463. } else {
  3464. size_t nb = request2size(bytes);
  3465. size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD;
  3466. char *mem = (char *) internal_malloc(m, req);
  3467. if (mem != 0) {
  3468. void *leader = 0;
  3469. void *trailer = 0;
  3470. mchunkptr p = mem2chunk(mem);
  3471. if (PREACTION(m))
  3472. return 0;
  3473. if ((((size_t) (mem)) % alignment) != 0) { /* misaligned */
  3474. /*
  3475. Find an aligned spot inside chunk. Since we need to give
  3476. back leading space in a chunk of at least MIN_CHUNK_SIZE, if
  3477. the first calculation places us at a spot with less than
  3478. MIN_CHUNK_SIZE leader, we can move to the next aligned spot.
  3479. We've allocated enough total room so that this is always
  3480. possible.
  3481. */
  3482. char *br = (char *) mem2chunk((size_t) (((size_t) (mem +
  3483. alignment -
  3484. SIZE_T_ONE))
  3485. & -alignment));
  3486. char *pos =
  3487. ((size_t) (br - (char *) (p)) >=
  3488. MIN_CHUNK_SIZE) ? br : br + alignment;
  3489. mchunkptr newp = (mchunkptr) pos;
  3490. size_t leadsize = pos - (char *) (p);
  3491. size_t newsize = chunksize(p) - leadsize;
  3492. if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */
  3493. newp->prev_foot = p->prev_foot + leadsize;
  3494. newp->head = (newsize | CINUSE_BIT);
  3495. } else { /* Otherwise, give back leader, use the rest */
  3496. set_inuse(m, newp, newsize);
  3497. set_inuse(m, p, leadsize);
  3498. leader = chunk2mem(p);
  3499. }
  3500. p = newp;
  3501. }
  3502. /* Give back spare room at the end */
  3503. if (!is_mmapped(p)) {
  3504. size_t size = chunksize(p);
  3505. if (size > nb + MIN_CHUNK_SIZE) {
  3506. size_t remainder_size = size - nb;
  3507. mchunkptr remainder = chunk_plus_offset(p, nb);
  3508. set_inuse(m, p, nb);
  3509. set_inuse(m, remainder, remainder_size);
  3510. trailer = chunk2mem(remainder);
  3511. }
  3512. }
  3513. assert(chunksize(p) >= nb);
  3514. assert((((size_t) (chunk2mem(p))) % alignment) == 0);
  3515. check_inuse_chunk(m, p);
  3516. POSTACTION(m);
  3517. if (leader != 0) {
  3518. internal_free(m, leader);
  3519. }
  3520. if (trailer != 0) {
  3521. internal_free(m, trailer);
  3522. }
  3523. return chunk2mem(p);
  3524. }
  3525. }
  3526. return 0;
  3527. }
  3528. /* ------------------------ comalloc/coalloc support --------------------- */
  3529. static void **
  3530. ialloc(mstate m, size_t n_elements, size_t * sizes, int opts, void *chunks[])
  3531. {
  3532. /*
  3533. This provides common support for independent_X routines, handling
  3534. all of the combinations that can result.
  3535. The opts arg has:
  3536. bit 0 set if all elements are same size (using sizes[0])
  3537. bit 1 set if elements should be zeroed
  3538. */
  3539. size_t element_size; /* chunksize of each element, if all same */
  3540. size_t contents_size; /* total size of elements */
  3541. size_t array_size; /* request size of pointer array */
  3542. void *mem; /* malloced aggregate space */
  3543. mchunkptr p; /* corresponding chunk */
  3544. size_t remainder_size; /* remaining bytes while splitting */
  3545. void **marray; /* either "chunks" or malloced ptr array */
  3546. mchunkptr array_chunk; /* chunk for malloced ptr array */
  3547. flag_t was_enabled; /* to disable mmap */
  3548. size_t size;
  3549. size_t i;
  3550. /* compute array length, if needed */
  3551. if (chunks != 0) {
  3552. if (n_elements == 0)
  3553. return chunks; /* nothing to do */
  3554. marray = chunks;
  3555. array_size = 0;
  3556. } else {
  3557. /* if empty req, must still return chunk representing empty array */
  3558. if (n_elements == 0)
  3559. return (void **) internal_malloc(m, 0);
  3560. marray = 0;
  3561. array_size = request2size(n_elements * (sizeof(void *)));
  3562. }
  3563. /* compute total element size */
  3564. if (opts & 0x1) { /* all-same-size */
  3565. element_size = request2size(*sizes);
  3566. contents_size = n_elements * element_size;
  3567. } else { /* add up all the sizes */
  3568. element_size = 0;
  3569. contents_size = 0;
  3570. for (i = 0; i != n_elements; ++i)
  3571. contents_size += request2size(sizes[i]);
  3572. }
  3573. size = contents_size + array_size;
  3574. /*
  3575. Allocate the aggregate chunk. First disable direct-mmapping so
  3576. malloc won't use it, since we would not be able to later
  3577. free/realloc space internal to a segregated mmap region.
  3578. */
  3579. was_enabled = use_mmap(m);
  3580. disable_mmap(m);
  3581. mem = internal_malloc(m, size - CHUNK_OVERHEAD);
  3582. if (was_enabled)
  3583. enable_mmap(m);
  3584. if (mem == 0)
  3585. return 0;
  3586. if (PREACTION(m))
  3587. return 0;
  3588. p = mem2chunk(mem);
  3589. remainder_size = chunksize(p);
  3590. assert(!is_mmapped(p));
  3591. if (opts & 0x2) { /* optionally clear the elements */
  3592. memset((size_t *) mem, 0, remainder_size - SIZE_T_SIZE - array_size);
  3593. }
  3594. /* If not provided, allocate the pointer array as final part of chunk */
  3595. if (marray == 0) {
  3596. size_t array_chunk_size;
  3597. array_chunk = chunk_plus_offset(p, contents_size);
  3598. array_chunk_size = remainder_size - contents_size;
  3599. marray = (void **) (chunk2mem(array_chunk));
  3600. set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size);
  3601. remainder_size = contents_size;
  3602. }
  3603. /* split out elements */
  3604. for (i = 0;; ++i) {
  3605. marray[i] = chunk2mem(p);
  3606. if (i != n_elements - 1) {
  3607. if (element_size != 0)
  3608. size = element_size;
  3609. else
  3610. size = request2size(sizes[i]);
  3611. remainder_size -= size;
  3612. set_size_and_pinuse_of_inuse_chunk(m, p, size);
  3613. p = chunk_plus_offset(p, size);
  3614. } else { /* the final element absorbs any overallocation slop */
  3615. set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size);
  3616. break;
  3617. }
  3618. }
  3619. #if DEBUG
  3620. if (marray != chunks) {
  3621. /* final element must have exactly exhausted chunk */
  3622. if (element_size != 0) {
  3623. assert(remainder_size == element_size);
  3624. } else {
  3625. assert(remainder_size == request2size(sizes[i]));
  3626. }
  3627. check_inuse_chunk(m, mem2chunk(marray));
  3628. }
  3629. for (i = 0; i != n_elements; ++i)
  3630. check_inuse_chunk(m, mem2chunk(marray[i]));
  3631. #endif /* DEBUG */
  3632. POSTACTION(m);
  3633. return marray;
  3634. }
  3635. /* -------------------------- public routines ---------------------------- */
  3636. #if !ONLY_MSPACES
  3637. void *
  3638. dlmalloc(size_t bytes)
  3639. {
  3640. /*
  3641. Basic algorithm:
  3642. If a small request (< 256 bytes minus per-chunk overhead):
  3643. 1. If one exists, use a remainderless chunk in associated smallbin.
  3644. (Remainderless means that there are too few excess bytes to
  3645. represent as a chunk.)
  3646. 2. If it is big enough, use the dv chunk, which is normally the
  3647. chunk adjacent to the one used for the most recent small request.
  3648. 3. If one exists, split the smallest available chunk in a bin,
  3649. saving remainder in dv.
  3650. 4. If it is big enough, use the top chunk.
  3651. 5. If available, get memory from system and use it
  3652. Otherwise, for a large request:
  3653. 1. Find the smallest available binned chunk that fits, and use it
  3654. if it is better fitting than dv chunk, splitting if necessary.
  3655. 2. If better fitting than any binned chunk, use the dv chunk.
  3656. 3. If it is big enough, use the top chunk.
  3657. 4. If request size >= mmap threshold, try to directly mmap this chunk.
  3658. 5. If available, get memory from system and use it
  3659. The ugly goto's here ensure that postaction occurs along all paths.
  3660. */
  3661. if (!PREACTION(gm)) {
  3662. void *mem;
  3663. size_t nb;
  3664. if (bytes <= MAX_SMALL_REQUEST) {
  3665. bindex_t idx;
  3666. binmap_t smallbits;
  3667. nb = (bytes < MIN_REQUEST) ? MIN_CHUNK_SIZE : pad_request(bytes);
  3668. idx = small_index(nb);
  3669. smallbits = gm->smallmap >> idx;
  3670. if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
  3671. mchunkptr b, p;
  3672. idx += ~smallbits & 1; /* Uses next bin if idx empty */
  3673. b = smallbin_at(gm, idx);
  3674. p = b->fd;
  3675. assert(chunksize(p) == small_index2size(idx));
  3676. unlink_first_small_chunk(gm, b, p, idx);
  3677. set_inuse_and_pinuse(gm, p, small_index2size(idx));
  3678. mem = chunk2mem(p);
  3679. check_malloced_chunk(gm, mem, nb);
  3680. goto postaction;
  3681. }
  3682. else if (nb > gm->dvsize) {
  3683. if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
  3684. mchunkptr b, p, r;
  3685. size_t rsize;
  3686. bindex_t i;
  3687. binmap_t leftbits =
  3688. (smallbits << idx) & left_bits(idx2bit(idx));
  3689. binmap_t leastbit = least_bit(leftbits);
  3690. compute_bit2idx(leastbit, i);
  3691. b = smallbin_at(gm, i);
  3692. p = b->fd;
  3693. assert(chunksize(p) == small_index2size(i));
  3694. unlink_first_small_chunk(gm, b, p, i);
  3695. rsize = small_index2size(i) - nb;
  3696. /* Fit here cannot be remainderless if 4byte sizes */
  3697. if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
  3698. set_inuse_and_pinuse(gm, p, small_index2size(i));
  3699. else {
  3700. set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
  3701. r = chunk_plus_offset(p, nb);
  3702. set_size_and_pinuse_of_free_chunk(r, rsize);
  3703. replace_dv(gm, r, rsize);
  3704. }
  3705. mem = chunk2mem(p);
  3706. check_malloced_chunk(gm, mem, nb);
  3707. goto postaction;
  3708. }
  3709. else if (gm->treemap != 0
  3710. && (mem = tmalloc_small(gm, nb)) != 0) {
  3711. check_malloced_chunk(gm, mem, nb);
  3712. goto postaction;
  3713. }
  3714. }
  3715. } else if (bytes >= MAX_REQUEST)
  3716. nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
  3717. else {
  3718. nb = pad_request(bytes);
  3719. if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) {
  3720. check_malloced_chunk(gm, mem, nb);
  3721. goto postaction;
  3722. }
  3723. }
  3724. if (nb <= gm->dvsize) {
  3725. size_t rsize = gm->dvsize - nb;
  3726. mchunkptr p = gm->dv;
  3727. if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
  3728. mchunkptr r = gm->dv = chunk_plus_offset(p, nb);
  3729. gm->dvsize = rsize;
  3730. set_size_and_pinuse_of_free_chunk(r, rsize);
  3731. set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
  3732. } else { /* exhaust dv */
  3733. size_t dvs = gm->dvsize;
  3734. gm->dvsize = 0;
  3735. gm->dv = 0;
  3736. set_inuse_and_pinuse(gm, p, dvs);
  3737. }
  3738. mem = chunk2mem(p);
  3739. check_malloced_chunk(gm, mem, nb);
  3740. goto postaction;
  3741. }
  3742. else if (nb < gm->topsize) { /* Split top */
  3743. size_t rsize = gm->topsize -= nb;
  3744. mchunkptr p = gm->top;
  3745. mchunkptr r = gm->top = chunk_plus_offset(p, nb);
  3746. r->head = rsize | PINUSE_BIT;
  3747. set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
  3748. mem = chunk2mem(p);
  3749. check_top_chunk(gm, gm->top);
  3750. check_malloced_chunk(gm, mem, nb);
  3751. goto postaction;
  3752. }
  3753. mem = sys_alloc(gm, nb);
  3754. postaction:
  3755. POSTACTION(gm);
  3756. return mem;
  3757. }
  3758. return 0;
  3759. }
  3760. void
  3761. dlfree(void *mem)
  3762. {
  3763. /*
  3764. Consolidate freed chunks with preceeding or succeeding bordering
  3765. free chunks, if they exist, and then place in a bin. Intermixed
  3766. with special cases for top, dv, mmapped chunks, and usage errors.
  3767. */
  3768. if (mem != 0) {
  3769. mchunkptr p = mem2chunk(mem);
  3770. #if FOOTERS
  3771. mstate fm = get_mstate_for(p);
  3772. if (!ok_magic(fm)) {
  3773. USAGE_ERROR_ACTION(fm, p);
  3774. return;
  3775. }
  3776. #else /* FOOTERS */
  3777. #define fm gm
  3778. #endif /* FOOTERS */
  3779. if (!PREACTION(fm)) {
  3780. check_inuse_chunk(fm, p);
  3781. if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) {
  3782. size_t psize = chunksize(p);
  3783. mchunkptr next = chunk_plus_offset(p, psize);
  3784. if (!pinuse(p)) {
  3785. size_t prevsize = p->prev_foot;
  3786. if ((prevsize & IS_MMAPPED_BIT) != 0) {
  3787. prevsize &= ~IS_MMAPPED_BIT;
  3788. psize += prevsize + MMAP_FOOT_PAD;
  3789. if (CALL_MUNMAP((char *) p - prevsize, psize) == 0)
  3790. fm->footprint -= psize;
  3791. goto postaction;
  3792. } else {
  3793. mchunkptr prev = chunk_minus_offset(p, prevsize);
  3794. psize += prevsize;
  3795. p = prev;
  3796. if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
  3797. if (p != fm->dv) {
  3798. unlink_chunk(fm, p, prevsize);
  3799. } else if ((next->head & INUSE_BITS) ==
  3800. INUSE_BITS) {
  3801. fm->dvsize = psize;
  3802. set_free_with_pinuse(p, psize, next);
  3803. goto postaction;
  3804. }
  3805. } else
  3806. goto erroraction;
  3807. }
  3808. }
  3809. if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
  3810. if (!cinuse(next)) { /* consolidate forward */
  3811. if (next == fm->top) {
  3812. size_t tsize = fm->topsize += psize;
  3813. fm->top = p;
  3814. p->head = tsize | PINUSE_BIT;
  3815. if (p == fm->dv) {
  3816. fm->dv = 0;
  3817. fm->dvsize = 0;
  3818. }
  3819. if (should_trim(fm, tsize))
  3820. sys_trim(fm, 0);
  3821. goto postaction;
  3822. } else if (next == fm->dv) {
  3823. size_t dsize = fm->dvsize += psize;
  3824. fm->dv = p;
  3825. set_size_and_pinuse_of_free_chunk(p, dsize);
  3826. goto postaction;
  3827. } else {
  3828. size_t nsize = chunksize(next);
  3829. psize += nsize;
  3830. unlink_chunk(fm, next, nsize);
  3831. set_size_and_pinuse_of_free_chunk(p, psize);
  3832. if (p == fm->dv) {
  3833. fm->dvsize = psize;
  3834. goto postaction;
  3835. }
  3836. }
  3837. } else
  3838. set_free_with_pinuse(p, psize, next);
  3839. insert_chunk(fm, p, psize);
  3840. check_free_chunk(fm, p);
  3841. goto postaction;
  3842. }
  3843. }
  3844. erroraction:
  3845. USAGE_ERROR_ACTION(fm, p);
  3846. postaction:
  3847. POSTACTION(fm);
  3848. }
  3849. }
  3850. #if !FOOTERS
  3851. #undef fm
  3852. #endif /* FOOTERS */
  3853. }
  3854. void *
  3855. dlcalloc(size_t n_elements, size_t elem_size)
  3856. {
  3857. void *mem;
  3858. size_t req = 0;
  3859. if (n_elements != 0) {
  3860. req = n_elements * elem_size;
  3861. if (((n_elements | elem_size) & ~(size_t) 0xffff) &&
  3862. (req / n_elements != elem_size))
  3863. req = MAX_SIZE_T; /* force downstream failure on overflow */
  3864. }
  3865. mem = dlmalloc(req);
  3866. if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
  3867. memset(mem, 0, req);
  3868. return mem;
  3869. }
  3870. void *
  3871. dlrealloc(void *oldmem, size_t bytes)
  3872. {
  3873. if (oldmem == 0)
  3874. return dlmalloc(bytes);
  3875. #ifdef REALLOC_ZERO_BYTES_FREES
  3876. if (bytes == 0) {
  3877. dlfree(oldmem);
  3878. return 0;
  3879. }
  3880. #endif /* REALLOC_ZERO_BYTES_FREES */
  3881. else {
  3882. #if ! FOOTERS
  3883. mstate m = gm;
  3884. #else /* FOOTERS */
  3885. mstate m = get_mstate_for(mem2chunk(oldmem));
  3886. if (!ok_magic(m)) {
  3887. USAGE_ERROR_ACTION(m, oldmem);
  3888. return 0;
  3889. }
  3890. #endif /* FOOTERS */
  3891. return internal_realloc(m, oldmem, bytes);
  3892. }
  3893. }
  3894. void *
  3895. dlmemalign(size_t alignment, size_t bytes)
  3896. {
  3897. return internal_memalign(gm, alignment, bytes);
  3898. }
  3899. void **
  3900. dlindependent_calloc(size_t n_elements, size_t elem_size, void *chunks[])
  3901. {
  3902. size_t sz = elem_size; /* serves as 1-element array */
  3903. return ialloc(gm, n_elements, &sz, 3, chunks);
  3904. }
  3905. void **
  3906. dlindependent_comalloc(size_t n_elements, size_t sizes[], void *chunks[])
  3907. {
  3908. return ialloc(gm, n_elements, sizes, 0, chunks);
  3909. }
  3910. void *
  3911. dlvalloc(size_t bytes)
  3912. {
  3913. size_t pagesz;
  3914. init_mparams();
  3915. pagesz = mparams.page_size;
  3916. return dlmemalign(pagesz, bytes);
  3917. }
  3918. void *
  3919. dlpvalloc(size_t bytes)
  3920. {
  3921. size_t pagesz;
  3922. init_mparams();
  3923. pagesz = mparams.page_size;
  3924. return dlmemalign(pagesz,
  3925. (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE));
  3926. }
  3927. int
  3928. dlmalloc_trim(size_t pad)
  3929. {
  3930. int result = 0;
  3931. if (!PREACTION(gm)) {
  3932. result = sys_trim(gm, pad);
  3933. POSTACTION(gm);
  3934. }
  3935. return result;
  3936. }
  3937. size_t
  3938. dlmalloc_footprint(void)
  3939. {
  3940. return gm->footprint;
  3941. }
  3942. size_t
  3943. dlmalloc_max_footprint(void)
  3944. {
  3945. return gm->max_footprint;
  3946. }
  3947. #if !NO_MALLINFO
  3948. struct mallinfo
  3949. dlmallinfo(void)
  3950. {
  3951. return internal_mallinfo(gm);
  3952. }
  3953. #endif /* NO_MALLINFO */
  3954. void
  3955. dlmalloc_stats()
  3956. {
  3957. internal_malloc_stats(gm);
  3958. }
  3959. size_t
  3960. dlmalloc_usable_size(void *mem)
  3961. {
  3962. if (mem != 0) {
  3963. mchunkptr p = mem2chunk(mem);
  3964. if (cinuse(p))
  3965. return chunksize(p) - overhead_for(p);
  3966. }
  3967. return 0;
  3968. }
  3969. int
  3970. dlmallopt(int param_number, int value)
  3971. {
  3972. return change_mparam(param_number, value);
  3973. }
  3974. #endif /* !ONLY_MSPACES */
  3975. /* ----------------------------- user mspaces ---------------------------- */
  3976. #if MSPACES
  3977. static mstate
  3978. init_user_mstate(char *tbase, size_t tsize)
  3979. {
  3980. size_t msize = pad_request(sizeof(struct malloc_state));
  3981. mchunkptr mn;
  3982. mchunkptr msp = align_as_chunk(tbase);
  3983. mstate m = (mstate) (chunk2mem(msp));
  3984. memset(m, 0, msize);
  3985. INITIAL_LOCK(&m->mutex);
  3986. msp->head = (msize | PINUSE_BIT | CINUSE_BIT);
  3987. m->seg.base = m->least_addr = tbase;
  3988. m->seg.size = m->footprint = m->max_footprint = tsize;
  3989. m->magic = mparams.magic;
  3990. m->mflags = mparams.default_mflags;
  3991. disable_contiguous(m);
  3992. init_bins(m);
  3993. mn = next_chunk(mem2chunk(m));
  3994. init_top(m, mn, (size_t) ((tbase + tsize) - (char *) mn) - TOP_FOOT_SIZE);
  3995. check_top_chunk(m, m->top);
  3996. return m;
  3997. }
  3998. mspace
  3999. create_mspace(size_t capacity, int locked)
  4000. {
  4001. mstate m = 0;
  4002. size_t msize = pad_request(sizeof(struct malloc_state));
  4003. init_mparams(); /* Ensure pagesize etc initialized */
  4004. if (capacity < (size_t) - (msize + TOP_FOOT_SIZE + mparams.page_size)) {
  4005. size_t rs = ((capacity == 0) ? mparams.granularity :
  4006. (capacity + TOP_FOOT_SIZE + msize));
  4007. size_t tsize = granularity_align(rs);
  4008. char *tbase = (char *) (CALL_MMAP(tsize));
  4009. if (tbase != CMFAIL) {
  4010. m = init_user_mstate(tbase, tsize);
  4011. m->seg.sflags = IS_MMAPPED_BIT;
  4012. set_lock(m, locked);
  4013. }
  4014. }
  4015. return (mspace) m;
  4016. }
  4017. mspace
  4018. create_mspace_with_base(void *base, size_t capacity, int locked)
  4019. {
  4020. mstate m = 0;
  4021. size_t msize = pad_request(sizeof(struct malloc_state));
  4022. init_mparams(); /* Ensure pagesize etc initialized */
  4023. if (capacity > msize + TOP_FOOT_SIZE &&
  4024. capacity < (size_t) - (msize + TOP_FOOT_SIZE + mparams.page_size)) {
  4025. m = init_user_mstate((char *) base, capacity);
  4026. m->seg.sflags = EXTERN_BIT;
  4027. set_lock(m, locked);
  4028. }
  4029. return (mspace) m;
  4030. }
  4031. size_t
  4032. destroy_mspace(mspace msp)
  4033. {
  4034. size_t freed = 0;
  4035. mstate ms = (mstate) msp;
  4036. if (ok_magic(ms)) {
  4037. msegmentptr sp = &ms->seg;
  4038. while (sp != 0) {
  4039. char *base = sp->base;
  4040. size_t size = sp->size;
  4041. flag_t flag = sp->sflags;
  4042. sp = sp->next;
  4043. if ((flag & IS_MMAPPED_BIT) && !(flag & EXTERN_BIT) &&
  4044. CALL_MUNMAP(base, size) == 0)
  4045. freed += size;
  4046. }
  4047. } else {
  4048. USAGE_ERROR_ACTION(ms, ms);
  4049. }
  4050. return freed;
  4051. }
  4052. /*
  4053. mspace versions of routines are near-clones of the global
  4054. versions. This is not so nice but better than the alternatives.
  4055. */
  4056. void *
  4057. mspace_malloc(mspace msp, size_t bytes)
  4058. {
  4059. mstate ms = (mstate) msp;
  4060. if (!ok_magic(ms)) {
  4061. USAGE_ERROR_ACTION(ms, ms);
  4062. return 0;
  4063. }
  4064. if (!PREACTION(ms)) {
  4065. void *mem;
  4066. size_t nb;
  4067. if (bytes <= MAX_SMALL_REQUEST) {
  4068. bindex_t idx;
  4069. binmap_t smallbits;
  4070. nb = (bytes < MIN_REQUEST) ? MIN_CHUNK_SIZE : pad_request(bytes);
  4071. idx = small_index(nb);
  4072. smallbits = ms->smallmap >> idx;
  4073. if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
  4074. mchunkptr b, p;
  4075. idx += ~smallbits & 1; /* Uses next bin if idx empty */
  4076. b = smallbin_at(ms, idx);
  4077. p = b->fd;
  4078. assert(chunksize(p) == small_index2size(idx));
  4079. unlink_first_small_chunk(ms, b, p, idx);
  4080. set_inuse_and_pinuse(ms, p, small_index2size(idx));
  4081. mem = chunk2mem(p);
  4082. check_malloced_chunk(ms, mem, nb);
  4083. goto postaction;
  4084. }
  4085. else if (nb > ms->dvsize) {
  4086. if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
  4087. mchunkptr b, p, r;
  4088. size_t rsize;
  4089. bindex_t i;
  4090. binmap_t leftbits =
  4091. (smallbits << idx) & left_bits(idx2bit(idx));
  4092. binmap_t leastbit = least_bit(leftbits);
  4093. compute_bit2idx(leastbit, i);
  4094. b = smallbin_at(ms, i);
  4095. p = b->fd;
  4096. assert(chunksize(p) == small_index2size(i));
  4097. unlink_first_small_chunk(ms, b, p, i);
  4098. rsize = small_index2size(i) - nb;
  4099. /* Fit here cannot be remainderless if 4byte sizes */
  4100. if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
  4101. set_inuse_and_pinuse(ms, p, small_index2size(i));
  4102. else {
  4103. set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
  4104. r = chunk_plus_offset(p, nb);
  4105. set_size_and_pinuse_of_free_chunk(r, rsize);
  4106. replace_dv(ms, r, rsize);
  4107. }
  4108. mem = chunk2mem(p);
  4109. check_malloced_chunk(ms, mem, nb);
  4110. goto postaction;
  4111. }
  4112. else if (ms->treemap != 0
  4113. && (mem = tmalloc_small(ms, nb)) != 0) {
  4114. check_malloced_chunk(ms, mem, nb);
  4115. goto postaction;
  4116. }
  4117. }
  4118. } else if (bytes >= MAX_REQUEST)
  4119. nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
  4120. else {
  4121. nb = pad_request(bytes);
  4122. if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) {
  4123. check_malloced_chunk(ms, mem, nb);
  4124. goto postaction;
  4125. }
  4126. }
  4127. if (nb <= ms->dvsize) {
  4128. size_t rsize = ms->dvsize - nb;
  4129. mchunkptr p = ms->dv;
  4130. if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
  4131. mchunkptr r = ms->dv = chunk_plus_offset(p, nb);
  4132. ms->dvsize = rsize;
  4133. set_size_and_pinuse_of_free_chunk(r, rsize);
  4134. set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
  4135. } else { /* exhaust dv */
  4136. size_t dvs = ms->dvsize;
  4137. ms->dvsize = 0;
  4138. ms->dv = 0;
  4139. set_inuse_and_pinuse(ms, p, dvs);
  4140. }
  4141. mem = chunk2mem(p);
  4142. check_malloced_chunk(ms, mem, nb);
  4143. goto postaction;
  4144. }
  4145. else if (nb < ms->topsize) { /* Split top */
  4146. size_t rsize = ms->topsize -= nb;
  4147. mchunkptr p = ms->top;
  4148. mchunkptr r = ms->top = chunk_plus_offset(p, nb);
  4149. r->head = rsize | PINUSE_BIT;
  4150. set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
  4151. mem = chunk2mem(p);
  4152. check_top_chunk(ms, ms->top);
  4153. check_malloced_chunk(ms, mem, nb);
  4154. goto postaction;
  4155. }
  4156. mem = sys_alloc(ms, nb);
  4157. postaction:
  4158. POSTACTION(ms);
  4159. return mem;
  4160. }
  4161. return 0;
  4162. }
  4163. void
  4164. mspace_free(mspace msp, void *mem)
  4165. {
  4166. if (mem != 0) {
  4167. mchunkptr p = mem2chunk(mem);
  4168. #if FOOTERS
  4169. mstate fm = get_mstate_for(p);
  4170. #else /* FOOTERS */
  4171. mstate fm = (mstate) msp;
  4172. #endif /* FOOTERS */
  4173. if (!ok_magic(fm)) {
  4174. USAGE_ERROR_ACTION(fm, p);
  4175. return;
  4176. }
  4177. if (!PREACTION(fm)) {
  4178. check_inuse_chunk(fm, p);
  4179. if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) {
  4180. size_t psize = chunksize(p);
  4181. mchunkptr next = chunk_plus_offset(p, psize);
  4182. if (!pinuse(p)) {
  4183. size_t prevsize = p->prev_foot;
  4184. if ((prevsize & IS_MMAPPED_BIT) != 0) {
  4185. prevsize &= ~IS_MMAPPED_BIT;
  4186. psize += prevsize + MMAP_FOOT_PAD;
  4187. if (CALL_MUNMAP((char *) p - prevsize, psize) == 0)
  4188. fm->footprint -= psize;
  4189. goto postaction;
  4190. } else {
  4191. mchunkptr prev = chunk_minus_offset(p, prevsize);
  4192. psize += prevsize;
  4193. p = prev;
  4194. if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
  4195. if (p != fm->dv) {
  4196. unlink_chunk(fm, p, prevsize);
  4197. } else if ((next->head & INUSE_BITS) ==
  4198. INUSE_BITS) {
  4199. fm->dvsize = psize;
  4200. set_free_with_pinuse(p, psize, next);
  4201. goto postaction;
  4202. }
  4203. } else
  4204. goto erroraction;
  4205. }
  4206. }
  4207. if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
  4208. if (!cinuse(next)) { /* consolidate forward */
  4209. if (next == fm->top) {
  4210. size_t tsize = fm->topsize += psize;
  4211. fm->top = p;
  4212. p->head = tsize | PINUSE_BIT;
  4213. if (p == fm->dv) {
  4214. fm->dv = 0;
  4215. fm->dvsize = 0;
  4216. }
  4217. if (should_trim(fm, tsize))
  4218. sys_trim(fm, 0);
  4219. goto postaction;
  4220. } else if (next == fm->dv) {
  4221. size_t dsize = fm->dvsize += psize;
  4222. fm->dv = p;
  4223. set_size_and_pinuse_of_free_chunk(p, dsize);
  4224. goto postaction;
  4225. } else {
  4226. size_t nsize = chunksize(next);
  4227. psize += nsize;
  4228. unlink_chunk(fm, next, nsize);
  4229. set_size_and_pinuse_of_free_chunk(p, psize);
  4230. if (p == fm->dv) {
  4231. fm->dvsize = psize;
  4232. goto postaction;
  4233. }
  4234. }
  4235. } else
  4236. set_free_with_pinuse(p, psize, next);
  4237. insert_chunk(fm, p, psize);
  4238. check_free_chunk(fm, p);
  4239. goto postaction;
  4240. }
  4241. }
  4242. erroraction:
  4243. USAGE_ERROR_ACTION(fm, p);
  4244. postaction:
  4245. POSTACTION(fm);
  4246. }
  4247. }
  4248. }
  4249. void *
  4250. mspace_calloc(mspace msp, size_t n_elements, size_t elem_size)
  4251. {
  4252. void *mem;
  4253. size_t req = 0;
  4254. mstate ms = (mstate) msp;
  4255. if (!ok_magic(ms)) {
  4256. USAGE_ERROR_ACTION(ms, ms);
  4257. return 0;
  4258. }
  4259. if (n_elements != 0) {
  4260. req = n_elements * elem_size;
  4261. if (((n_elements | elem_size) & ~(size_t) 0xffff) &&
  4262. (req / n_elements != elem_size))
  4263. req = MAX_SIZE_T; /* force downstream failure on overflow */
  4264. }
  4265. mem = internal_malloc(ms, req);
  4266. if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
  4267. memset(mem, 0, req);
  4268. return mem;
  4269. }
  4270. void *
  4271. mspace_realloc(mspace msp, void *oldmem, size_t bytes)
  4272. {
  4273. if (oldmem == 0)
  4274. return mspace_malloc(msp, bytes);
  4275. #ifdef REALLOC_ZERO_BYTES_FREES
  4276. if (bytes == 0) {
  4277. mspace_free(msp, oldmem);
  4278. return 0;
  4279. }
  4280. #endif /* REALLOC_ZERO_BYTES_FREES */
  4281. else {
  4282. #if FOOTERS
  4283. mchunkptr p = mem2chunk(oldmem);
  4284. mstate ms = get_mstate_for(p);
  4285. #else /* FOOTERS */
  4286. mstate ms = (mstate) msp;
  4287. #endif /* FOOTERS */
  4288. if (!ok_magic(ms)) {
  4289. USAGE_ERROR_ACTION(ms, ms);
  4290. return 0;
  4291. }
  4292. return internal_realloc(ms, oldmem, bytes);
  4293. }
  4294. }
  4295. void *
  4296. mspace_memalign(mspace msp, size_t alignment, size_t bytes)
  4297. {
  4298. mstate ms = (mstate) msp;
  4299. if (!ok_magic(ms)) {
  4300. USAGE_ERROR_ACTION(ms, ms);
  4301. return 0;
  4302. }
  4303. return internal_memalign(ms, alignment, bytes);
  4304. }
  4305. void **
  4306. mspace_independent_calloc(mspace msp, size_t n_elements,
  4307. size_t elem_size, void *chunks[])
  4308. {
  4309. size_t sz = elem_size; /* serves as 1-element array */
  4310. mstate ms = (mstate) msp;
  4311. if (!ok_magic(ms)) {
  4312. USAGE_ERROR_ACTION(ms, ms);
  4313. return 0;
  4314. }
  4315. return ialloc(ms, n_elements, &sz, 3, chunks);
  4316. }
  4317. void **
  4318. mspace_independent_comalloc(mspace msp, size_t n_elements,
  4319. size_t sizes[], void *chunks[])
  4320. {
  4321. mstate ms = (mstate) msp;
  4322. if (!ok_magic(ms)) {
  4323. USAGE_ERROR_ACTION(ms, ms);
  4324. return 0;
  4325. }
  4326. return ialloc(ms, n_elements, sizes, 0, chunks);
  4327. }
  4328. int
  4329. mspace_trim(mspace msp, size_t pad)
  4330. {
  4331. int result = 0;
  4332. mstate ms = (mstate) msp;
  4333. if (ok_magic(ms)) {
  4334. if (!PREACTION(ms)) {
  4335. result = sys_trim(ms, pad);
  4336. POSTACTION(ms);
  4337. }
  4338. } else {
  4339. USAGE_ERROR_ACTION(ms, ms);
  4340. }
  4341. return result;
  4342. }
  4343. void
  4344. mspace_malloc_stats(mspace msp)
  4345. {
  4346. mstate ms = (mstate) msp;
  4347. if (ok_magic(ms)) {
  4348. internal_malloc_stats(ms);
  4349. } else {
  4350. USAGE_ERROR_ACTION(ms, ms);
  4351. }
  4352. }
  4353. size_t
  4354. mspace_footprint(mspace msp)
  4355. {
  4356. size_t result;
  4357. mstate ms = (mstate) msp;
  4358. if (ok_magic(ms)) {
  4359. result = ms->footprint;
  4360. }
  4361. USAGE_ERROR_ACTION(ms, ms);
  4362. return result;
  4363. }
  4364. size_t
  4365. mspace_max_footprint(mspace msp)
  4366. {
  4367. size_t result;
  4368. mstate ms = (mstate) msp;
  4369. if (ok_magic(ms)) {
  4370. result = ms->max_footprint;
  4371. }
  4372. USAGE_ERROR_ACTION(ms, ms);
  4373. return result;
  4374. }
  4375. #if !NO_MALLINFO
  4376. struct mallinfo
  4377. mspace_mallinfo(mspace msp)
  4378. {
  4379. mstate ms = (mstate) msp;
  4380. if (!ok_magic(ms)) {
  4381. USAGE_ERROR_ACTION(ms, ms);
  4382. }
  4383. return internal_mallinfo(ms);
  4384. }
  4385. #endif /* NO_MALLINFO */
  4386. int
  4387. mspace_mallopt(int param_number, int value)
  4388. {
  4389. return change_mparam(param_number, value);
  4390. }
  4391. #endif /* MSPACES */
  4392. /* -------------------- Alternative MORECORE functions ------------------- */
  4393. /*
  4394. Guidelines for creating a custom version of MORECORE:
  4395. * For best performance, MORECORE should allocate in multiples of pagesize.
  4396. * MORECORE may allocate more memory than requested. (Or even less,
  4397. but this will usually result in a malloc failure.)
  4398. * MORECORE must not allocate memory when given argument zero, but
  4399. instead return one past the end address of memory from previous
  4400. nonzero call.
  4401. * For best performance, consecutive calls to MORECORE with positive
  4402. arguments should return increasing addresses, indicating that
  4403. space has been contiguously extended.
  4404. * Even though consecutive calls to MORECORE need not return contiguous
  4405. addresses, it must be OK for malloc'ed chunks to span multiple
  4406. regions in those cases where they do happen to be contiguous.
  4407. * MORECORE need not handle negative arguments -- it may instead
  4408. just return MFAIL when given negative arguments.
  4409. Negative arguments are always multiples of pagesize. MORECORE
  4410. must not misinterpret negative args as large positive unsigned
  4411. args. You can suppress all such calls from even occurring by defining
  4412. MORECORE_CANNOT_TRIM,
  4413. As an example alternative MORECORE, here is a custom allocator
  4414. kindly contributed for pre-OSX macOS. It uses virtually but not
  4415. necessarily physically contiguous non-paged memory (locked in,
  4416. present and won't get swapped out). You can use it by uncommenting
  4417. this section, adding some #includes, and setting up the appropriate
  4418. defines above:
  4419. #define MORECORE osMoreCore
  4420. There is also a shutdown routine that should somehow be called for
  4421. cleanup upon program exit.
  4422. #define MAX_POOL_ENTRIES 100
  4423. #define MINIMUM_MORECORE_SIZE (64 * 1024U)
  4424. static int next_os_pool;
  4425. void *our_os_pools[MAX_POOL_ENTRIES];
  4426. void *osMoreCore(int size)
  4427. {
  4428. void *ptr = 0;
  4429. static void *sbrk_top = 0;
  4430. if (size > 0)
  4431. {
  4432. if (size < MINIMUM_MORECORE_SIZE)
  4433. size = MINIMUM_MORECORE_SIZE;
  4434. if (CurrentExecutionLevel() == kTaskLevel)
  4435. ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
  4436. if (ptr == 0)
  4437. {
  4438. return (void *) MFAIL;
  4439. }
  4440. // save ptrs so they can be freed during cleanup
  4441. our_os_pools[next_os_pool] = ptr;
  4442. next_os_pool++;
  4443. ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
  4444. sbrk_top = (char *) ptr + size;
  4445. return ptr;
  4446. }
  4447. else if (size < 0)
  4448. {
  4449. // we don't currently support shrink behavior
  4450. return (void *) MFAIL;
  4451. }
  4452. else
  4453. {
  4454. return sbrk_top;
  4455. }
  4456. }
  4457. // cleanup any allocated memory pools
  4458. // called as last thing before shutting down driver
  4459. void osCleanupMem(void)
  4460. {
  4461. void **ptr;
  4462. for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
  4463. if (*ptr)
  4464. {
  4465. PoolDeallocate(*ptr);
  4466. *ptr = 0;
  4467. }
  4468. }
  4469. */
  4470. /* -----------------------------------------------------------------------
  4471. History:
  4472. V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee)
  4473. * Add max_footprint functions
  4474. * Ensure all appropriate literals are size_t
  4475. * Fix conditional compilation problem for some #define settings
  4476. * Avoid concatenating segments with the one provided
  4477. in create_mspace_with_base
  4478. * Rename some variables to avoid compiler shadowing warnings
  4479. * Use explicit lock initialization.
  4480. * Better handling of sbrk interference.
  4481. * Simplify and fix segment insertion, trimming and mspace_destroy
  4482. * Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x
  4483. * Thanks especially to Dennis Flanagan for help on these.
  4484. V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee)
  4485. * Fix memalign brace error.
  4486. V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee)
  4487. * Fix improper #endif nesting in C++
  4488. * Add explicit casts needed for C++
  4489. V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee)
  4490. * Use trees for large bins
  4491. * Support mspaces
  4492. * Use segments to unify sbrk-based and mmap-based system allocation,
  4493. removing need for emulation on most platforms without sbrk.
  4494. * Default safety checks
  4495. * Optional footer checks. Thanks to William Robertson for the idea.
  4496. * Internal code refactoring
  4497. * Incorporate suggestions and platform-specific changes.
  4498. Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas,
  4499. Aaron Bachmann, Emery Berger, and others.
  4500. * Speed up non-fastbin processing enough to remove fastbins.
  4501. * Remove useless cfree() to avoid conflicts with other apps.
  4502. * Remove internal memcpy, memset. Compilers handle builtins better.
  4503. * Remove some options that no one ever used and rename others.
  4504. V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee)
  4505. * Fix malloc_state bitmap array misdeclaration
  4506. V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee)
  4507. * Allow tuning of FIRST_SORTED_BIN_SIZE
  4508. * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte.
  4509. * Better detection and support for non-contiguousness of MORECORE.
  4510. Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger
  4511. * Bypass most of malloc if no frees. Thanks To Emery Berger.
  4512. * Fix freeing of old top non-contiguous chunk im sysmalloc.
  4513. * Raised default trim and map thresholds to 256K.
  4514. * Fix mmap-related #defines. Thanks to Lubos Lunak.
  4515. * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield.
  4516. * Branch-free bin calculation
  4517. * Default trim and mmap thresholds now 256K.
  4518. V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
  4519. * Introduce independent_comalloc and independent_calloc.
  4520. Thanks to Michael Pachos for motivation and help.
  4521. * Make optional .h file available
  4522. * Allow > 2GB requests on 32bit systems.
  4523. * new WIN32 sbrk, mmap, munmap, lock code from <[email protected]>.
  4524. Thanks also to Andreas Mueller <a.mueller at paradatec.de>,
  4525. and Anonymous.
  4526. * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for
  4527. helping test this.)
  4528. * memalign: check alignment arg
  4529. * realloc: don't try to shift chunks backwards, since this
  4530. leads to more fragmentation in some programs and doesn't
  4531. seem to help in any others.
  4532. * Collect all cases in malloc requiring system memory into sysmalloc
  4533. * Use mmap as backup to sbrk
  4534. * Place all internal state in malloc_state
  4535. * Introduce fastbins (although similar to 2.5.1)
  4536. * Many minor tunings and cosmetic improvements
  4537. * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK
  4538. * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS
  4539. Thanks to Tony E. Bennett <[email protected]> and others.
  4540. * Include errno.h to support default failure action.
  4541. V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee)
  4542. * return null for negative arguments
  4543. * Added Several WIN32 cleanups from Martin C. Fong <mcfong at yahoo.com>
  4544. * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
  4545. (e.g. WIN32 platforms)
  4546. * Cleanup header file inclusion for WIN32 platforms
  4547. * Cleanup code to avoid Microsoft Visual C++ compiler complaints
  4548. * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
  4549. memory allocation routines
  4550. * Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
  4551. * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
  4552. usage of 'assert' in non-WIN32 code
  4553. * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
  4554. avoid infinite loop
  4555. * Always call 'fREe()' rather than 'free()'
  4556. V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee)
  4557. * Fixed ordering problem with boundary-stamping
  4558. V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
  4559. * Added pvalloc, as recommended by H.J. Liu
  4560. * Added 64bit pointer support mainly from Wolfram Gloger
  4561. * Added anonymously donated WIN32 sbrk emulation
  4562. * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
  4563. * malloc_extend_top: fix mask error that caused wastage after
  4564. foreign sbrks
  4565. * Add linux mremap support code from HJ Liu
  4566. V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
  4567. * Integrated most documentation with the code.
  4568. * Add support for mmap, with help from
  4569. Wolfram Gloger ([email protected]).
  4570. * Use last_remainder in more cases.
  4571. * Pack bins using idea from [email protected]
  4572. * Use ordered bins instead of best-fit threshhold
  4573. * Eliminate block-local decls to simplify tracing and debugging.
  4574. * Support another case of realloc via move into top
  4575. * Fix error occuring when initial sbrk_base not word-aligned.
  4576. * Rely on page size for units instead of SBRK_UNIT to
  4577. avoid surprises about sbrk alignment conventions.
  4578. * Add mallinfo, mallopt. Thanks to Raymond Nijssen
  4579. ([email protected]) for the suggestion.
  4580. * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
  4581. * More precautions for cases where other routines call sbrk,
  4582. courtesy of Wolfram Gloger ([email protected]).
  4583. * Added macros etc., allowing use in linux libc from
  4584. H.J. Lu ([email protected])
  4585. * Inverted this history list
  4586. V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
  4587. * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
  4588. * Removed all preallocation code since under current scheme
  4589. the work required to undo bad preallocations exceeds
  4590. the work saved in good cases for most test programs.
  4591. * No longer use return list or unconsolidated bins since
  4592. no scheme using them consistently outperforms those that don't
  4593. given above changes.
  4594. * Use best fit for very large chunks to prevent some worst-cases.
  4595. * Added some support for debugging
  4596. V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
  4597. * Removed footers when chunks are in use. Thanks to
  4598. Paul Wilson ([email protected]) for the suggestion.
  4599. V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
  4600. * Added malloc_trim, with help from Wolfram Gloger
  4601. ([email protected]).
  4602. V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
  4603. V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
  4604. * realloc: try to expand in both directions
  4605. * malloc: swap order of clean-bin strategy;
  4606. * realloc: only conditionally expand backwards
  4607. * Try not to scavenge used bins
  4608. * Use bin counts as a guide to preallocation
  4609. * Occasionally bin return list chunks in first scan
  4610. * Add a few optimizations from [email protected]
  4611. V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
  4612. * faster bin computation & slightly different binning
  4613. * merged all consolidations to one part of malloc proper
  4614. (eliminating old malloc_find_space & malloc_clean_bin)
  4615. * Scan 2 returns chunks (not just 1)
  4616. * Propagate failure in realloc if malloc returns 0
  4617. * Add stuff to allow compilation on non-ANSI compilers
  4618. from [email protected]
  4619. V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
  4620. * removed potential for odd address access in prev_chunk
  4621. * removed dependency on getpagesize.h
  4622. * misc cosmetics and a bit more internal documentation
  4623. * anticosmetics: mangled names in macros to evade debugger strangeness
  4624. * tested on sparc, hp-700, dec-mips, rs6000
  4625. with gcc & native cc (hp, dec only) allowing
  4626. Detlefs & Zorn comparison study (in SIGPLAN Notices.)
  4627. Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
  4628. * Based loosely on libg++-1.2X malloc. (It retains some of the overall
  4629. structure of old version, but most details differ.)
  4630. */
  4631. #endif /* !HAVE_MALLOC */
  4632. /* vi: set ts=4 sw=4 expandtab: */