malloc.c 218 KB

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