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