malloc.c 218 KB

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