SDL_malloc.c 222 KB

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