malloc.c 178 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609
  1. /* Malloc implementation for multiple threads without lock contention.
  2. Copyright (C) 1996-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Contributed by Wolfram Gloger <wg@malloc.de>
  5. and Doug Lea <dl@cs.oswego.edu>, 2001.
  6. The GNU C Library is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU Lesser General Public License as
  8. published by the Free Software Foundation; either version 2.1 of the
  9. License, or (at your option) any later version.
  10. The GNU C Library is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. Lesser General Public License for more details.
  14. You should have received a copy of the GNU Lesser General Public
  15. License along with the GNU C Library; see the file COPYING.LIB. If
  16. not, see <http://www.gnu.org/licenses/>. */
  17. /*
  18. This is a version (aka ptmalloc2) of malloc/free/realloc written by
  19. Doug Lea and adapted to multiple threads/arenas by Wolfram Gloger.
  20. There have been substantial changes made after the integration into
  21. glibc in all parts of the code. Do not look for much commonality
  22. with the ptmalloc2 version.
  23. * Version ptmalloc2-20011215
  24. based on:
  25. VERSION 2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
  26. * Quickstart
  27. In order to compile this implementation, a Makefile is provided with
  28. the ptmalloc2 distribution, which has pre-defined targets for some
  29. popular systems (e.g. "make posix" for Posix threads). All that is
  30. typically required with regard to compiler flags is the selection of
  31. the thread package via defining one out of USE_PTHREADS, USE_THR or
  32. USE_SPROC. Check the thread-m.h file for what effects this has.
  33. Many/most systems will additionally require USE_TSD_DATA_HACK to be
  34. defined, so this is the default for "make posix".
  35. * Why use this malloc?
  36. This is not the fastest, most space-conserving, most portable, or
  37. most tunable malloc ever written. However it is among the fastest
  38. while also being among the most space-conserving, portable and tunable.
  39. Consistent balance across these factors results in a good general-purpose
  40. allocator for malloc-intensive programs.
  41. The main properties of the algorithms are:
  42. * For large (>= 512 bytes) requests, it is a pure best-fit allocator,
  43. with ties normally decided via FIFO (i.e. least recently used).
  44. * For small (<= 64 bytes by default) requests, it is a caching
  45. allocator, that maintains pools of quickly recycled chunks.
  46. * In between, and for combinations of large and small requests, it does
  47. the best it can trying to meet both goals at once.
  48. * For very large requests (>= 128KB by default), it relies on system
  49. memory mapping facilities, if supported.
  50. For a longer but slightly out of date high-level description, see
  51. http://gee.cs.oswego.edu/dl/html/malloc.html
  52. You may already by default be using a C library containing a malloc
  53. that is based on some version of this malloc (for example in
  54. linux). You might still want to use the one in this file in order to
  55. customize settings or to avoid overheads associated with library
  56. versions.
  57. * Contents, described in more detail in "description of public routines" below.
  58. Standard (ANSI/SVID/...) functions:
  59. malloc(size_t n);
  60. calloc(size_t n_elements, size_t element_size);
  61. free(void* p);
  62. realloc(void* p, size_t n);
  63. memalign(size_t alignment, size_t n);
  64. valloc(size_t n);
  65. mallinfo()
  66. mallopt(int parameter_number, int parameter_value)
  67. Additional functions:
  68. independent_calloc(size_t n_elements, size_t size, void* chunks[]);
  69. independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
  70. pvalloc(size_t n);
  71. malloc_trim(size_t pad);
  72. malloc_usable_size(void* p);
  73. malloc_stats();
  74. * Vital statistics:
  75. Supported pointer representation: 4 or 8 bytes
  76. Supported size_t representation: 4 or 8 bytes
  77. Note that size_t is allowed to be 4 bytes even if pointers are 8.
  78. You can adjust this by defining INTERNAL_SIZE_T
  79. Alignment: 2 * sizeof(size_t) (default)
  80. (i.e., 8 byte alignment with 4byte size_t). This suffices for
  81. nearly all current machines and C compilers. However, you can
  82. define MALLOC_ALIGNMENT to be wider than this if necessary.
  83. Minimum overhead per allocated chunk: 4 or 8 bytes
  84. Each malloced chunk has a hidden word of overhead holding size
  85. and status information.
  86. Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
  87. 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
  88. When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
  89. ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
  90. needed; 4 (8) for a trailing size field and 8 (16) bytes for
  91. free list pointers. Thus, the minimum allocatable size is
  92. 16/24/32 bytes.
  93. Even a request for zero bytes (i.e., malloc(0)) returns a
  94. pointer to something of the minimum allocatable size.
  95. The maximum overhead wastage (i.e., number of extra bytes
  96. allocated than were requested in malloc) is less than or equal
  97. to the minimum size, except for requests >= mmap_threshold that
  98. are serviced via mmap(), where the worst case wastage is 2 *
  99. sizeof(size_t) bytes plus the remainder from a system page (the
  100. minimal mmap unit); typically 4096 or 8192 bytes.
  101. Maximum allocated size: 4-byte size_t: 2^32 minus about two pages
  102. 8-byte size_t: 2^64 minus about two pages
  103. It is assumed that (possibly signed) size_t values suffice to
  104. represent chunk sizes. `Possibly signed' is due to the fact
  105. that `size_t' may be defined on a system as either a signed or
  106. an unsigned type. The ISO C standard says that it must be
  107. unsigned, but a few systems are known not to adhere to this.
  108. Additionally, even when size_t is unsigned, sbrk (which is by
  109. default used to obtain memory from system) accepts signed
  110. arguments, and may not be able to handle size_t-wide arguments
  111. with negative sign bit. Generally, values that would
  112. appear as negative after accounting for overhead and alignment
  113. are supported only via mmap(), which does not have this
  114. limitation.
  115. Requests for sizes outside the allowed range will perform an optional
  116. failure action and then return null. (Requests may also
  117. also fail because a system is out of memory.)
  118. Thread-safety: thread-safe
  119. Compliance: I believe it is compliant with the 1997 Single Unix Specification
  120. Also SVID/XPG, ANSI C, and probably others as well.
  121. * Synopsis of compile-time options:
  122. People have reported using previous versions of this malloc on all
  123. versions of Unix, sometimes by tweaking some of the defines
  124. below. It has been tested most extensively on Solaris and Linux.
  125. People also report using it in stand-alone embedded systems.
  126. The implementation is in straight, hand-tuned ANSI C. It is not
  127. at all modular. (Sorry!) It uses a lot of macros. To be at all
  128. usable, this code should be compiled using an optimizing compiler
  129. (for example gcc -O3) that can simplify expressions and control
  130. paths. (FAQ: some macros import variables as arguments rather than
  131. declare locals because people reported that some debuggers
  132. otherwise get confused.)
  133. OPTION DEFAULT VALUE
  134. Compilation Environment options:
  135. HAVE_MREMAP 0
  136. Changing default word sizes:
  137. INTERNAL_SIZE_T size_t
  138. Configuration and functionality options:
  139. USE_PUBLIC_MALLOC_WRAPPERS NOT defined
  140. USE_MALLOC_LOCK NOT defined
  141. MALLOC_DEBUG NOT defined
  142. REALLOC_ZERO_BYTES_FREES 1
  143. TRIM_FASTBINS 0
  144. Options for customizing MORECORE:
  145. MORECORE sbrk
  146. MORECORE_FAILURE -1
  147. MORECORE_CONTIGUOUS 1
  148. MORECORE_CANNOT_TRIM NOT defined
  149. MORECORE_CLEARS 1
  150. MMAP_AS_MORECORE_SIZE (1024 * 1024)
  151. Tuning options that are also dynamically changeable via mallopt:
  152. DEFAULT_MXFAST 64 (for 32bit), 128 (for 64bit)
  153. DEFAULT_TRIM_THRESHOLD 128 * 1024
  154. DEFAULT_TOP_PAD 0
  155. DEFAULT_MMAP_THRESHOLD 128 * 1024
  156. DEFAULT_MMAP_MAX 65536
  157. There are several other #defined constants and macros that you
  158. probably don't want to touch unless you are extending or adapting malloc. */
  159. /*
  160. void* is the pointer type that malloc should say it returns
  161. */
  162. #ifndef void
  163. #define void void
  164. #endif /*void*/
  165. #include <stddef.h> /* for size_t */
  166. #include <stdlib.h> /* for getenv(), abort() */
  167. #include <unistd.h> /* for __libc_enable_secure */
  168. #include <atomic.h>
  169. #include <_itoa.h>
  170. #include <bits/wordsize.h>
  171. #include <sys/sysinfo.h>
  172. #include <ldsodefs.h>
  173. #include <unistd.h>
  174. #include <stdio.h> /* needed for malloc_stats */
  175. #include <errno.h>
  176. #include <assert.h>
  177. #include <shlib-compat.h>
  178. /* For uintptr_t. */
  179. #include <stdint.h>
  180. /* For va_arg, va_start, va_end. */
  181. #include <stdarg.h>
  182. /* For MIN, MAX, powerof2. */
  183. #include <sys/param.h>
  184. /* For ALIGN_UP et. al. */
  185. #include <libc-pointer-arith.h>
  186. /* For DIAG_PUSH/POP_NEEDS_COMMENT et al. */
  187. #include <libc-diag.h>
  188. #include <malloc/malloc-internal.h>
  189. /* For SINGLE_THREAD_P. */
  190. #include <sysdep-cancel.h>
  191. /*
  192. Debugging:
  193. Because freed chunks may be overwritten with bookkeeping fields, this
  194. malloc will often die when freed memory is overwritten by user
  195. programs. This can be very effective (albeit in an annoying way)
  196. in helping track down dangling pointers.
  197. If you compile with -DMALLOC_DEBUG, a number of assertion checks are
  198. enabled that will catch more memory errors. You probably won't be
  199. able to make much sense of the actual assertion errors, but they
  200. should help you locate incorrectly overwritten memory. The checking
  201. is fairly extensive, and will slow down execution
  202. noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set
  203. will attempt to check every non-mmapped allocated and free chunk in
  204. the course of computing the summmaries. (By nature, mmapped regions
  205. cannot be checked very much automatically.)
  206. Setting MALLOC_DEBUG may also be helpful if you are trying to modify
  207. this code. The assertions in the check routines spell out in more
  208. detail the assumptions and invariants underlying the algorithms.
  209. Setting MALLOC_DEBUG does NOT provide an automated mechanism for
  210. checking that all accesses to malloced memory stay within their
  211. bounds. However, there are several add-ons and adaptations of this
  212. or other mallocs available that do this.
  213. */
  214. #ifndef MALLOC_DEBUG
  215. #define MALLOC_DEBUG 0
  216. #endif
  217. #ifndef NDEBUG
  218. # define __assert_fail(assertion, file, line, function) \
  219. __malloc_assert(assertion, file, line, function)
  220. extern const char *__progname;
  221. static void
  222. __malloc_assert (const char *assertion, const char *file, unsigned int line,
  223. const char *function)
  224. {
  225. (void) __fxprintf (NULL, "%s%s%s:%u: %s%sAssertion `%s' failed.\n",
  226. __progname, __progname[0] ? ": " : "",
  227. file, line,
  228. function ? function : "", function ? ": " : "",
  229. assertion);
  230. fflush (stderr);
  231. abort ();
  232. }
  233. #endif
  234. #if USE_TCACHE
  235. /* We want 64 entries. This is an arbitrary limit, which tunables can reduce. */
  236. # define TCACHE_MAX_BINS 64
  237. # define MAX_TCACHE_SIZE tidx2usize (TCACHE_MAX_BINS-1)
  238. /* Only used to pre-fill the tunables. */
  239. # define tidx2usize(idx) (((size_t) idx) * MALLOC_ALIGNMENT + MINSIZE - SIZE_SZ)
  240. /* When "x" is from chunksize(). */
  241. # define csize2tidx(x) (((x) - MINSIZE + MALLOC_ALIGNMENT - 1) / MALLOC_ALIGNMENT)
  242. /* When "x" is a user-provided size. */
  243. # define usize2tidx(x) csize2tidx (request2size (x))
  244. /* With rounding and alignment, the bins are...
  245. idx 0 bytes 0..24 (64-bit) or 0..12 (32-bit)
  246. idx 1 bytes 25..40 or 13..20
  247. idx 2 bytes 41..56 or 21..28
  248. etc. */
  249. /* This is another arbitrary limit, which tunables can change. Each
  250. tcache bin will hold at most this number of chunks. */
  251. # define TCACHE_FILL_COUNT 7
  252. #endif
  253. /*
  254. REALLOC_ZERO_BYTES_FREES should be set if a call to
  255. realloc with zero bytes should be the same as a call to free.
  256. This is required by the C standard. Otherwise, since this malloc
  257. returns a unique pointer for malloc(0), so does realloc(p, 0).
  258. */
  259. #ifndef REALLOC_ZERO_BYTES_FREES
  260. #define REALLOC_ZERO_BYTES_FREES 1
  261. #endif
  262. /*
  263. TRIM_FASTBINS controls whether free() of a very small chunk can
  264. immediately lead to trimming. Setting to true (1) can reduce memory
  265. footprint, but will almost always slow down programs that use a lot
  266. of small chunks.
  267. Define this only if you are willing to give up some speed to more
  268. aggressively reduce system-level memory footprint when releasing
  269. memory in programs that use many small chunks. You can get
  270. essentially the same effect by setting MXFAST to 0, but this can
  271. lead to even greater slowdowns in programs using many small chunks.
  272. TRIM_FASTBINS is an in-between compile-time option, that disables
  273. only those chunks bordering topmost memory from being placed in
  274. fastbins.
  275. */
  276. #ifndef TRIM_FASTBINS
  277. #define TRIM_FASTBINS 0
  278. #endif
  279. /* Definition for getting more memory from the OS. */
  280. #define MORECORE (*__morecore)
  281. #define MORECORE_FAILURE 0
  282. void * __default_morecore (ptrdiff_t);
  283. void *(*__morecore)(ptrdiff_t) = __default_morecore;
  284. #include <string.h>
  285. /*
  286. MORECORE-related declarations. By default, rely on sbrk
  287. */
  288. /*
  289. MORECORE is the name of the routine to call to obtain more memory
  290. from the system. See below for general guidance on writing
  291. alternative MORECORE functions, as well as a version for WIN32 and a
  292. sample version for pre-OSX macos.
  293. */
  294. #ifndef MORECORE
  295. #define MORECORE sbrk
  296. #endif
  297. /*
  298. MORECORE_FAILURE is the value returned upon failure of MORECORE
  299. as well as mmap. Since it cannot be an otherwise valid memory address,
  300. and must reflect values of standard sys calls, you probably ought not
  301. try to redefine it.
  302. */
  303. #ifndef MORECORE_FAILURE
  304. #define MORECORE_FAILURE (-1)
  305. #endif
  306. /*
  307. If MORECORE_CONTIGUOUS is true, take advantage of fact that
  308. consecutive calls to MORECORE with positive arguments always return
  309. contiguous increasing addresses. This is true of unix sbrk. Even
  310. if not defined, when regions happen to be contiguous, malloc will
  311. permit allocations spanning regions obtained from different
  312. calls. But defining this when applicable enables some stronger
  313. consistency checks and space efficiencies.
  314. */
  315. #ifndef MORECORE_CONTIGUOUS
  316. #define MORECORE_CONTIGUOUS 1
  317. #endif
  318. /*
  319. Define MORECORE_CANNOT_TRIM if your version of MORECORE
  320. cannot release space back to the system when given negative
  321. arguments. This is generally necessary only if you are using
  322. a hand-crafted MORECORE function that cannot handle negative arguments.
  323. */
  324. /* #define MORECORE_CANNOT_TRIM */
  325. /* MORECORE_CLEARS (default 1)
  326. The degree to which the routine mapped to MORECORE zeroes out
  327. memory: never (0), only for newly allocated space (1) or always
  328. (2). The distinction between (1) and (2) is necessary because on
  329. some systems, if the application first decrements and then
  330. increments the break value, the contents of the reallocated space
  331. are unspecified.
  332. */
  333. #ifndef MORECORE_CLEARS
  334. # define MORECORE_CLEARS 1
  335. #endif
  336. /*
  337. MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
  338. sbrk fails, and mmap is used as a backup. The value must be a
  339. multiple of page size. This backup strategy generally applies only
  340. when systems have "holes" in address space, so sbrk cannot perform
  341. contiguous expansion, but there is still space available on system.
  342. On systems for which this is known to be useful (i.e. most linux
  343. kernels), this occurs only when programs allocate huge amounts of
  344. memory. Between this, and the fact that mmap regions tend to be
  345. limited, the size should be large, to avoid too many mmap calls and
  346. thus avoid running out of kernel resources. */
  347. #ifndef MMAP_AS_MORECORE_SIZE
  348. #define MMAP_AS_MORECORE_SIZE (1024 * 1024)
  349. #endif
  350. /*
  351. Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
  352. large blocks.
  353. */
  354. #ifndef HAVE_MREMAP
  355. #define HAVE_MREMAP 0
  356. #endif
  357. /* We may need to support __malloc_initialize_hook for backwards
  358. compatibility. */
  359. #if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_24)
  360. # define HAVE_MALLOC_INIT_HOOK 1
  361. #else
  362. # define HAVE_MALLOC_INIT_HOOK 0
  363. #endif
  364. /*
  365. This version of malloc supports the standard SVID/XPG mallinfo
  366. routine that returns a struct containing usage properties and
  367. statistics. It should work on any SVID/XPG compliant system that has
  368. a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
  369. install such a thing yourself, cut out the preliminary declarations
  370. as described above and below and save them in a malloc.h file. But
  371. there's no compelling reason to bother to do this.)
  372. The main declaration needed is the mallinfo struct that is returned
  373. (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
  374. bunch of fields that are not even meaningful in this version of
  375. malloc. These fields are are instead filled by mallinfo() with
  376. other numbers that might be of interest.
  377. */
  378. /* ---------- description of public routines ------------ */
  379. /*
  380. malloc(size_t n)
  381. Returns a pointer to a newly allocated chunk of at least n bytes, or null
  382. if no space is available. Additionally, on failure, errno is
  383. set to ENOMEM on ANSI C systems.
  384. If n is zero, malloc returns a minumum-sized chunk. (The minimum
  385. size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
  386. systems.) On most systems, size_t is an unsigned type, so calls
  387. with negative arguments are interpreted as requests for huge amounts
  388. of space, which will often fail. The maximum supported value of n
  389. differs across systems, but is in all cases less than the maximum
  390. representable value of a size_t.
  391. */
  392. void* __libc_malloc(size_t);
  393. libc_hidden_proto (__libc_malloc)
  394. /*
  395. free(void* p)
  396. Releases the chunk of memory pointed to by p, that had been previously
  397. allocated using malloc or a related routine such as realloc.
  398. It has no effect if p is null. It can have arbitrary (i.e., bad!)
  399. effects if p has already been freed.
  400. Unless disabled (using mallopt), freeing very large spaces will
  401. when possible, automatically trigger operations that give
  402. back unused memory to the system, thus reducing program footprint.
  403. */
  404. void __libc_free(void*);
  405. libc_hidden_proto (__libc_free)
  406. /*
  407. calloc(size_t n_elements, size_t element_size);
  408. Returns a pointer to n_elements * element_size bytes, with all locations
  409. set to zero.
  410. */
  411. void* __libc_calloc(size_t, size_t);
  412. /*
  413. realloc(void* p, size_t n)
  414. Returns a pointer to a chunk of size n that contains the same data
  415. as does chunk p up to the minimum of (n, p's size) bytes, or null
  416. if no space is available.
  417. The returned pointer may or may not be the same as p. The algorithm
  418. prefers extending p when possible, otherwise it employs the
  419. equivalent of a malloc-copy-free sequence.
  420. If p is null, realloc is equivalent to malloc.
  421. If space is not available, realloc returns null, errno is set (if on
  422. ANSI) and p is NOT freed.
  423. if n is for fewer bytes than already held by p, the newly unused
  424. space is lopped off and freed if possible. Unless the #define
  425. REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
  426. zero (re)allocates a minimum-sized chunk.
  427. Large chunks that were internally obtained via mmap will always be
  428. grown using malloc-copy-free sequences unless the system supports
  429. MREMAP (currently only linux).
  430. The old unix realloc convention of allowing the last-free'd chunk
  431. to be used as an argument to realloc is not supported.
  432. */
  433. void* __libc_realloc(void*, size_t);
  434. libc_hidden_proto (__libc_realloc)
  435. /*
  436. memalign(size_t alignment, size_t n);
  437. Returns a pointer to a newly allocated chunk of n bytes, aligned
  438. in accord with the alignment argument.
  439. The alignment argument should be a power of two. If the argument is
  440. not a power of two, the nearest greater power is used.
  441. 8-byte alignment is guaranteed by normal malloc calls, so don't
  442. bother calling memalign with an argument of 8 or less.
  443. Overreliance on memalign is a sure way to fragment space.
  444. */
  445. void* __libc_memalign(size_t, size_t);
  446. libc_hidden_proto (__libc_memalign)
  447. /*
  448. valloc(size_t n);
  449. Equivalent to memalign(pagesize, n), where pagesize is the page
  450. size of the system. If the pagesize is unknown, 4096 is used.
  451. */
  452. void* __libc_valloc(size_t);
  453. /*
  454. mallopt(int parameter_number, int parameter_value)
  455. Sets tunable parameters The format is to provide a
  456. (parameter-number, parameter-value) pair. mallopt then sets the
  457. corresponding parameter to the argument value if it can (i.e., so
  458. long as the value is meaningful), and returns 1 if successful else
  459. 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
  460. normally defined in malloc.h. Only one of these (M_MXFAST) is used
  461. in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
  462. so setting them has no effect. But this malloc also supports four
  463. other options in mallopt. See below for details. Briefly, supported
  464. parameters are as follows (listed defaults are for "typical"
  465. configurations).
  466. Symbol param # default allowed param values
  467. M_MXFAST 1 64 0-80 (0 disables fastbins)
  468. M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
  469. M_TOP_PAD -2 0 any
  470. M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
  471. M_MMAP_MAX -4 65536 any (0 disables use of mmap)
  472. */
  473. int __libc_mallopt(int, int);
  474. libc_hidden_proto (__libc_mallopt)
  475. /*
  476. mallinfo()
  477. Returns (by copy) a struct containing various summary statistics:
  478. arena: current total non-mmapped bytes allocated from system
  479. ordblks: the number of free chunks
  480. smblks: the number of fastbin blocks (i.e., small chunks that
  481. have been freed but not use resused or consolidated)
  482. hblks: current number of mmapped regions
  483. hblkhd: total bytes held in mmapped regions
  484. usmblks: always 0
  485. fsmblks: total bytes held in fastbin blocks
  486. uordblks: current total allocated space (normal or mmapped)
  487. fordblks: total free space
  488. keepcost: the maximum number of bytes that could ideally be released
  489. back to system via malloc_trim. ("ideally" means that
  490. it ignores page restrictions etc.)
  491. Because these fields are ints, but internal bookkeeping may
  492. be kept as longs, the reported values may wrap around zero and
  493. thus be inaccurate.
  494. */
  495. struct mallinfo __libc_mallinfo(void);
  496. /*
  497. pvalloc(size_t n);
  498. Equivalent to valloc(minimum-page-that-holds(n)), that is,
  499. round up n to nearest pagesize.
  500. */
  501. void* __libc_pvalloc(size_t);
  502. /*
  503. malloc_trim(size_t pad);
  504. If possible, gives memory back to the system (via negative
  505. arguments to sbrk) if there is unused memory at the `high' end of
  506. the malloc pool. You can call this after freeing large blocks of
  507. memory to potentially reduce the system-level memory requirements
  508. of a program. However, it cannot guarantee to reduce memory. Under
  509. some allocation patterns, some large free blocks of memory will be
  510. locked between two used chunks, so they cannot be given back to
  511. the system.
  512. The `pad' argument to malloc_trim represents the amount of free
  513. trailing space to leave untrimmed. If this argument is zero,
  514. only the minimum amount of memory to maintain internal data
  515. structures will be left (one page or less). Non-zero arguments
  516. can be supplied to maintain enough trailing space to service
  517. future expected allocations without having to re-obtain memory
  518. from the system.
  519. Malloc_trim returns 1 if it actually released any memory, else 0.
  520. On systems that do not support "negative sbrks", it will always
  521. return 0.
  522. */
  523. int __malloc_trim(size_t);
  524. /*
  525. malloc_usable_size(void* p);
  526. Returns the number of bytes you can actually use in
  527. an allocated chunk, which may be more than you requested (although
  528. often not) due to alignment and minimum size constraints.
  529. You can use this many bytes without worrying about
  530. overwriting other allocated objects. This is not a particularly great
  531. programming practice. malloc_usable_size can be more useful in
  532. debugging and assertions, for example:
  533. p = malloc(n);
  534. assert(malloc_usable_size(p) >= 256);
  535. */
  536. size_t __malloc_usable_size(void*);
  537. /*
  538. malloc_stats();
  539. Prints on stderr the amount of space obtained from the system (both
  540. via sbrk and mmap), the maximum amount (which may be more than
  541. current if malloc_trim and/or munmap got called), and the current
  542. number of bytes allocated via malloc (or realloc, etc) but not yet
  543. freed. Note that this is the number of bytes allocated, not the
  544. number requested. It will be larger than the number requested
  545. because of alignment and bookkeeping overhead. Because it includes
  546. alignment wastage as being in use, this figure may be greater than
  547. zero even when no user-level chunks are allocated.
  548. The reported current and maximum system memory can be inaccurate if
  549. a program makes other calls to system memory allocation functions
  550. (normally sbrk) outside of malloc.
  551. malloc_stats prints only the most commonly interesting statistics.
  552. More information can be obtained by calling mallinfo.
  553. */
  554. void __malloc_stats(void);
  555. /*
  556. posix_memalign(void **memptr, size_t alignment, size_t size);
  557. POSIX wrapper like memalign(), checking for validity of size.
  558. */
  559. int __posix_memalign(void **, size_t, size_t);
  560. /* mallopt tuning options */
  561. /*
  562. M_MXFAST is the maximum request size used for "fastbins", special bins
  563. that hold returned chunks without consolidating their spaces. This
  564. enables future requests for chunks of the same size to be handled
  565. very quickly, but can increase fragmentation, and thus increase the
  566. overall memory footprint of a program.
  567. This malloc manages fastbins very conservatively yet still
  568. efficiently, so fragmentation is rarely a problem for values less
  569. than or equal to the default. The maximum supported value of MXFAST
  570. is 80. You wouldn't want it any higher than this anyway. Fastbins
  571. are designed especially for use with many small structs, objects or
  572. strings -- the default handles structs/objects/arrays with sizes up
  573. to 8 4byte fields, or small strings representing words, tokens,
  574. etc. Using fastbins for larger objects normally worsens
  575. fragmentation without improving speed.
  576. M_MXFAST is set in REQUEST size units. It is internally used in
  577. chunksize units, which adds padding and alignment. You can reduce
  578. M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
  579. algorithm to be a closer approximation of fifo-best-fit in all cases,
  580. not just for larger requests, but will generally cause it to be
  581. slower.
  582. */
  583. /* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
  584. #ifndef M_MXFAST
  585. #define M_MXFAST 1
  586. #endif
  587. #ifndef DEFAULT_MXFAST
  588. #define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
  589. #endif
  590. /*
  591. M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
  592. to keep before releasing via malloc_trim in free().
  593. Automatic trimming is mainly useful in long-lived programs.
  594. Because trimming via sbrk can be slow on some systems, and can
  595. sometimes be wasteful (in cases where programs immediately
  596. afterward allocate more large chunks) the value should be high
  597. enough so that your overall system performance would improve by
  598. releasing this much memory.
  599. The trim threshold and the mmap control parameters (see below)
  600. can be traded off with one another. Trimming and mmapping are
  601. two different ways of releasing unused memory back to the
  602. system. Between these two, it is often possible to keep
  603. system-level demands of a long-lived program down to a bare
  604. minimum. For example, in one test suite of sessions measuring
  605. the XF86 X server on Linux, using a trim threshold of 128K and a
  606. mmap threshold of 192K led to near-minimal long term resource
  607. consumption.
  608. If you are using this malloc in a long-lived program, it should
  609. pay to experiment with these values. As a rough guide, you
  610. might set to a value close to the average size of a process
  611. (program) running on your system. Releasing this much memory
  612. would allow such a process to run in memory. Generally, it's
  613. worth it to tune for trimming rather tham memory mapping when a
  614. program undergoes phases where several large chunks are
  615. allocated and released in ways that can reuse each other's
  616. storage, perhaps mixed with phases where there are no such
  617. chunks at all. And in well-behaved long-lived programs,
  618. controlling release of large blocks via trimming versus mapping
  619. is usually faster.
  620. However, in most programs, these parameters serve mainly as
  621. protection against the system-level effects of carrying around
  622. massive amounts of unneeded memory. Since frequent calls to
  623. sbrk, mmap, and munmap otherwise degrade performance, the default
  624. parameters are set to relatively high values that serve only as
  625. safeguards.
  626. The trim value It must be greater than page size to have any useful
  627. effect. To disable trimming completely, you can set to
  628. (unsigned long)(-1)
  629. Trim settings interact with fastbin (MXFAST) settings: Unless
  630. TRIM_FASTBINS is defined, automatic trimming never takes place upon
  631. freeing a chunk with size less than or equal to MXFAST. Trimming is
  632. instead delayed until subsequent freeing of larger chunks. However,
  633. you can still force an attempted trim by calling malloc_trim.
  634. Also, trimming is not generally possible in cases where
  635. the main arena is obtained via mmap.
  636. Note that the trick some people use of mallocing a huge space and
  637. then freeing it at program startup, in an attempt to reserve system
  638. memory, doesn't have the intended effect under automatic trimming,
  639. since that memory will immediately be returned to the system.
  640. */
  641. #define M_TRIM_THRESHOLD -1
  642. #ifndef DEFAULT_TRIM_THRESHOLD
  643. #define DEFAULT_TRIM_THRESHOLD (128 * 1024)
  644. #endif
  645. /*
  646. M_TOP_PAD is the amount of extra `padding' space to allocate or
  647. retain whenever sbrk is called. It is used in two ways internally:
  648. * When sbrk is called to extend the top of the arena to satisfy
  649. a new malloc request, this much padding is added to the sbrk
  650. request.
  651. * When malloc_trim is called automatically from free(),
  652. it is used as the `pad' argument.
  653. In both cases, the actual amount of padding is rounded
  654. so that the end of the arena is always a system page boundary.
  655. The main reason for using padding is to avoid calling sbrk so
  656. often. Having even a small pad greatly reduces the likelihood
  657. that nearly every malloc request during program start-up (or
  658. after trimming) will invoke sbrk, which needlessly wastes
  659. time.
  660. Automatic rounding-up to page-size units is normally sufficient
  661. to avoid measurable overhead, so the default is 0. However, in
  662. systems where sbrk is relatively slow, it can pay to increase
  663. this value, at the expense of carrying around more memory than
  664. the program needs.
  665. */
  666. #define M_TOP_PAD -2
  667. #ifndef DEFAULT_TOP_PAD
  668. #define DEFAULT_TOP_PAD (0)
  669. #endif
  670. /*
  671. MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
  672. adjusted MMAP_THRESHOLD.
  673. */
  674. #ifndef DEFAULT_MMAP_THRESHOLD_MIN
  675. #define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
  676. #endif
  677. #ifndef DEFAULT_MMAP_THRESHOLD_MAX
  678. /* For 32-bit platforms we cannot increase the maximum mmap
  679. threshold much because it is also the minimum value for the
  680. maximum heap size and its alignment. Going above 512k (i.e., 1M
  681. for new heaps) wastes too much address space. */
  682. # if __WORDSIZE == 32
  683. # define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
  684. # else
  685. # define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
  686. # endif
  687. #endif
  688. /*
  689. M_MMAP_THRESHOLD is the request size threshold for using mmap()
  690. to service a request. Requests of at least this size that cannot
  691. be allocated using already-existing space will be serviced via mmap.
  692. (If enough normal freed space already exists it is used instead.)
  693. Using mmap segregates relatively large chunks of memory so that
  694. they can be individually obtained and released from the host
  695. system. A request serviced through mmap is never reused by any
  696. other request (at least not directly; the system may just so
  697. happen to remap successive requests to the same locations).
  698. Segregating space in this way has the benefits that:
  699. 1. Mmapped space can ALWAYS be individually released back
  700. to the system, which helps keep the system level memory
  701. demands of a long-lived program low.
  702. 2. Mapped memory can never become `locked' between
  703. other chunks, as can happen with normally allocated chunks, which
  704. means that even trimming via malloc_trim would not release them.
  705. 3. On some systems with "holes" in address spaces, mmap can obtain
  706. memory that sbrk cannot.
  707. However, it has the disadvantages that:
  708. 1. The space cannot be reclaimed, consolidated, and then
  709. used to service later requests, as happens with normal chunks.
  710. 2. It can lead to more wastage because of mmap page alignment
  711. requirements
  712. 3. It causes malloc performance to be more dependent on host
  713. system memory management support routines which may vary in
  714. implementation quality and may impose arbitrary
  715. limitations. Generally, servicing a request via normal
  716. malloc steps is faster than going through a system's mmap.
  717. The advantages of mmap nearly always outweigh disadvantages for
  718. "large" chunks, but the value of "large" varies across systems. The
  719. default is an empirically derived value that works well in most
  720. systems.
  721. Update in 2006:
  722. The above was written in 2001. Since then the world has changed a lot.
  723. Memory got bigger. Applications got bigger. The virtual address space
  724. layout in 32 bit linux changed.
  725. In the new situation, brk() and mmap space is shared and there are no
  726. artificial limits on brk size imposed by the kernel. What is more,
  727. applications have started using transient allocations larger than the
  728. 128Kb as was imagined in 2001.
  729. The price for mmap is also high now; each time glibc mmaps from the
  730. kernel, the kernel is forced to zero out the memory it gives to the
  731. application. Zeroing memory is expensive and eats a lot of cache and
  732. memory bandwidth. This has nothing to do with the efficiency of the
  733. virtual memory system, by doing mmap the kernel just has no choice but
  734. to zero.
  735. In 2001, the kernel had a maximum size for brk() which was about 800
  736. megabytes on 32 bit x86, at that point brk() would hit the first
  737. mmaped shared libaries and couldn't expand anymore. With current 2.6
  738. kernels, the VA space layout is different and brk() and mmap
  739. both can span the entire heap at will.
  740. Rather than using a static threshold for the brk/mmap tradeoff,
  741. we are now using a simple dynamic one. The goal is still to avoid
  742. fragmentation. The old goals we kept are
  743. 1) try to get the long lived large allocations to use mmap()
  744. 2) really large allocations should always use mmap()
  745. and we're adding now:
  746. 3) transient allocations should use brk() to avoid forcing the kernel
  747. having to zero memory over and over again
  748. The implementation works with a sliding threshold, which is by default
  749. limited to go between 128Kb and 32Mb (64Mb for 64 bitmachines) and starts
  750. out at 128Kb as per the 2001 default.
  751. This allows us to satisfy requirement 1) under the assumption that long
  752. lived allocations are made early in the process' lifespan, before it has
  753. started doing dynamic allocations of the same size (which will
  754. increase the threshold).
  755. The upperbound on the threshold satisfies requirement 2)
  756. The threshold goes up in value when the application frees memory that was
  757. allocated with the mmap allocator. The idea is that once the application
  758. starts freeing memory of a certain size, it's highly probable that this is
  759. a size the application uses for transient allocations. This estimator
  760. is there to satisfy the new third requirement.
  761. */
  762. #define M_MMAP_THRESHOLD -3
  763. #ifndef DEFAULT_MMAP_THRESHOLD
  764. #define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
  765. #endif
  766. /*
  767. M_MMAP_MAX is the maximum number of requests to simultaneously
  768. service using mmap. This parameter exists because
  769. some systems have a limited number of internal tables for
  770. use by mmap, and using more than a few of them may degrade
  771. performance.
  772. The default is set to a value that serves only as a safeguard.
  773. Setting to 0 disables use of mmap for servicing large requests.
  774. */
  775. #define M_MMAP_MAX -4
  776. #ifndef DEFAULT_MMAP_MAX
  777. #define DEFAULT_MMAP_MAX (65536)
  778. #endif
  779. #include <malloc.h>
  780. #ifndef RETURN_ADDRESS
  781. #define RETURN_ADDRESS(X_) (NULL)
  782. #endif
  783. /* Forward declarations. */
  784. struct malloc_chunk;
  785. typedef struct malloc_chunk* mchunkptr;
  786. /* Internal routines. */
  787. static void* _int_malloc(mstate, size_t);
  788. static void _int_free(mstate, mchunkptr, int);
  789. static void* _int_realloc(mstate, mchunkptr, INTERNAL_SIZE_T,
  790. INTERNAL_SIZE_T);
  791. static void* _int_memalign(mstate, size_t, size_t);
  792. static void* _mid_memalign(size_t, size_t, void *);
  793. static void malloc_printerr(const char *str) __attribute__ ((noreturn));
  794. static void* mem2mem_check(void *p, size_t sz);
  795. static void top_check(void);
  796. static void munmap_chunk(mchunkptr p);
  797. #if HAVE_MREMAP
  798. static mchunkptr mremap_chunk(mchunkptr p, size_t new_size);
  799. #endif
  800. static void* malloc_check(size_t sz, const void *caller);
  801. static void free_check(void* mem, const void *caller);
  802. static void* realloc_check(void* oldmem, size_t bytes,
  803. const void *caller);
  804. static void* memalign_check(size_t alignment, size_t bytes,
  805. const void *caller);
  806. /* ------------------ MMAP support ------------------ */
  807. #include <fcntl.h>
  808. #include <sys/mman.h>
  809. #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
  810. # define MAP_ANONYMOUS MAP_ANON
  811. #endif
  812. #ifndef MAP_NORESERVE
  813. # define MAP_NORESERVE 0
  814. #endif
  815. #define MMAP(addr, size, prot, flags) \
  816. __mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0)
  817. /*
  818. ----------------------- Chunk representations -----------------------
  819. */
  820. /*
  821. This struct declaration is misleading (but accurate and necessary).
  822. It declares a "view" into memory allowing access to necessary
  823. fields at known offsets from a given base. See explanation below.
  824. */
  825. struct malloc_chunk {
  826. INTERNAL_SIZE_T mchunk_prev_size; /* Size of previous chunk (if free). */
  827. INTERNAL_SIZE_T mchunk_size; /* Size in bytes, including overhead. */
  828. struct malloc_chunk* fd; /* double links -- used only if free. */
  829. struct malloc_chunk* bk;
  830. /* Only used for large blocks: pointer to next larger size. */
  831. struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
  832. struct malloc_chunk* bk_nextsize;
  833. };
  834. /*
  835. malloc_chunk details:
  836. (The following includes lightly edited explanations by Colin Plumb.)
  837. Chunks of memory are maintained using a `boundary tag' method as
  838. described in e.g., Knuth or Standish. (See the paper by Paul
  839. Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
  840. survey of such techniques.) Sizes of free chunks are stored both
  841. in the front of each chunk and at the end. This makes
  842. consolidating fragmented chunks into bigger chunks very fast. The
  843. size fields also hold bits representing whether chunks are free or
  844. in use.
  845. An allocated chunk looks like this:
  846. chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  847. | Size of previous chunk, if unallocated (P clear) |
  848. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  849. | Size of chunk, in bytes |A|M|P|
  850. mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  851. | User data starts here... .
  852. . .
  853. . (malloc_usable_size() bytes) .
  854. . |
  855. nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  856. | (size of chunk, but used for application data) |
  857. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  858. | Size of next chunk, in bytes |A|0|1|
  859. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  860. Where "chunk" is the front of the chunk for the purpose of most of
  861. the malloc code, but "mem" is the pointer that is returned to the
  862. user. "Nextchunk" is the beginning of the next contiguous chunk.
  863. Chunks always begin on even word boundaries, so the mem portion
  864. (which is returned to the user) is also on an even word boundary, and
  865. thus at least double-word aligned.
  866. Free chunks are stored in circular doubly-linked lists, and look like this:
  867. chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  868. | Size of previous chunk, if unallocated (P clear) |
  869. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  870. `head:' | Size of chunk, in bytes |A|0|P|
  871. mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  872. | Forward pointer to next chunk in list |
  873. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  874. | Back pointer to previous chunk in list |
  875. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  876. | Unused space (may be 0 bytes long) .
  877. . .
  878. . |
  879. nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  880. `foot:' | Size of chunk, in bytes |
  881. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  882. | Size of next chunk, in bytes |A|0|0|
  883. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  884. The P (PREV_INUSE) bit, stored in the unused low-order bit of the
  885. chunk size (which is always a multiple of two words), is an in-use
  886. bit for the *previous* chunk. If that bit is *clear*, then the
  887. word before the current chunk size contains the previous chunk
  888. size, and can be used to find the front of the previous chunk.
  889. The very first chunk allocated always has this bit set,
  890. preventing access to non-existent (or non-owned) memory. If
  891. prev_inuse is set for any given chunk, then you CANNOT determine
  892. the size of the previous chunk, and might even get a memory
  893. addressing fault when trying to do so.
  894. The A (NON_MAIN_ARENA) bit is cleared for chunks on the initial,
  895. main arena, described by the main_arena variable. When additional
  896. threads are spawned, each thread receives its own arena (up to a
  897. configurable limit, after which arenas are reused for multiple
  898. threads), and the chunks in these arenas have the A bit set. To
  899. find the arena for a chunk on such a non-main arena, heap_for_ptr
  900. performs a bit mask operation and indirection through the ar_ptr
  901. member of the per-heap header heap_info (see arena.c).
  902. Note that the `foot' of the current chunk is actually represented
  903. as the prev_size of the NEXT chunk. This makes it easier to
  904. deal with alignments etc but can be very confusing when trying
  905. to extend or adapt this code.
  906. The three exceptions to all this are:
  907. 1. The special chunk `top' doesn't bother using the
  908. trailing size field since there is no next contiguous chunk
  909. that would have to index off it. After initialization, `top'
  910. is forced to always exist. If it would become less than
  911. MINSIZE bytes long, it is replenished.
  912. 2. Chunks allocated via mmap, which have the second-lowest-order
  913. bit M (IS_MMAPPED) set in their size fields. Because they are
  914. allocated one-by-one, each must contain its own trailing size
  915. field. If the M bit is set, the other bits are ignored
  916. (because mmapped chunks are neither in an arena, nor adjacent
  917. to a freed chunk). The M bit is also used for chunks which
  918. originally came from a dumped heap via malloc_set_state in
  919. hooks.c.
  920. 3. Chunks in fastbins are treated as allocated chunks from the
  921. point of view of the chunk allocator. They are consolidated
  922. with their neighbors only in bulk, in malloc_consolidate.
  923. */
  924. /*
  925. ---------- Size and alignment checks and conversions ----------
  926. */
  927. /* conversion from malloc headers to user pointers, and back */
  928. #define chunk2mem(p) ((void*)((char*)(p) + 2*SIZE_SZ))
  929. #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
  930. /* The smallest possible chunk */
  931. #define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))
  932. /* The smallest size we can malloc is an aligned minimal chunk */
  933. #define MINSIZE \
  934. (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
  935. /* Check if m has acceptable alignment */
  936. #define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
  937. #define misaligned_chunk(p) \
  938. ((uintptr_t)(MALLOC_ALIGNMENT == 2 * SIZE_SZ ? (p) : chunk2mem (p)) \
  939. & MALLOC_ALIGN_MASK)
  940. /*
  941. Check if a request is so large that it would wrap around zero when
  942. padded and aligned. To simplify some other code, the bound is made
  943. low enough so that adding MINSIZE will also not wrap around zero.
  944. */
  945. #define REQUEST_OUT_OF_RANGE(req) \
  946. ((unsigned long) (req) >= \
  947. (unsigned long) (INTERNAL_SIZE_T) (-2 * MINSIZE))
  948. /* pad request bytes into a usable size -- internal version */
  949. #define request2size(req) \
  950. (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
  951. MINSIZE : \
  952. ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
  953. /* Same, except also perform an argument and result check. First, we check
  954. that the padding done by request2size didn't result in an integer
  955. overflow. Then we check (using REQUEST_OUT_OF_RANGE) that the resulting
  956. size isn't so large that a later alignment would lead to another integer
  957. overflow. */
  958. #define checked_request2size(req, sz) \
  959. ({ \
  960. (sz) = request2size (req); \
  961. if (((sz) < (req)) \
  962. || REQUEST_OUT_OF_RANGE (sz)) \
  963. { \
  964. __set_errno (ENOMEM); \
  965. return 0; \
  966. } \
  967. })
  968. /*
  969. --------------- Physical chunk operations ---------------
  970. */
  971. /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
  972. #define PREV_INUSE 0x1
  973. /* extract inuse bit of previous chunk */
  974. #define prev_inuse(p) ((p)->mchunk_size & PREV_INUSE)
  975. /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
  976. #define IS_MMAPPED 0x2
  977. /* check for mmap()'ed chunk */
  978. #define chunk_is_mmapped(p) ((p)->mchunk_size & IS_MMAPPED)
  979. /* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
  980. from a non-main arena. This is only set immediately before handing
  981. the chunk to the user, if necessary. */
  982. #define NON_MAIN_ARENA 0x4
  983. /* Check for chunk from main arena. */
  984. #define chunk_main_arena(p) (((p)->mchunk_size & NON_MAIN_ARENA) == 0)
  985. /* Mark a chunk as not being on the main arena. */
  986. #define set_non_main_arena(p) ((p)->mchunk_size |= NON_MAIN_ARENA)
  987. /*
  988. Bits to mask off when extracting size
  989. Note: IS_MMAPPED is intentionally not masked off from size field in
  990. macros for which mmapped chunks should never be seen. This should
  991. cause helpful core dumps to occur if it is tried by accident by
  992. people extending or adapting this malloc.
  993. */
  994. #define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
  995. /* Get size, ignoring use bits */
  996. #define chunksize(p) (chunksize_nomask (p) & ~(SIZE_BITS))
  997. /* Like chunksize, but do not mask SIZE_BITS. */
  998. #define chunksize_nomask(p) ((p)->mchunk_size)
  999. /* Ptr to next physical malloc_chunk. */
  1000. #define next_chunk(p) ((mchunkptr) (((char *) (p)) + chunksize (p)))
  1001. /* Size of the chunk below P. Only valid if !prev_inuse (P). */
  1002. #define prev_size(p) ((p)->mchunk_prev_size)
  1003. /* Set the size of the chunk below P. Only valid if !prev_inuse (P). */
  1004. #define set_prev_size(p, sz) ((p)->mchunk_prev_size = (sz))
  1005. /* Ptr to previous physical malloc_chunk. Only valid if !prev_inuse (P). */
  1006. #define prev_chunk(p) ((mchunkptr) (((char *) (p)) - prev_size (p)))
  1007. /* Treat space at ptr + offset as a chunk */
  1008. #define chunk_at_offset(p, s) ((mchunkptr) (((char *) (p)) + (s)))
  1009. /* extract p's inuse bit */
  1010. #define inuse(p) \
  1011. ((((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size) & PREV_INUSE)
  1012. /* set/clear chunk as being inuse without otherwise disturbing */
  1013. #define set_inuse(p) \
  1014. ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size |= PREV_INUSE
  1015. #define clear_inuse(p) \
  1016. ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size &= ~(PREV_INUSE)
  1017. /* check/set/clear inuse bits in known places */
  1018. #define inuse_bit_at_offset(p, s) \
  1019. (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size & PREV_INUSE)
  1020. #define set_inuse_bit_at_offset(p, s) \
  1021. (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size |= PREV_INUSE)
  1022. #define clear_inuse_bit_at_offset(p, s) \
  1023. (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size &= ~(PREV_INUSE))
  1024. /* Set size at head, without disturbing its use bit */
  1025. #define set_head_size(p, s) ((p)->mchunk_size = (((p)->mchunk_size & SIZE_BITS) | (s)))
  1026. /* Set size/use field */
  1027. #define set_head(p, s) ((p)->mchunk_size = (s))
  1028. /* Set size at footer (only when chunk is not in use) */
  1029. #define set_foot(p, s) (((mchunkptr) ((char *) (p) + (s)))->mchunk_prev_size = (s))
  1030. #pragma GCC poison mchunk_size
  1031. #pragma GCC poison mchunk_prev_size
  1032. /*
  1033. -------------------- Internal data structures --------------------
  1034. All internal state is held in an instance of malloc_state defined
  1035. below. There are no other static variables, except in two optional
  1036. cases:
  1037. * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.
  1038. * If mmap doesn't support MAP_ANONYMOUS, a dummy file descriptor
  1039. for mmap.
  1040. Beware of lots of tricks that minimize the total bookkeeping space
  1041. requirements. The result is a little over 1K bytes (for 4byte
  1042. pointers and size_t.)
  1043. */
  1044. /*
  1045. Bins
  1046. An array of bin headers for free chunks. Each bin is doubly
  1047. linked. The bins are approximately proportionally (log) spaced.
  1048. There are a lot of these bins (128). This may look excessive, but
  1049. works very well in practice. Most bins hold sizes that are
  1050. unusual as malloc request sizes, but are more usual for fragments
  1051. and consolidated sets of chunks, which is what these bins hold, so
  1052. they can be found quickly. All procedures maintain the invariant
  1053. that no consolidated chunk physically borders another one, so each
  1054. chunk in a list is known to be preceeded and followed by either
  1055. inuse chunks or the ends of memory.
  1056. Chunks in bins are kept in size order, with ties going to the
  1057. approximately least recently used chunk. Ordering isn't needed
  1058. for the small bins, which all contain the same-sized chunks, but
  1059. facilitates best-fit allocation for larger chunks. These lists
  1060. are just sequential. Keeping them in order almost never requires
  1061. enough traversal to warrant using fancier ordered data
  1062. structures.
  1063. Chunks of the same size are linked with the most
  1064. recently freed at the front, and allocations are taken from the
  1065. back. This results in LRU (FIFO) allocation order, which tends
  1066. to give each chunk an equal opportunity to be consolidated with
  1067. adjacent freed chunks, resulting in larger free chunks and less
  1068. fragmentation.
  1069. To simplify use in double-linked lists, each bin header acts
  1070. as a malloc_chunk. This avoids special-casing for headers.
  1071. But to conserve space and improve locality, we allocate
  1072. only the fd/bk pointers of bins, and then use repositioning tricks
  1073. to treat these as the fields of a malloc_chunk*.
  1074. */
  1075. typedef struct malloc_chunk *mbinptr;
  1076. /* addressing -- note that bin_at(0) does not exist */
  1077. #define bin_at(m, i) \
  1078. (mbinptr) (((char *) &((m)->bins[((i) - 1) * 2])) \
  1079. - offsetof (struct malloc_chunk, fd))
  1080. /* analog of ++bin */
  1081. #define next_bin(b) ((mbinptr) ((char *) (b) + (sizeof (mchunkptr) << 1)))
  1082. /* Reminders about list directionality within bins */
  1083. #define first(b) ((b)->fd)
  1084. #define last(b) ((b)->bk)
  1085. /*
  1086. Indexing
  1087. Bins for sizes < 512 bytes contain chunks of all the same size, spaced
  1088. 8 bytes apart. Larger bins are approximately logarithmically spaced:
  1089. 64 bins of size 8
  1090. 32 bins of size 64
  1091. 16 bins of size 512
  1092. 8 bins of size 4096
  1093. 4 bins of size 32768
  1094. 2 bins of size 262144
  1095. 1 bin of size what's left
  1096. There is actually a little bit of slop in the numbers in bin_index
  1097. for the sake of speed. This makes no difference elsewhere.
  1098. The bins top out around 1MB because we expect to service large
  1099. requests via mmap.
  1100. Bin 0 does not exist. Bin 1 is the unordered list; if that would be
  1101. a valid chunk size the small bins are bumped up one.
  1102. */
  1103. #define NBINS 128
  1104. #define NSMALLBINS 64
  1105. #define SMALLBIN_WIDTH MALLOC_ALIGNMENT
  1106. #define SMALLBIN_CORRECTION (MALLOC_ALIGNMENT > 2 * SIZE_SZ)
  1107. #define MIN_LARGE_SIZE ((NSMALLBINS - SMALLBIN_CORRECTION) * SMALLBIN_WIDTH)
  1108. #define in_smallbin_range(sz) \
  1109. ((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE)
  1110. #define smallbin_index(sz) \
  1111. ((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\
  1112. + SMALLBIN_CORRECTION)
  1113. #define largebin_index_32(sz) \
  1114. (((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\
  1115. ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
  1116. ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
  1117. ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
  1118. ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
  1119. 126)
  1120. #define largebin_index_32_big(sz) \
  1121. (((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\
  1122. ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
  1123. ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
  1124. ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
  1125. ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
  1126. 126)
  1127. // XXX It remains to be seen whether it is good to keep the widths of
  1128. // XXX the buckets the same or whether it should be scaled by a factor
  1129. // XXX of two as well.
  1130. #define largebin_index_64(sz) \
  1131. (((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\
  1132. ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
  1133. ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
  1134. ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
  1135. ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
  1136. 126)
  1137. #define largebin_index(sz) \
  1138. (SIZE_SZ == 8 ? largebin_index_64 (sz) \
  1139. : MALLOC_ALIGNMENT == 16 ? largebin_index_32_big (sz) \
  1140. : largebin_index_32 (sz))
  1141. #define bin_index(sz) \
  1142. ((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz))
  1143. /* Take a chunk off a bin list. */
  1144. static void
  1145. unlink_chunk (mstate av, mchunkptr p)
  1146. {
  1147. if (chunksize (p) != prev_size (next_chunk (p)))
  1148. malloc_printerr ("corrupted size vs. prev_size");
  1149. mchunkptr fd = p->fd;
  1150. mchunkptr bk = p->bk;
  1151. if (__builtin_expect (fd->bk != p || bk->fd != p, 0))
  1152. malloc_printerr ("corrupted double-linked list");
  1153. fd->bk = bk;
  1154. bk->fd = fd;
  1155. if (!in_smallbin_range (chunksize_nomask (p)) && p->fd_nextsize != NULL)
  1156. {
  1157. if (p->fd_nextsize->bk_nextsize != p
  1158. || p->bk_nextsize->fd_nextsize != p)
  1159. malloc_printerr ("corrupted double-linked list (not small)");
  1160. if (fd->fd_nextsize == NULL)
  1161. {
  1162. if (p->fd_nextsize == p)
  1163. fd->fd_nextsize = fd->bk_nextsize = fd;
  1164. else
  1165. {
  1166. fd->fd_nextsize = p->fd_nextsize;
  1167. fd->bk_nextsize = p->bk_nextsize;
  1168. p->fd_nextsize->bk_nextsize = fd;
  1169. p->bk_nextsize->fd_nextsize = fd;
  1170. }
  1171. }
  1172. else
  1173. {
  1174. p->fd_nextsize->bk_nextsize = p->bk_nextsize;
  1175. p->bk_nextsize->fd_nextsize = p->fd_nextsize;
  1176. }
  1177. }
  1178. }
  1179. /*
  1180. Unsorted chunks
  1181. All remainders from chunk splits, as well as all returned chunks,
  1182. are first placed in the "unsorted" bin. They are then placed
  1183. in regular bins after malloc gives them ONE chance to be used before
  1184. binning. So, basically, the unsorted_chunks list acts as a queue,
  1185. with chunks being placed on it in free (and malloc_consolidate),
  1186. and taken off (to be either used or placed in bins) in malloc.
  1187. The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
  1188. does not have to be taken into account in size comparisons.
  1189. */
  1190. /* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
  1191. #define unsorted_chunks(M) (bin_at (M, 1))
  1192. /*
  1193. Top
  1194. The top-most available chunk (i.e., the one bordering the end of
  1195. available memory) is treated specially. It is never included in
  1196. any bin, is used only if no other chunk is available, and is
  1197. released back to the system if it is very large (see
  1198. M_TRIM_THRESHOLD). Because top initially
  1199. points to its own bin with initial zero size, thus forcing
  1200. extension on the first malloc request, we avoid having any special
  1201. code in malloc to check whether it even exists yet. But we still
  1202. need to do so when getting memory from system, so we make
  1203. initial_top treat the bin as a legal but unusable chunk during the
  1204. interval between initialization and the first call to
  1205. sysmalloc. (This is somewhat delicate, since it relies on
  1206. the 2 preceding words to be zero during this interval as well.)
  1207. */
  1208. /* Conveniently, the unsorted bin can be used as dummy top on first call */
  1209. #define initial_top(M) (unsorted_chunks (M))
  1210. /*
  1211. Binmap
  1212. To help compensate for the large number of bins, a one-level index
  1213. structure is used for bin-by-bin searching. `binmap' is a
  1214. bitvector recording whether bins are definitely empty so they can
  1215. be skipped over during during traversals. The bits are NOT always
  1216. cleared as soon as bins are empty, but instead only
  1217. when they are noticed to be empty during traversal in malloc.
  1218. */
  1219. /* Conservatively use 32 bits per map word, even if on 64bit system */
  1220. #define BINMAPSHIFT 5
  1221. #define BITSPERMAP (1U << BINMAPSHIFT)
  1222. #define BINMAPSIZE (NBINS / BITSPERMAP)
  1223. #define idx2block(i) ((i) >> BINMAPSHIFT)
  1224. #define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT) - 1))))
  1225. #define mark_bin(m, i) ((m)->binmap[idx2block (i)] |= idx2bit (i))
  1226. #define unmark_bin(m, i) ((m)->binmap[idx2block (i)] &= ~(idx2bit (i)))
  1227. #define get_binmap(m, i) ((m)->binmap[idx2block (i)] & idx2bit (i))
  1228. /*
  1229. Fastbins
  1230. An array of lists holding recently freed small chunks. Fastbins
  1231. are not doubly linked. It is faster to single-link them, and
  1232. since chunks are never removed from the middles of these lists,
  1233. double linking is not necessary. Also, unlike regular bins, they
  1234. are not even processed in FIFO order (they use faster LIFO) since
  1235. ordering doesn't much matter in the transient contexts in which
  1236. fastbins are normally used.
  1237. Chunks in fastbins keep their inuse bit set, so they cannot
  1238. be consolidated with other free chunks. malloc_consolidate
  1239. releases all chunks in fastbins and consolidates them with
  1240. other free chunks.
  1241. */
  1242. typedef struct malloc_chunk *mfastbinptr;
  1243. #define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])
  1244. /* offset 2 to use otherwise unindexable first 2 bins */
  1245. #define fastbin_index(sz) \
  1246. ((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
  1247. /* The maximum fastbin request size we support */
  1248. #define MAX_FAST_SIZE (80 * SIZE_SZ / 4)
  1249. #define NFASTBINS (fastbin_index (request2size (MAX_FAST_SIZE)) + 1)
  1250. /*
  1251. FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
  1252. that triggers automatic consolidation of possibly-surrounding
  1253. fastbin chunks. This is a heuristic, so the exact value should not
  1254. matter too much. It is defined at half the default trim threshold as a
  1255. compromise heuristic to only attempt consolidation if it is likely
  1256. to lead to trimming. However, it is not dynamically tunable, since
  1257. consolidation reduces fragmentation surrounding large chunks even
  1258. if trimming is not used.
  1259. */
  1260. #define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)
  1261. /*
  1262. NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
  1263. regions. Otherwise, contiguity is exploited in merging together,
  1264. when possible, results from consecutive MORECORE calls.
  1265. The initial value comes from MORECORE_CONTIGUOUS, but is
  1266. changed dynamically if mmap is ever used as an sbrk substitute.
  1267. */
  1268. #define NONCONTIGUOUS_BIT (2U)
  1269. #define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
  1270. #define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
  1271. #define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
  1272. #define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
  1273. /* Maximum size of memory handled in fastbins. */
  1274. static INTERNAL_SIZE_T global_max_fast;
  1275. /*
  1276. Set value of max_fast.
  1277. Use impossibly small value if 0.
  1278. Precondition: there are no existing fastbin chunks in the main arena.
  1279. Since do_check_malloc_state () checks this, we call malloc_consolidate ()
  1280. before changing max_fast. Note other arenas will leak their fast bin
  1281. entries if max_fast is reduced.
  1282. */
  1283. #define set_max_fast(s) \
  1284. global_max_fast = (((s) == 0) \
  1285. ? SMALLBIN_WIDTH : ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK))
  1286. static inline INTERNAL_SIZE_T
  1287. get_max_fast (void)
  1288. {
  1289. /* Tell the GCC optimizers that global_max_fast is never larger
  1290. than MAX_FAST_SIZE. This avoids out-of-bounds array accesses in
  1291. _int_malloc after constant propagation of the size parameter.
  1292. (The code never executes because malloc preserves the
  1293. global_max_fast invariant, but the optimizers may not recognize
  1294. this.) */
  1295. if (global_max_fast > MAX_FAST_SIZE)
  1296. __builtin_unreachable ();
  1297. return global_max_fast;
  1298. }
  1299. /*
  1300. ----------- Internal state representation and initialization -----------
  1301. */
  1302. /*
  1303. have_fastchunks indicates that there are probably some fastbin chunks.
  1304. It is set true on entering a chunk into any fastbin, and cleared early in
  1305. malloc_consolidate. The value is approximate since it may be set when there
  1306. are no fastbin chunks, or it may be clear even if there are fastbin chunks
  1307. available. Given it's sole purpose is to reduce number of redundant calls to
  1308. malloc_consolidate, it does not affect correctness. As a result we can safely
  1309. use relaxed atomic accesses.
  1310. */
  1311. struct malloc_state
  1312. {
  1313. /* Serialize access. */
  1314. __libc_lock_define (, mutex);
  1315. /* Flags (formerly in max_fast). */
  1316. int flags;
  1317. /* Set if the fastbin chunks contain recently inserted free blocks. */
  1318. /* Note this is a bool but not all targets support atomics on booleans. */
  1319. int have_fastchunks;
  1320. /* Fastbins */
  1321. mfastbinptr fastbinsY[NFASTBINS];
  1322. /* Base of the topmost chunk -- not otherwise kept in a bin */
  1323. mchunkptr top;
  1324. /* The remainder from the most recent split of a small request */
  1325. mchunkptr last_remainder;
  1326. /* Normal bins packed as described above */
  1327. mchunkptr bins[NBINS * 2 - 2];
  1328. /* Bitmap of bins */
  1329. unsigned int binmap[BINMAPSIZE];
  1330. /* Linked list */
  1331. struct malloc_state *next;
  1332. /* Linked list for free arenas. Access to this field is serialized
  1333. by free_list_lock in arena.c. */
  1334. struct malloc_state *next_free;
  1335. /* Number of threads attached to this arena. 0 if the arena is on
  1336. the free list. Access to this field is serialized by
  1337. free_list_lock in arena.c. */
  1338. INTERNAL_SIZE_T attached_threads;
  1339. /* Memory allocated from the system in this arena. */
  1340. INTERNAL_SIZE_T system_mem;
  1341. INTERNAL_SIZE_T max_system_mem;
  1342. };
  1343. struct malloc_par
  1344. {
  1345. /* Tunable parameters */
  1346. unsigned long trim_threshold;
  1347. INTERNAL_SIZE_T top_pad;
  1348. INTERNAL_SIZE_T mmap_threshold;
  1349. INTERNAL_SIZE_T arena_test;
  1350. INTERNAL_SIZE_T arena_max;
  1351. /* Memory map support */
  1352. int n_mmaps;
  1353. int n_mmaps_max;
  1354. int max_n_mmaps;
  1355. /* the mmap_threshold is dynamic, until the user sets
  1356. it manually, at which point we need to disable any
  1357. dynamic behavior. */
  1358. int no_dyn_threshold;
  1359. /* Statistics */
  1360. INTERNAL_SIZE_T mmapped_mem;
  1361. INTERNAL_SIZE_T max_mmapped_mem;
  1362. /* First address handed out by MORECORE/sbrk. */
  1363. char *sbrk_base;
  1364. #if USE_TCACHE
  1365. /* Maximum number of buckets to use. */
  1366. size_t tcache_bins;
  1367. size_t tcache_max_bytes;
  1368. /* Maximum number of chunks in each bucket. */
  1369. size_t tcache_count;
  1370. /* Maximum number of chunks to remove from the unsorted list, which
  1371. aren't used to prefill the cache. */
  1372. size_t tcache_unsorted_limit;
  1373. #endif
  1374. };
  1375. /* There are several instances of this struct ("arenas") in this
  1376. malloc. If you are adapting this malloc in a way that does NOT use
  1377. a static or mmapped malloc_state, you MUST explicitly zero-fill it
  1378. before using. This malloc relies on the property that malloc_state
  1379. is initialized to all zeroes (as is true of C statics). */
  1380. static struct malloc_state main_arena =
  1381. {
  1382. .mutex = _LIBC_LOCK_INITIALIZER,
  1383. .next = &main_arena,
  1384. .attached_threads = 1
  1385. };
  1386. /* These variables are used for undumping support. Chunked are marked
  1387. as using mmap, but we leave them alone if they fall into this
  1388. range. NB: The chunk size for these chunks only includes the
  1389. initial size field (of SIZE_SZ bytes), there is no trailing size
  1390. field (unlike with regular mmapped chunks). */
  1391. static mchunkptr dumped_main_arena_start; /* Inclusive. */
  1392. static mchunkptr dumped_main_arena_end; /* Exclusive. */
  1393. /* True if the pointer falls into the dumped arena. Use this after
  1394. chunk_is_mmapped indicates a chunk is mmapped. */
  1395. #define DUMPED_MAIN_ARENA_CHUNK(p) \
  1396. ((p) >= dumped_main_arena_start && (p) < dumped_main_arena_end)
  1397. /* There is only one instance of the malloc parameters. */
  1398. static struct malloc_par mp_ =
  1399. {
  1400. .top_pad = DEFAULT_TOP_PAD,
  1401. .n_mmaps_max = DEFAULT_MMAP_MAX,
  1402. .mmap_threshold = DEFAULT_MMAP_THRESHOLD,
  1403. .trim_threshold = DEFAULT_TRIM_THRESHOLD,
  1404. #define NARENAS_FROM_NCORES(n) ((n) * (sizeof (long) == 4 ? 2 : 8))
  1405. .arena_test = NARENAS_FROM_NCORES (1)
  1406. #if USE_TCACHE
  1407. ,
  1408. .tcache_count = TCACHE_FILL_COUNT,
  1409. .tcache_bins = TCACHE_MAX_BINS,
  1410. .tcache_max_bytes = tidx2usize (TCACHE_MAX_BINS-1),
  1411. .tcache_unsorted_limit = 0 /* No limit. */
  1412. #endif
  1413. };
  1414. /*
  1415. Initialize a malloc_state struct.
  1416. This is called from ptmalloc_init () or from _int_new_arena ()
  1417. when creating a new arena.
  1418. */
  1419. static void
  1420. malloc_init_state (mstate av)
  1421. {
  1422. int i;
  1423. mbinptr bin;
  1424. /* Establish circular links for normal bins */
  1425. for (i = 1; i < NBINS; ++i)
  1426. {
  1427. bin = bin_at (av, i);
  1428. bin->fd = bin->bk = bin;
  1429. }
  1430. #if MORECORE_CONTIGUOUS
  1431. if (av != &main_arena)
  1432. #endif
  1433. set_noncontiguous (av);
  1434. if (av == &main_arena)
  1435. set_max_fast (DEFAULT_MXFAST);
  1436. atomic_store_relaxed (&av->have_fastchunks, false);
  1437. av->top = initial_top (av);
  1438. }
  1439. /*
  1440. Other internal utilities operating on mstates
  1441. */
  1442. static void *sysmalloc (INTERNAL_SIZE_T, mstate);
  1443. static int systrim (size_t, mstate);
  1444. static void malloc_consolidate (mstate);
  1445. /* -------------- Early definitions for debugging hooks ---------------- */
  1446. /* Define and initialize the hook variables. These weak definitions must
  1447. appear before any use of the variables in a function (arena.c uses one). */
  1448. #ifndef weak_variable
  1449. /* In GNU libc we want the hook variables to be weak definitions to
  1450. avoid a problem with Emacs. */
  1451. # define weak_variable weak_function
  1452. #endif
  1453. /* Forward declarations. */
  1454. static void *malloc_hook_ini (size_t sz,
  1455. const void *caller) __THROW;
  1456. static void *realloc_hook_ini (void *ptr, size_t sz,
  1457. const void *caller) __THROW;
  1458. static void *memalign_hook_ini (size_t alignment, size_t sz,
  1459. const void *caller) __THROW;
  1460. #if HAVE_MALLOC_INIT_HOOK
  1461. void weak_variable (*__malloc_initialize_hook) (void) = NULL;
  1462. compat_symbol (libc, __malloc_initialize_hook,
  1463. __malloc_initialize_hook, GLIBC_2_0);
  1464. #endif
  1465. void weak_variable (*__free_hook) (void *__ptr,
  1466. const void *) = NULL;
  1467. void *weak_variable (*__malloc_hook)
  1468. (size_t __size, const void *) = malloc_hook_ini;
  1469. void *weak_variable (*__realloc_hook)
  1470. (void *__ptr, size_t __size, const void *)
  1471. = realloc_hook_ini;
  1472. void *weak_variable (*__memalign_hook)
  1473. (size_t __alignment, size_t __size, const void *)
  1474. = memalign_hook_ini;
  1475. void weak_variable (*__after_morecore_hook) (void) = NULL;
  1476. /* This function is called from the arena shutdown hook, to free the
  1477. thread cache (if it exists). */
  1478. static void tcache_thread_shutdown (void);
  1479. /* ------------------ Testing support ----------------------------------*/
  1480. static int perturb_byte;
  1481. static void
  1482. alloc_perturb (char *p, size_t n)
  1483. {
  1484. if (__glibc_unlikely (perturb_byte))
  1485. memset (p, perturb_byte ^ 0xff, n);
  1486. }
  1487. static void
  1488. free_perturb (char *p, size_t n)
  1489. {
  1490. if (__glibc_unlikely (perturb_byte))
  1491. memset (p, perturb_byte, n);
  1492. }
  1493. #include <stap-probe.h>
  1494. /* ------------------- Support for multiple arenas -------------------- */
  1495. #include "arena.c"
  1496. /*
  1497. Debugging support
  1498. These routines make a number of assertions about the states
  1499. of data structures that should be true at all times. If any
  1500. are not true, it's very likely that a user program has somehow
  1501. trashed memory. (It's also possible that there is a coding error
  1502. in malloc. In which case, please report it!)
  1503. */
  1504. #if !MALLOC_DEBUG
  1505. # define check_chunk(A, P)
  1506. # define check_free_chunk(A, P)
  1507. # define check_inuse_chunk(A, P)
  1508. # define check_remalloced_chunk(A, P, N)
  1509. # define check_malloced_chunk(A, P, N)
  1510. # define check_malloc_state(A)
  1511. #else
  1512. # define check_chunk(A, P) do_check_chunk (A, P)
  1513. # define check_free_chunk(A, P) do_check_free_chunk (A, P)
  1514. # define check_inuse_chunk(A, P) do_check_inuse_chunk (A, P)
  1515. # define check_remalloced_chunk(A, P, N) do_check_remalloced_chunk (A, P, N)
  1516. # define check_malloced_chunk(A, P, N) do_check_malloced_chunk (A, P, N)
  1517. # define check_malloc_state(A) do_check_malloc_state (A)
  1518. /*
  1519. Properties of all chunks
  1520. */
  1521. static void
  1522. do_check_chunk (mstate av, mchunkptr p)
  1523. {
  1524. unsigned long sz = chunksize (p);
  1525. /* min and max possible addresses assuming contiguous allocation */
  1526. char *max_address = (char *) (av->top) + chunksize (av->top);
  1527. char *min_address = max_address - av->system_mem;
  1528. if (!chunk_is_mmapped (p))
  1529. {
  1530. /* Has legal address ... */
  1531. if (p != av->top)
  1532. {
  1533. if (contiguous (av))
  1534. {
  1535. assert (((char *) p) >= min_address);
  1536. assert (((char *) p + sz) <= ((char *) (av->top)));
  1537. }
  1538. }
  1539. else
  1540. {
  1541. /* top size is always at least MINSIZE */
  1542. assert ((unsigned long) (sz) >= MINSIZE);
  1543. /* top predecessor always marked inuse */
  1544. assert (prev_inuse (p));
  1545. }
  1546. }
  1547. else if (!DUMPED_MAIN_ARENA_CHUNK (p))
  1548. {
  1549. /* address is outside main heap */
  1550. if (contiguous (av) && av->top != initial_top (av))
  1551. {
  1552. assert (((char *) p) < min_address || ((char *) p) >= max_address);
  1553. }
  1554. /* chunk is page-aligned */
  1555. assert (((prev_size (p) + sz) & (GLRO (dl_pagesize) - 1)) == 0);
  1556. /* mem is aligned */
  1557. assert (aligned_OK (chunk2mem (p)));
  1558. }
  1559. }
  1560. /*
  1561. Properties of free chunks
  1562. */
  1563. static void
  1564. do_check_free_chunk (mstate av, mchunkptr p)
  1565. {
  1566. INTERNAL_SIZE_T sz = chunksize_nomask (p) & ~(PREV_INUSE | NON_MAIN_ARENA);
  1567. mchunkptr next = chunk_at_offset (p, sz);
  1568. do_check_chunk (av, p);
  1569. /* Chunk must claim to be free ... */
  1570. assert (!inuse (p));
  1571. assert (!chunk_is_mmapped (p));
  1572. /* Unless a special marker, must have OK fields */
  1573. if ((unsigned long) (sz) >= MINSIZE)
  1574. {
  1575. assert ((sz & MALLOC_ALIGN_MASK) == 0);
  1576. assert (aligned_OK (chunk2mem (p)));
  1577. /* ... matching footer field */
  1578. assert (prev_size (next_chunk (p)) == sz);
  1579. /* ... and is fully consolidated */
  1580. assert (prev_inuse (p));
  1581. assert (next == av->top || inuse (next));
  1582. /* ... and has minimally sane links */
  1583. assert (p->fd->bk == p);
  1584. assert (p->bk->fd == p);
  1585. }
  1586. else /* markers are always of size SIZE_SZ */
  1587. assert (sz == SIZE_SZ);
  1588. }
  1589. /*
  1590. Properties of inuse chunks
  1591. */
  1592. static void
  1593. do_check_inuse_chunk (mstate av, mchunkptr p)
  1594. {
  1595. mchunkptr next;
  1596. do_check_chunk (av, p);
  1597. if (chunk_is_mmapped (p))
  1598. return; /* mmapped chunks have no next/prev */
  1599. /* Check whether it claims to be in use ... */
  1600. assert (inuse (p));
  1601. next = next_chunk (p);
  1602. /* ... and is surrounded by OK chunks.
  1603. Since more things can be checked with free chunks than inuse ones,
  1604. if an inuse chunk borders them and debug is on, it's worth doing them.
  1605. */
  1606. if (!prev_inuse (p))
  1607. {
  1608. /* Note that we cannot even look at prev unless it is not inuse */
  1609. mchunkptr prv = prev_chunk (p);
  1610. assert (next_chunk (prv) == p);
  1611. do_check_free_chunk (av, prv);
  1612. }
  1613. if (next == av->top)
  1614. {
  1615. assert (prev_inuse (next));
  1616. assert (chunksize (next) >= MINSIZE);
  1617. }
  1618. else if (!inuse (next))
  1619. do_check_free_chunk (av, next);
  1620. }
  1621. /*
  1622. Properties of chunks recycled from fastbins
  1623. */
  1624. static void
  1625. do_check_remalloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
  1626. {
  1627. INTERNAL_SIZE_T sz = chunksize_nomask (p) & ~(PREV_INUSE | NON_MAIN_ARENA);
  1628. if (!chunk_is_mmapped (p))
  1629. {
  1630. assert (av == arena_for_chunk (p));
  1631. if (chunk_main_arena (p))
  1632. assert (av == &main_arena);
  1633. else
  1634. assert (av != &main_arena);
  1635. }
  1636. do_check_inuse_chunk (av, p);
  1637. /* Legal size ... */
  1638. assert ((sz & MALLOC_ALIGN_MASK) == 0);
  1639. assert ((unsigned long) (sz) >= MINSIZE);
  1640. /* ... and alignment */
  1641. assert (aligned_OK (chunk2mem (p)));
  1642. /* chunk is less than MINSIZE more than request */
  1643. assert ((long) (sz) - (long) (s) >= 0);
  1644. assert ((long) (sz) - (long) (s + MINSIZE) < 0);
  1645. }
  1646. /*
  1647. Properties of nonrecycled chunks at the point they are malloced
  1648. */
  1649. static void
  1650. do_check_malloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
  1651. {
  1652. /* same as recycled case ... */
  1653. do_check_remalloced_chunk (av, p, s);
  1654. /*
  1655. ... plus, must obey implementation invariant that prev_inuse is
  1656. always true of any allocated chunk; i.e., that each allocated
  1657. chunk borders either a previously allocated and still in-use
  1658. chunk, or the base of its memory arena. This is ensured
  1659. by making all allocations from the `lowest' part of any found
  1660. chunk. This does not necessarily hold however for chunks
  1661. recycled via fastbins.
  1662. */
  1663. assert (prev_inuse (p));
  1664. }
  1665. /*
  1666. Properties of malloc_state.
  1667. This may be useful for debugging malloc, as well as detecting user
  1668. programmer errors that somehow write into malloc_state.
  1669. If you are extending or experimenting with this malloc, you can
  1670. probably figure out how to hack this routine to print out or
  1671. display chunk addresses, sizes, bins, and other instrumentation.
  1672. */
  1673. static void
  1674. do_check_malloc_state (mstate av)
  1675. {
  1676. int i;
  1677. mchunkptr p;
  1678. mchunkptr q;
  1679. mbinptr b;
  1680. unsigned int idx;
  1681. INTERNAL_SIZE_T size;
  1682. unsigned long total = 0;
  1683. int max_fast_bin;
  1684. /* internal size_t must be no wider than pointer type */
  1685. assert (sizeof (INTERNAL_SIZE_T) <= sizeof (char *));
  1686. /* alignment is a power of 2 */
  1687. assert ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - 1)) == 0);
  1688. /* Check the arena is initialized. */
  1689. assert (av->top != 0);
  1690. /* No memory has been allocated yet, so doing more tests is not possible. */
  1691. if (av->top == initial_top (av))
  1692. return;
  1693. /* pagesize is a power of 2 */
  1694. assert (powerof2(GLRO (dl_pagesize)));
  1695. /* A contiguous main_arena is consistent with sbrk_base. */
  1696. if (av == &main_arena && contiguous (av))
  1697. assert ((char *) mp_.sbrk_base + av->system_mem ==
  1698. (char *) av->top + chunksize (av->top));
  1699. /* properties of fastbins */
  1700. /* max_fast is in allowed range */
  1701. assert ((get_max_fast () & ~1) <= request2size (MAX_FAST_SIZE));
  1702. max_fast_bin = fastbin_index (get_max_fast ());
  1703. for (i = 0; i < NFASTBINS; ++i)
  1704. {
  1705. p = fastbin (av, i);
  1706. /* The following test can only be performed for the main arena.
  1707. While mallopt calls malloc_consolidate to get rid of all fast
  1708. bins (especially those larger than the new maximum) this does
  1709. only happen for the main arena. Trying to do this for any
  1710. other arena would mean those arenas have to be locked and
  1711. malloc_consolidate be called for them. This is excessive. And
  1712. even if this is acceptable to somebody it still cannot solve
  1713. the problem completely since if the arena is locked a
  1714. concurrent malloc call might create a new arena which then
  1715. could use the newly invalid fast bins. */
  1716. /* all bins past max_fast are empty */
  1717. if (av == &main_arena && i > max_fast_bin)
  1718. assert (p == 0);
  1719. while (p != 0)
  1720. {
  1721. /* each chunk claims to be inuse */
  1722. do_check_inuse_chunk (av, p);
  1723. total += chunksize (p);
  1724. /* chunk belongs in this bin */
  1725. assert (fastbin_index (chunksize (p)) == i);
  1726. p = p->fd;
  1727. }
  1728. }
  1729. /* check normal bins */
  1730. for (i = 1; i < NBINS; ++i)
  1731. {
  1732. b = bin_at (av, i);
  1733. /* binmap is accurate (except for bin 1 == unsorted_chunks) */
  1734. if (i >= 2)
  1735. {
  1736. unsigned int binbit = get_binmap (av, i);
  1737. int empty = last (b) == b;
  1738. if (!binbit)
  1739. assert (empty);
  1740. else if (!empty)
  1741. assert (binbit);
  1742. }
  1743. for (p = last (b); p != b; p = p->bk)
  1744. {
  1745. /* each chunk claims to be free */
  1746. do_check_free_chunk (av, p);
  1747. size = chunksize (p);
  1748. total += size;
  1749. if (i >= 2)
  1750. {
  1751. /* chunk belongs in bin */
  1752. idx = bin_index (size);
  1753. assert (idx == i);
  1754. /* lists are sorted */
  1755. assert (p->bk == b ||
  1756. (unsigned long) chunksize (p->bk) >= (unsigned long) chunksize (p));
  1757. if (!in_smallbin_range (size))
  1758. {
  1759. if (p->fd_nextsize != NULL)
  1760. {
  1761. if (p->fd_nextsize == p)
  1762. assert (p->bk_nextsize == p);
  1763. else
  1764. {
  1765. if (p->fd_nextsize == first (b))
  1766. assert (chunksize (p) < chunksize (p->fd_nextsize));
  1767. else
  1768. assert (chunksize (p) > chunksize (p->fd_nextsize));
  1769. if (p == first (b))
  1770. assert (chunksize (p) > chunksize (p->bk_nextsize));
  1771. else
  1772. assert (chunksize (p) < chunksize (p->bk_nextsize));
  1773. }
  1774. }
  1775. else
  1776. assert (p->bk_nextsize == NULL);
  1777. }
  1778. }
  1779. else if (!in_smallbin_range (size))
  1780. assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL);
  1781. /* chunk is followed by a legal chain of inuse chunks */
  1782. for (q = next_chunk (p);
  1783. (q != av->top && inuse (q) &&
  1784. (unsigned long) (chunksize (q)) >= MINSIZE);
  1785. q = next_chunk (q))
  1786. do_check_inuse_chunk (av, q);
  1787. }
  1788. }
  1789. /* top chunk is OK */
  1790. check_chunk (av, av->top);
  1791. }
  1792. #endif
  1793. /* ----------------- Support for debugging hooks -------------------- */
  1794. #include "hooks.c"
  1795. /* ----------- Routines dealing with system allocation -------------- */
  1796. /*
  1797. sysmalloc handles malloc cases requiring more memory from the system.
  1798. On entry, it is assumed that av->top does not have enough
  1799. space to service request for nb bytes, thus requiring that av->top
  1800. be extended or replaced.
  1801. */
  1802. static void *
  1803. sysmalloc (INTERNAL_SIZE_T nb, mstate av)
  1804. {
  1805. mchunkptr old_top; /* incoming value of av->top */
  1806. INTERNAL_SIZE_T old_size; /* its size */
  1807. char *old_end; /* its end address */
  1808. long size; /* arg to first MORECORE or mmap call */
  1809. char *brk; /* return value from MORECORE */
  1810. long correction; /* arg to 2nd MORECORE call */
  1811. char *snd_brk; /* 2nd return val */
  1812. INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
  1813. INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
  1814. char *aligned_brk; /* aligned offset into brk */
  1815. mchunkptr p; /* the allocated/returned chunk */
  1816. mchunkptr remainder; /* remainder from allocation */
  1817. unsigned long remainder_size; /* its size */
  1818. size_t pagesize = GLRO (dl_pagesize);
  1819. bool tried_mmap = false;
  1820. /*
  1821. If have mmap, and the request size meets the mmap threshold, and
  1822. the system supports mmap, and there are few enough currently
  1823. allocated mmapped regions, try to directly map this request
  1824. rather than expanding top.
  1825. */
  1826. if (av == NULL
  1827. || ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold)
  1828. && (mp_.n_mmaps < mp_.n_mmaps_max)))
  1829. {
  1830. char *mm; /* return value from mmap call*/
  1831. try_mmap:
  1832. /*
  1833. Round up size to nearest page. For mmapped chunks, the overhead
  1834. is one SIZE_SZ unit larger than for normal chunks, because there
  1835. is no following chunk whose prev_size field could be used.
  1836. See the front_misalign handling below, for glibc there is no
  1837. need for further alignments unless we have have high alignment.
  1838. */
  1839. if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
  1840. size = ALIGN_UP (nb + SIZE_SZ, pagesize);
  1841. else
  1842. size = ALIGN_UP (nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize);
  1843. tried_mmap = true;
  1844. /* Don't try if size wraps around 0 */
  1845. if ((unsigned long) (size) > (unsigned long) (nb))
  1846. {
  1847. mm = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0));
  1848. if (mm != MAP_FAILED)
  1849. {
  1850. /*
  1851. The offset to the start of the mmapped region is stored
  1852. in the prev_size field of the chunk. This allows us to adjust
  1853. returned start address to meet alignment requirements here
  1854. and in memalign(), and still be able to compute proper
  1855. address argument for later munmap in free() and realloc().
  1856. */
  1857. if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
  1858. {
  1859. /* For glibc, chunk2mem increases the address by 2*SIZE_SZ and
  1860. MALLOC_ALIGN_MASK is 2*SIZE_SZ-1. Each mmap'ed area is page
  1861. aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */
  1862. assert (((INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK) == 0);
  1863. front_misalign = 0;
  1864. }
  1865. else
  1866. front_misalign = (INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK;
  1867. if (front_misalign > 0)
  1868. {
  1869. correction = MALLOC_ALIGNMENT - front_misalign;
  1870. p = (mchunkptr) (mm + correction);
  1871. set_prev_size (p, correction);
  1872. set_head (p, (size - correction) | IS_MMAPPED);
  1873. }
  1874. else
  1875. {
  1876. p = (mchunkptr) mm;
  1877. set_prev_size (p, 0);
  1878. set_head (p, size | IS_MMAPPED);
  1879. }
  1880. /* update statistics */
  1881. int new = atomic_exchange_and_add (&mp_.n_mmaps, 1) + 1;
  1882. atomic_max (&mp_.max_n_mmaps, new);
  1883. unsigned long sum;
  1884. sum = atomic_exchange_and_add (&mp_.mmapped_mem, size) + size;
  1885. atomic_max (&mp_.max_mmapped_mem, sum);
  1886. check_chunk (av, p);
  1887. return chunk2mem (p);
  1888. }
  1889. }
  1890. }
  1891. /* There are no usable arenas and mmap also failed. */
  1892. if (av == NULL)
  1893. return 0;
  1894. /* Record incoming configuration of top */
  1895. old_top = av->top;
  1896. old_size = chunksize (old_top);
  1897. old_end = (char *) (chunk_at_offset (old_top, old_size));
  1898. brk = snd_brk = (char *) (MORECORE_FAILURE);
  1899. /*
  1900. If not the first time through, we require old_size to be
  1901. at least MINSIZE and to have prev_inuse set.
  1902. */
  1903. assert ((old_top == initial_top (av) && old_size == 0) ||
  1904. ((unsigned long) (old_size) >= MINSIZE &&
  1905. prev_inuse (old_top) &&
  1906. ((unsigned long) old_end & (pagesize - 1)) == 0));
  1907. /* Precondition: not enough current space to satisfy nb request */
  1908. assert ((unsigned long) (old_size) < (unsigned long) (nb + MINSIZE));
  1909. if (av != &main_arena)
  1910. {
  1911. heap_info *old_heap, *heap;
  1912. size_t old_heap_size;
  1913. /* First try to extend the current heap. */
  1914. old_heap = heap_for_ptr (old_top);
  1915. old_heap_size = old_heap->size;
  1916. if ((long) (MINSIZE + nb - old_size) > 0
  1917. && grow_heap (old_heap, MINSIZE + nb - old_size) == 0)
  1918. {
  1919. av->system_mem += old_heap->size - old_heap_size;
  1920. set_head (old_top, (((char *) old_heap + old_heap->size) - (char *) old_top)
  1921. | PREV_INUSE);
  1922. }
  1923. else if ((heap = new_heap (nb + (MINSIZE + sizeof (*heap)), mp_.top_pad)))
  1924. {
  1925. /* Use a newly allocated heap. */
  1926. heap->ar_ptr = av;
  1927. heap->prev = old_heap;
  1928. av->system_mem += heap->size;
  1929. /* Set up the new top. */
  1930. top (av) = chunk_at_offset (heap, sizeof (*heap));
  1931. set_head (top (av), (heap->size - sizeof (*heap)) | PREV_INUSE);
  1932. /* Setup fencepost and free the old top chunk with a multiple of
  1933. MALLOC_ALIGNMENT in size. */
  1934. /* The fencepost takes at least MINSIZE bytes, because it might
  1935. become the top chunk again later. Note that a footer is set
  1936. up, too, although the chunk is marked in use. */
  1937. old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK;
  1938. set_head (chunk_at_offset (old_top, old_size + 2 * SIZE_SZ), 0 | PREV_INUSE);
  1939. if (old_size >= MINSIZE)
  1940. {
  1941. set_head (chunk_at_offset (old_top, old_size), (2 * SIZE_SZ) | PREV_INUSE);
  1942. set_foot (chunk_at_offset (old_top, old_size), (2 * SIZE_SZ));
  1943. set_head (old_top, old_size | PREV_INUSE | NON_MAIN_ARENA);
  1944. _int_free (av, old_top, 1);
  1945. }
  1946. else
  1947. {
  1948. set_head (old_top, (old_size + 2 * SIZE_SZ) | PREV_INUSE);
  1949. set_foot (old_top, (old_size + 2 * SIZE_SZ));
  1950. }
  1951. }
  1952. else if (!tried_mmap)
  1953. /* We can at least try to use to mmap memory. */
  1954. goto try_mmap;
  1955. }
  1956. else /* av == main_arena */
  1957. { /* Request enough space for nb + pad + overhead */
  1958. size = nb + mp_.top_pad + MINSIZE;
  1959. /*
  1960. If contiguous, we can subtract out existing space that we hope to
  1961. combine with new space. We add it back later only if
  1962. we don't actually get contiguous space.
  1963. */
  1964. if (contiguous (av))
  1965. size -= old_size;
  1966. /*
  1967. Round to a multiple of page size.
  1968. If MORECORE is not contiguous, this ensures that we only call it
  1969. with whole-page arguments. And if MORECORE is contiguous and
  1970. this is not first time through, this preserves page-alignment of
  1971. previous calls. Otherwise, we correct to page-align below.
  1972. */
  1973. size = ALIGN_UP (size, pagesize);
  1974. /*
  1975. Don't try to call MORECORE if argument is so big as to appear
  1976. negative. Note that since mmap takes size_t arg, it may succeed
  1977. below even if we cannot call MORECORE.
  1978. */
  1979. if (size > 0)
  1980. {
  1981. brk = (char *) (MORECORE (size));
  1982. LIBC_PROBE (memory_sbrk_more, 2, brk, size);
  1983. }
  1984. if (brk != (char *) (MORECORE_FAILURE))
  1985. {
  1986. /* Call the `morecore' hook if necessary. */
  1987. void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
  1988. if (__builtin_expect (hook != NULL, 0))
  1989. (*hook)();
  1990. }
  1991. else
  1992. {
  1993. /*
  1994. If have mmap, try using it as a backup when MORECORE fails or
  1995. cannot be used. This is worth doing on systems that have "holes" in
  1996. address space, so sbrk cannot extend to give contiguous space, but
  1997. space is available elsewhere. Note that we ignore mmap max count
  1998. and threshold limits, since the space will not be used as a
  1999. segregated mmap region.
  2000. */
  2001. /* Cannot merge with old top, so add its size back in */
  2002. if (contiguous (av))
  2003. size = ALIGN_UP (size + old_size, pagesize);
  2004. /* If we are relying on mmap as backup, then use larger units */
  2005. if ((unsigned long) (size) < (unsigned long) (MMAP_AS_MORECORE_SIZE))
  2006. size = MMAP_AS_MORECORE_SIZE;
  2007. /* Don't try if size wraps around 0 */
  2008. if ((unsigned long) (size) > (unsigned long) (nb))
  2009. {
  2010. char *mbrk = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0));
  2011. if (mbrk != MAP_FAILED)
  2012. {
  2013. /* We do not need, and cannot use, another sbrk call to find end */
  2014. brk = mbrk;
  2015. snd_brk = brk + size;
  2016. /*
  2017. Record that we no longer have a contiguous sbrk region.
  2018. After the first time mmap is used as backup, we do not
  2019. ever rely on contiguous space since this could incorrectly
  2020. bridge regions.
  2021. */
  2022. set_noncontiguous (av);
  2023. }
  2024. }
  2025. }
  2026. if (brk != (char *) (MORECORE_FAILURE))
  2027. {
  2028. if (mp_.sbrk_base == 0)
  2029. mp_.sbrk_base = brk;
  2030. av->system_mem += size;
  2031. /*
  2032. If MORECORE extends previous space, we can likewise extend top size.
  2033. */
  2034. if (brk == old_end && snd_brk == (char *) (MORECORE_FAILURE))
  2035. set_head (old_top, (size + old_size) | PREV_INUSE);
  2036. else if (contiguous (av) && old_size && brk < old_end)
  2037. /* Oops! Someone else killed our space.. Can't touch anything. */
  2038. malloc_printerr ("break adjusted to free malloc space");
  2039. /*
  2040. Otherwise, make adjustments:
  2041. * If the first time through or noncontiguous, we need to call sbrk
  2042. just to find out where the end of memory lies.
  2043. * We need to ensure that all returned chunks from malloc will meet
  2044. MALLOC_ALIGNMENT
  2045. * If there was an intervening foreign sbrk, we need to adjust sbrk
  2046. request size to account for fact that we will not be able to
  2047. combine new space with existing space in old_top.
  2048. * Almost all systems internally allocate whole pages at a time, in
  2049. which case we might as well use the whole last page of request.
  2050. So we allocate enough more memory to hit a page boundary now,
  2051. which in turn causes future contiguous calls to page-align.
  2052. */
  2053. else
  2054. {
  2055. front_misalign = 0;
  2056. end_misalign = 0;
  2057. correction = 0;
  2058. aligned_brk = brk;
  2059. /* handle contiguous cases */
  2060. if (contiguous (av))
  2061. {
  2062. /* Count foreign sbrk as system_mem. */
  2063. if (old_size)
  2064. av->system_mem += brk - old_end;
  2065. /* Guarantee alignment of first new chunk made from this space */
  2066. front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
  2067. if (front_misalign > 0)
  2068. {
  2069. /*
  2070. Skip over some bytes to arrive at an aligned position.
  2071. We don't need to specially mark these wasted front bytes.
  2072. They will never be accessed anyway because
  2073. prev_inuse of av->top (and any chunk created from its start)
  2074. is always true after initialization.
  2075. */
  2076. correction = MALLOC_ALIGNMENT - front_misalign;
  2077. aligned_brk += correction;
  2078. }
  2079. /*
  2080. If this isn't adjacent to existing space, then we will not
  2081. be able to merge with old_top space, so must add to 2nd request.
  2082. */
  2083. correction += old_size;
  2084. /* Extend the end address to hit a page boundary */
  2085. end_misalign = (INTERNAL_SIZE_T) (brk + size + correction);
  2086. correction += (ALIGN_UP (end_misalign, pagesize)) - end_misalign;
  2087. assert (correction >= 0);
  2088. snd_brk = (char *) (MORECORE (correction));
  2089. /*
  2090. If can't allocate correction, try to at least find out current
  2091. brk. It might be enough to proceed without failing.
  2092. Note that if second sbrk did NOT fail, we assume that space
  2093. is contiguous with first sbrk. This is a safe assumption unless
  2094. program is multithreaded but doesn't use locks and a foreign sbrk
  2095. occurred between our first and second calls.
  2096. */
  2097. if (snd_brk == (char *) (MORECORE_FAILURE))
  2098. {
  2099. correction = 0;
  2100. snd_brk = (char *) (MORECORE (0));
  2101. }
  2102. else
  2103. {
  2104. /* Call the `morecore' hook if necessary. */
  2105. void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
  2106. if (__builtin_expect (hook != NULL, 0))
  2107. (*hook)();
  2108. }
  2109. }
  2110. /* handle non-contiguous cases */
  2111. else
  2112. {
  2113. if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
  2114. /* MORECORE/mmap must correctly align */
  2115. assert (((unsigned long) chunk2mem (brk) & MALLOC_ALIGN_MASK) == 0);
  2116. else
  2117. {
  2118. front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
  2119. if (front_misalign > 0)
  2120. {
  2121. /*
  2122. Skip over some bytes to arrive at an aligned position.
  2123. We don't need to specially mark these wasted front bytes.
  2124. They will never be accessed anyway because
  2125. prev_inuse of av->top (and any chunk created from its start)
  2126. is always true after initialization.
  2127. */
  2128. aligned_brk += MALLOC_ALIGNMENT - front_misalign;
  2129. }
  2130. }
  2131. /* Find out current end of memory */
  2132. if (snd_brk == (char *) (MORECORE_FAILURE))
  2133. {
  2134. snd_brk = (char *) (MORECORE (0));
  2135. }
  2136. }
  2137. /* Adjust top based on results of second sbrk */
  2138. if (snd_brk != (char *) (MORECORE_FAILURE))
  2139. {
  2140. av->top = (mchunkptr) aligned_brk;
  2141. set_head (av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
  2142. av->system_mem += correction;
  2143. /*
  2144. If not the first time through, we either have a
  2145. gap due to foreign sbrk or a non-contiguous region. Insert a
  2146. double fencepost at old_top to prevent consolidation with space
  2147. we don't own. These fenceposts are artificial chunks that are
  2148. marked as inuse and are in any case too small to use. We need
  2149. two to make sizes and alignments work out.
  2150. */
  2151. if (old_size != 0)
  2152. {
  2153. /*
  2154. Shrink old_top to insert fenceposts, keeping size a
  2155. multiple of MALLOC_ALIGNMENT. We know there is at least
  2156. enough space in old_top to do this.
  2157. */
  2158. old_size = (old_size - 4 * SIZE_SZ) & ~MALLOC_ALIGN_MASK;
  2159. set_head (old_top, old_size | PREV_INUSE);
  2160. /*
  2161. Note that the following assignments completely overwrite
  2162. old_top when old_size was previously MINSIZE. This is
  2163. intentional. We need the fencepost, even if old_top otherwise gets
  2164. lost.
  2165. */
  2166. set_head (chunk_at_offset (old_top, old_size),
  2167. (2 * SIZE_SZ) | PREV_INUSE);
  2168. set_head (chunk_at_offset (old_top, old_size + 2 * SIZE_SZ),
  2169. (2 * SIZE_SZ) | PREV_INUSE);
  2170. /* If possible, release the rest. */
  2171. if (old_size >= MINSIZE)
  2172. {
  2173. _int_free (av, old_top, 1);
  2174. }
  2175. }
  2176. }
  2177. }
  2178. }
  2179. } /* if (av != &main_arena) */
  2180. if ((unsigned long) av->system_mem > (unsigned long) (av->max_system_mem))
  2181. av->max_system_mem = av->system_mem;
  2182. check_malloc_state (av);
  2183. /* finally, do the allocation */
  2184. p = av->top;
  2185. size = chunksize (p);
  2186. /* check that one of the above allocation paths succeeded */
  2187. if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
  2188. {
  2189. remainder_size = size - nb;
  2190. remainder = chunk_at_offset (p, nb);
  2191. av->top = remainder;
  2192. set_head (p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
  2193. set_head (remainder, remainder_size | PREV_INUSE);
  2194. check_malloced_chunk (av, p, nb);
  2195. return chunk2mem (p);
  2196. }
  2197. /* catch all failure paths */
  2198. __set_errno (ENOMEM);
  2199. return 0;
  2200. }
  2201. /*
  2202. systrim is an inverse of sorts to sysmalloc. It gives memory back
  2203. to the system (via negative arguments to sbrk) if there is unused
  2204. memory at the `high' end of the malloc pool. It is called
  2205. automatically by free() when top space exceeds the trim
  2206. threshold. It is also called by the public malloc_trim routine. It
  2207. returns 1 if it actually released any memory, else 0.
  2208. */
  2209. static int
  2210. systrim (size_t pad, mstate av)
  2211. {
  2212. long top_size; /* Amount of top-most memory */
  2213. long extra; /* Amount to release */
  2214. long released; /* Amount actually released */
  2215. char *current_brk; /* address returned by pre-check sbrk call */
  2216. char *new_brk; /* address returned by post-check sbrk call */
  2217. size_t pagesize;
  2218. long top_area;
  2219. pagesize = GLRO (dl_pagesize);
  2220. top_size = chunksize (av->top);
  2221. top_area = top_size - MINSIZE - 1;
  2222. if (top_area <= pad)
  2223. return 0;
  2224. /* Release in pagesize units and round down to the nearest page. */
  2225. extra = ALIGN_DOWN(top_area - pad, pagesize);
  2226. if (extra == 0)
  2227. return 0;
  2228. /*
  2229. Only proceed if end of memory is where we last set it.
  2230. This avoids problems if there were foreign sbrk calls.
  2231. */
  2232. current_brk = (char *) (MORECORE (0));
  2233. if (current_brk == (char *) (av->top) + top_size)
  2234. {
  2235. /*
  2236. Attempt to release memory. We ignore MORECORE return value,
  2237. and instead call again to find out where new end of memory is.
  2238. This avoids problems if first call releases less than we asked,
  2239. of if failure somehow altered brk value. (We could still
  2240. encounter problems if it altered brk in some very bad way,
  2241. but the only thing we can do is adjust anyway, which will cause
  2242. some downstream failure.)
  2243. */
  2244. MORECORE (-extra);
  2245. /* Call the `morecore' hook if necessary. */
  2246. void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
  2247. if (__builtin_expect (hook != NULL, 0))
  2248. (*hook)();
  2249. new_brk = (char *) (MORECORE (0));
  2250. LIBC_PROBE (memory_sbrk_less, 2, new_brk, extra);
  2251. if (new_brk != (char *) MORECORE_FAILURE)
  2252. {
  2253. released = (long) (current_brk - new_brk);
  2254. if (released != 0)
  2255. {
  2256. /* Success. Adjust top. */
  2257. av->system_mem -= released;
  2258. set_head (av->top, (top_size - released) | PREV_INUSE);
  2259. check_malloc_state (av);
  2260. return 1;
  2261. }
  2262. }
  2263. }
  2264. return 0;
  2265. }
  2266. static void
  2267. munmap_chunk (mchunkptr p)
  2268. {
  2269. size_t pagesize = GLRO (dl_pagesize);
  2270. INTERNAL_SIZE_T size = chunksize (p);
  2271. assert (chunk_is_mmapped (p));
  2272. /* Do nothing if the chunk is a faked mmapped chunk in the dumped
  2273. main arena. We never free this memory. */
  2274. if (DUMPED_MAIN_ARENA_CHUNK (p))
  2275. return;
  2276. uintptr_t mem = (uintptr_t) chunk2mem (p);
  2277. uintptr_t block = (uintptr_t) p - prev_size (p);
  2278. size_t total_size = prev_size (p) + size;
  2279. /* Unfortunately we have to do the compilers job by hand here. Normally
  2280. we would test BLOCK and TOTAL-SIZE separately for compliance with the
  2281. page size. But gcc does not recognize the optimization possibility
  2282. (in the moment at least) so we combine the two values into one before
  2283. the bit test. */
  2284. if (__glibc_unlikely ((block | total_size) & (pagesize - 1)) != 0
  2285. || __glibc_unlikely (!powerof2 (mem & (pagesize - 1))))
  2286. malloc_printerr ("munmap_chunk(): invalid pointer");
  2287. atomic_decrement (&mp_.n_mmaps);
  2288. atomic_add (&mp_.mmapped_mem, -total_size);
  2289. /* If munmap failed the process virtual memory address space is in a
  2290. bad shape. Just leave the block hanging around, the process will
  2291. terminate shortly anyway since not much can be done. */
  2292. __munmap ((char *) block, total_size);
  2293. }
  2294. #if HAVE_MREMAP
  2295. static mchunkptr
  2296. mremap_chunk (mchunkptr p, size_t new_size)
  2297. {
  2298. size_t pagesize = GLRO (dl_pagesize);
  2299. INTERNAL_SIZE_T offset = prev_size (p);
  2300. INTERNAL_SIZE_T size = chunksize (p);
  2301. char *cp;
  2302. assert (chunk_is_mmapped (p));
  2303. uintptr_t block = (uintptr_t) p - offset;
  2304. uintptr_t mem = (uintptr_t) chunk2mem(p);
  2305. size_t total_size = offset + size;
  2306. if (__glibc_unlikely ((block | total_size) & (pagesize - 1)) != 0
  2307. || __glibc_unlikely (!powerof2 (mem & (pagesize - 1))))
  2308. malloc_printerr("mremap_chunk(): invalid pointer");
  2309. /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
  2310. new_size = ALIGN_UP (new_size + offset + SIZE_SZ, pagesize);
  2311. /* No need to remap if the number of pages does not change. */
  2312. if (total_size == new_size)
  2313. return p;
  2314. cp = (char *) __mremap ((char *) block, total_size, new_size,
  2315. MREMAP_MAYMOVE);
  2316. if (cp == MAP_FAILED)
  2317. return 0;
  2318. p = (mchunkptr) (cp + offset);
  2319. assert (aligned_OK (chunk2mem (p)));
  2320. assert (prev_size (p) == offset);
  2321. set_head (p, (new_size - offset) | IS_MMAPPED);
  2322. INTERNAL_SIZE_T new;
  2323. new = atomic_exchange_and_add (&mp_.mmapped_mem, new_size - size - offset)
  2324. + new_size - size - offset;
  2325. atomic_max (&mp_.max_mmapped_mem, new);
  2326. return p;
  2327. }
  2328. #endif /* HAVE_MREMAP */
  2329. /*------------------------ Public wrappers. --------------------------------*/
  2330. #if USE_TCACHE
  2331. /* We overlay this structure on the user-data portion of a chunk when
  2332. the chunk is stored in the per-thread cache. */
  2333. typedef struct tcache_entry
  2334. {
  2335. struct tcache_entry *next;
  2336. /* This field exists to detect double frees. */
  2337. struct tcache_perthread_struct *key;
  2338. } tcache_entry;
  2339. /* There is one of these for each thread, which contains the
  2340. per-thread cache (hence "tcache_perthread_struct"). Keeping
  2341. overall size low is mildly important. Note that COUNTS and ENTRIES
  2342. are redundant (we could have just counted the linked list each
  2343. time), this is for performance reasons. */
  2344. typedef struct tcache_perthread_struct
  2345. {
  2346. char counts[TCACHE_MAX_BINS];
  2347. tcache_entry *entries[TCACHE_MAX_BINS];
  2348. } tcache_perthread_struct;
  2349. static __thread bool tcache_shutting_down = false;
  2350. static __thread tcache_perthread_struct *tcache = NULL;
  2351. /* Caller must ensure that we know tc_idx is valid and there's room
  2352. for more chunks. */
  2353. static __always_inline void
  2354. tcache_put (mchunkptr chunk, size_t tc_idx)
  2355. {
  2356. tcache_entry *e = (tcache_entry *) chunk2mem (chunk);
  2357. assert (tc_idx < TCACHE_MAX_BINS);
  2358. /* Mark this chunk as "in the tcache" so the test in _int_free will
  2359. detect a double free. */
  2360. e->key = tcache;
  2361. e->next = tcache->entries[tc_idx];
  2362. tcache->entries[tc_idx] = e;
  2363. ++(tcache->counts[tc_idx]);
  2364. }
  2365. /* Caller must ensure that we know tc_idx is valid and there's
  2366. available chunks to remove. */
  2367. static __always_inline void *
  2368. tcache_get (size_t tc_idx)
  2369. {
  2370. tcache_entry *e = tcache->entries[tc_idx];
  2371. assert (tc_idx < TCACHE_MAX_BINS);
  2372. assert (tcache->entries[tc_idx] > 0);
  2373. tcache->entries[tc_idx] = e->next;
  2374. --(tcache->counts[tc_idx]);
  2375. e->key = NULL;
  2376. return (void *) e;
  2377. }
  2378. static void
  2379. tcache_thread_shutdown (void)
  2380. {
  2381. int i;
  2382. tcache_perthread_struct *tcache_tmp = tcache;
  2383. if (!tcache)
  2384. return;
  2385. /* Disable the tcache and prevent it from being reinitialized. */
  2386. tcache = NULL;
  2387. tcache_shutting_down = true;
  2388. /* Free all of the entries and the tcache itself back to the arena
  2389. heap for coalescing. */
  2390. for (i = 0; i < TCACHE_MAX_BINS; ++i)
  2391. {
  2392. while (tcache_tmp->entries[i])
  2393. {
  2394. tcache_entry *e = tcache_tmp->entries[i];
  2395. tcache_tmp->entries[i] = e->next;
  2396. __libc_free (e);
  2397. }
  2398. }
  2399. __libc_free (tcache_tmp);
  2400. }
  2401. static void
  2402. tcache_init(void)
  2403. {
  2404. mstate ar_ptr;
  2405. void *victim = 0;
  2406. const size_t bytes = sizeof (tcache_perthread_struct);
  2407. if (tcache_shutting_down)
  2408. return;
  2409. arena_get (ar_ptr, bytes);
  2410. victim = _int_malloc (ar_ptr, bytes);
  2411. if (!victim && ar_ptr != NULL)
  2412. {
  2413. ar_ptr = arena_get_retry (ar_ptr, bytes);
  2414. victim = _int_malloc (ar_ptr, bytes);
  2415. }
  2416. if (ar_ptr != NULL)
  2417. __libc_lock_unlock (ar_ptr->mutex);
  2418. /* In a low memory situation, we may not be able to allocate memory
  2419. - in which case, we just keep trying later. However, we
  2420. typically do this very early, so either there is sufficient
  2421. memory, or there isn't enough memory to do non-trivial
  2422. allocations anyway. */
  2423. if (victim)
  2424. {
  2425. tcache = (tcache_perthread_struct *) victim;
  2426. memset (tcache, 0, sizeof (tcache_perthread_struct));
  2427. }
  2428. }
  2429. # define MAYBE_INIT_TCACHE() \
  2430. if (__glibc_unlikely (tcache == NULL)) \
  2431. tcache_init();
  2432. #else /* !USE_TCACHE */
  2433. # define MAYBE_INIT_TCACHE()
  2434. static void
  2435. tcache_thread_shutdown (void)
  2436. {
  2437. /* Nothing to do if there is no thread cache. */
  2438. }
  2439. #endif /* !USE_TCACHE */
  2440. void *
  2441. __libc_malloc (size_t bytes)
  2442. {
  2443. mstate ar_ptr;
  2444. void *victim;
  2445. void *(*hook) (size_t, const void *)
  2446. = atomic_forced_read (__malloc_hook);
  2447. if (__builtin_expect (hook != NULL, 0))
  2448. return (*hook)(bytes, RETURN_ADDRESS (0));
  2449. #if USE_TCACHE
  2450. /* int_free also calls request2size, be careful to not pad twice. */
  2451. size_t tbytes;
  2452. checked_request2size (bytes, tbytes);
  2453. size_t tc_idx = csize2tidx (tbytes);
  2454. MAYBE_INIT_TCACHE ();
  2455. DIAG_PUSH_NEEDS_COMMENT;
  2456. if (tc_idx < mp_.tcache_bins
  2457. /*&& tc_idx < TCACHE_MAX_BINS*/ /* to appease gcc */
  2458. && tcache
  2459. && tcache->entries[tc_idx] != NULL)
  2460. {
  2461. return tcache_get (tc_idx);
  2462. }
  2463. DIAG_POP_NEEDS_COMMENT;
  2464. #endif
  2465. if (SINGLE_THREAD_P)
  2466. {
  2467. victim = _int_malloc (&main_arena, bytes);
  2468. assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
  2469. &main_arena == arena_for_chunk (mem2chunk (victim)));
  2470. return victim;
  2471. }
  2472. arena_get (ar_ptr, bytes);
  2473. victim = _int_malloc (ar_ptr, bytes);
  2474. /* Retry with another arena only if we were able to find a usable arena
  2475. before. */
  2476. if (!victim && ar_ptr != NULL)
  2477. {
  2478. LIBC_PROBE (memory_malloc_retry, 1, bytes);
  2479. ar_ptr = arena_get_retry (ar_ptr, bytes);
  2480. victim = _int_malloc (ar_ptr, bytes);
  2481. }
  2482. if (ar_ptr != NULL)
  2483. __libc_lock_unlock (ar_ptr->mutex);
  2484. assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
  2485. ar_ptr == arena_for_chunk (mem2chunk (victim)));
  2486. return victim;
  2487. }
  2488. libc_hidden_def (__libc_malloc)
  2489. void
  2490. __libc_free (void *mem)
  2491. {
  2492. mstate ar_ptr;
  2493. mchunkptr p; /* chunk corresponding to mem */
  2494. void (*hook) (void *, const void *)
  2495. = atomic_forced_read (__free_hook);
  2496. if (__builtin_expect (hook != NULL, 0))
  2497. {
  2498. (*hook)(mem, RETURN_ADDRESS (0));
  2499. return;
  2500. }
  2501. if (mem == 0) /* free(0) has no effect */
  2502. return;
  2503. p = mem2chunk (mem);
  2504. if (chunk_is_mmapped (p)) /* release mmapped memory. */
  2505. {
  2506. /* See if the dynamic brk/mmap threshold needs adjusting.
  2507. Dumped fake mmapped chunks do not affect the threshold. */
  2508. if (!mp_.no_dyn_threshold
  2509. && chunksize_nomask (p) > mp_.mmap_threshold
  2510. && chunksize_nomask (p) <= DEFAULT_MMAP_THRESHOLD_MAX
  2511. && !DUMPED_MAIN_ARENA_CHUNK (p))
  2512. {
  2513. mp_.mmap_threshold = chunksize (p);
  2514. mp_.trim_threshold = 2 * mp_.mmap_threshold;
  2515. LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2,
  2516. mp_.mmap_threshold, mp_.trim_threshold);
  2517. }
  2518. munmap_chunk (p);
  2519. return;
  2520. }
  2521. MAYBE_INIT_TCACHE ();
  2522. ar_ptr = arena_for_chunk (p);
  2523. _int_free (ar_ptr, p, 0);
  2524. }
  2525. libc_hidden_def (__libc_free)
  2526. void *
  2527. __libc_realloc (void *oldmem, size_t bytes)
  2528. {
  2529. mstate ar_ptr;
  2530. INTERNAL_SIZE_T nb; /* padded request size */
  2531. void *newp; /* chunk to return */
  2532. void *(*hook) (void *, size_t, const void *) =
  2533. atomic_forced_read (__realloc_hook);
  2534. if (__builtin_expect (hook != NULL, 0))
  2535. return (*hook)(oldmem, bytes, RETURN_ADDRESS (0));
  2536. #if REALLOC_ZERO_BYTES_FREES
  2537. if (bytes == 0 && oldmem != NULL)
  2538. {
  2539. __libc_free (oldmem); return 0;
  2540. }
  2541. #endif
  2542. /* realloc of null is supposed to be same as malloc */
  2543. if (oldmem == 0)
  2544. return __libc_malloc (bytes);
  2545. /* chunk corresponding to oldmem */
  2546. const mchunkptr oldp = mem2chunk (oldmem);
  2547. /* its size */
  2548. const INTERNAL_SIZE_T oldsize = chunksize (oldp);
  2549. if (chunk_is_mmapped (oldp))
  2550. ar_ptr = NULL;
  2551. else
  2552. {
  2553. MAYBE_INIT_TCACHE ();
  2554. ar_ptr = arena_for_chunk (oldp);
  2555. }
  2556. /* Little security check which won't hurt performance: the allocator
  2557. never wrapps around at the end of the address space. Therefore
  2558. we can exclude some size values which might appear here by
  2559. accident or by "design" from some intruder. We need to bypass
  2560. this check for dumped fake mmap chunks from the old main arena
  2561. because the new malloc may provide additional alignment. */
  2562. if ((__builtin_expect ((uintptr_t) oldp > (uintptr_t) -oldsize, 0)
  2563. || __builtin_expect (misaligned_chunk (oldp), 0))
  2564. && !DUMPED_MAIN_ARENA_CHUNK (oldp))
  2565. malloc_printerr ("realloc(): invalid pointer");
  2566. checked_request2size (bytes, nb);
  2567. if (chunk_is_mmapped (oldp))
  2568. {
  2569. /* If this is a faked mmapped chunk from the dumped main arena,
  2570. always make a copy (and do not free the old chunk). */
  2571. if (DUMPED_MAIN_ARENA_CHUNK (oldp))
  2572. {
  2573. /* Must alloc, copy, free. */
  2574. void *newmem = __libc_malloc (bytes);
  2575. if (newmem == 0)
  2576. return NULL;
  2577. /* Copy as many bytes as are available from the old chunk
  2578. and fit into the new size. NB: The overhead for faked
  2579. mmapped chunks is only SIZE_SZ, not 2 * SIZE_SZ as for
  2580. regular mmapped chunks. */
  2581. if (bytes > oldsize - SIZE_SZ)
  2582. bytes = oldsize - SIZE_SZ;
  2583. memcpy (newmem, oldmem, bytes);
  2584. return newmem;
  2585. }
  2586. void *newmem;
  2587. #if HAVE_MREMAP
  2588. newp = mremap_chunk (oldp, nb);
  2589. if (newp)
  2590. return chunk2mem (newp);
  2591. #endif
  2592. /* Note the extra SIZE_SZ overhead. */
  2593. if (oldsize - SIZE_SZ >= nb)
  2594. return oldmem; /* do nothing */
  2595. /* Must alloc, copy, free. */
  2596. newmem = __libc_malloc (bytes);
  2597. if (newmem == 0)
  2598. return 0; /* propagate failure */
  2599. memcpy (newmem, oldmem, oldsize - 2 * SIZE_SZ);
  2600. munmap_chunk (oldp);
  2601. return newmem;
  2602. }
  2603. if (SINGLE_THREAD_P)
  2604. {
  2605. newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
  2606. assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
  2607. ar_ptr == arena_for_chunk (mem2chunk (newp)));
  2608. return newp;
  2609. }
  2610. __libc_lock_lock (ar_ptr->mutex);
  2611. newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
  2612. __libc_lock_unlock (ar_ptr->mutex);
  2613. assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
  2614. ar_ptr == arena_for_chunk (mem2chunk (newp)));
  2615. if (newp == NULL)
  2616. {
  2617. /* Try harder to allocate memory in other arenas. */
  2618. LIBC_PROBE (memory_realloc_retry, 2, bytes, oldmem);
  2619. newp = __libc_malloc (bytes);
  2620. if (newp != NULL)
  2621. {
  2622. memcpy (newp, oldmem, oldsize - SIZE_SZ);
  2623. _int_free (ar_ptr, oldp, 0);
  2624. }
  2625. }
  2626. return newp;
  2627. }
  2628. libc_hidden_def (__libc_realloc)
  2629. void *
  2630. __libc_memalign (size_t alignment, size_t bytes)
  2631. {
  2632. void *address = RETURN_ADDRESS (0);
  2633. return _mid_memalign (alignment, bytes, address);
  2634. }
  2635. static void *
  2636. _mid_memalign (size_t alignment, size_t bytes, void *address)
  2637. {
  2638. mstate ar_ptr;
  2639. void *p;
  2640. void *(*hook) (size_t, size_t, const void *) =
  2641. atomic_forced_read (__memalign_hook);
  2642. if (__builtin_expect (hook != NULL, 0))
  2643. return (*hook)(alignment, bytes, address);
  2644. /* If we need less alignment than we give anyway, just relay to malloc. */
  2645. if (alignment <= MALLOC_ALIGNMENT)
  2646. return __libc_malloc (bytes);
  2647. /* Otherwise, ensure that it is at least a minimum chunk size */
  2648. if (alignment < MINSIZE)
  2649. alignment = MINSIZE;
  2650. /* If the alignment is greater than SIZE_MAX / 2 + 1 it cannot be a
  2651. power of 2 and will cause overflow in the check below. */
  2652. if (alignment > SIZE_MAX / 2 + 1)
  2653. {
  2654. __set_errno (EINVAL);
  2655. return 0;
  2656. }
  2657. /* Check for overflow. */
  2658. if (bytes > SIZE_MAX - alignment - MINSIZE)
  2659. {
  2660. __set_errno (ENOMEM);
  2661. return 0;
  2662. }
  2663. /* Make sure alignment is power of 2. */
  2664. if (!powerof2 (alignment))
  2665. {
  2666. size_t a = MALLOC_ALIGNMENT * 2;
  2667. while (a < alignment)
  2668. a <<= 1;
  2669. alignment = a;
  2670. }
  2671. if (SINGLE_THREAD_P)
  2672. {
  2673. p = _int_memalign (&main_arena, alignment, bytes);
  2674. assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
  2675. &main_arena == arena_for_chunk (mem2chunk (p)));
  2676. return p;
  2677. }
  2678. arena_get (ar_ptr, bytes + alignment + MINSIZE);
  2679. p = _int_memalign (ar_ptr, alignment, bytes);
  2680. if (!p && ar_ptr != NULL)
  2681. {
  2682. LIBC_PROBE (memory_memalign_retry, 2, bytes, alignment);
  2683. ar_ptr = arena_get_retry (ar_ptr, bytes);
  2684. p = _int_memalign (ar_ptr, alignment, bytes);
  2685. }
  2686. if (ar_ptr != NULL)
  2687. __libc_lock_unlock (ar_ptr->mutex);
  2688. assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
  2689. ar_ptr == arena_for_chunk (mem2chunk (p)));
  2690. return p;
  2691. }
  2692. /* For ISO C11. */
  2693. weak_alias (__libc_memalign, aligned_alloc)
  2694. libc_hidden_def (__libc_memalign)
  2695. void *
  2696. __libc_valloc (size_t bytes)
  2697. {
  2698. if (__malloc_initialized < 0)
  2699. ptmalloc_init ();
  2700. void *address = RETURN_ADDRESS (0);
  2701. size_t pagesize = GLRO (dl_pagesize);
  2702. return _mid_memalign (pagesize, bytes, address);
  2703. }
  2704. void *
  2705. __libc_pvalloc (size_t bytes)
  2706. {
  2707. if (__malloc_initialized < 0)
  2708. ptmalloc_init ();
  2709. void *address = RETURN_ADDRESS (0);
  2710. size_t pagesize = GLRO (dl_pagesize);
  2711. size_t rounded_bytes = ALIGN_UP (bytes, pagesize);
  2712. /* Check for overflow. */
  2713. if (bytes > SIZE_MAX - 2 * pagesize - MINSIZE)
  2714. {
  2715. __set_errno (ENOMEM);
  2716. return 0;
  2717. }
  2718. return _mid_memalign (pagesize, rounded_bytes, address);
  2719. }
  2720. void *
  2721. __libc_calloc (size_t n, size_t elem_size)
  2722. {
  2723. mstate av;
  2724. mchunkptr oldtop, p;
  2725. INTERNAL_SIZE_T bytes, sz, csz, oldtopsize;
  2726. void *mem;
  2727. unsigned long clearsize;
  2728. unsigned long nclears;
  2729. INTERNAL_SIZE_T *d;
  2730. /* size_t is unsigned so the behavior on overflow is defined. */
  2731. bytes = n * elem_size;
  2732. #define HALF_INTERNAL_SIZE_T \
  2733. (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
  2734. if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0))
  2735. {
  2736. if (elem_size != 0 && bytes / elem_size != n)
  2737. {
  2738. __set_errno (ENOMEM);
  2739. return 0;
  2740. }
  2741. }
  2742. void *(*hook) (size_t, const void *) =
  2743. atomic_forced_read (__malloc_hook);
  2744. if (__builtin_expect (hook != NULL, 0))
  2745. {
  2746. sz = bytes;
  2747. mem = (*hook)(sz, RETURN_ADDRESS (0));
  2748. if (mem == 0)
  2749. return 0;
  2750. return memset (mem, 0, sz);
  2751. }
  2752. sz = bytes;
  2753. MAYBE_INIT_TCACHE ();
  2754. if (SINGLE_THREAD_P)
  2755. av = &main_arena;
  2756. else
  2757. arena_get (av, sz);
  2758. if (av)
  2759. {
  2760. /* Check if we hand out the top chunk, in which case there may be no
  2761. need to clear. */
  2762. #if MORECORE_CLEARS
  2763. oldtop = top (av);
  2764. oldtopsize = chunksize (top (av));
  2765. # if MORECORE_CLEARS < 2
  2766. /* Only newly allocated memory is guaranteed to be cleared. */
  2767. if (av == &main_arena &&
  2768. oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *) oldtop)
  2769. oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *) oldtop);
  2770. # endif
  2771. if (av != &main_arena)
  2772. {
  2773. heap_info *heap = heap_for_ptr (oldtop);
  2774. if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop)
  2775. oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop;
  2776. }
  2777. #endif
  2778. }
  2779. else
  2780. {
  2781. /* No usable arenas. */
  2782. oldtop = 0;
  2783. oldtopsize = 0;
  2784. }
  2785. mem = _int_malloc (av, sz);
  2786. assert (!mem || chunk_is_mmapped (mem2chunk (mem)) ||
  2787. av == arena_for_chunk (mem2chunk (mem)));
  2788. if (!SINGLE_THREAD_P)
  2789. {
  2790. if (mem == 0 && av != NULL)
  2791. {
  2792. LIBC_PROBE (memory_calloc_retry, 1, sz);
  2793. av = arena_get_retry (av, sz);
  2794. mem = _int_malloc (av, sz);
  2795. }
  2796. if (av != NULL)
  2797. __libc_lock_unlock (av->mutex);
  2798. }
  2799. /* Allocation failed even after a retry. */
  2800. if (mem == 0)
  2801. return 0;
  2802. p = mem2chunk (mem);
  2803. /* Two optional cases in which clearing not necessary */
  2804. if (chunk_is_mmapped (p))
  2805. {
  2806. if (__builtin_expect (perturb_byte, 0))
  2807. return memset (mem, 0, sz);
  2808. return mem;
  2809. }
  2810. csz = chunksize (p);
  2811. #if MORECORE_CLEARS
  2812. if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize))
  2813. {
  2814. /* clear only the bytes from non-freshly-sbrked memory */
  2815. csz = oldtopsize;
  2816. }
  2817. #endif
  2818. /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
  2819. contents have an odd number of INTERNAL_SIZE_T-sized words;
  2820. minimally 3. */
  2821. d = (INTERNAL_SIZE_T *) mem;
  2822. clearsize = csz - SIZE_SZ;
  2823. nclears = clearsize / sizeof (INTERNAL_SIZE_T);
  2824. assert (nclears >= 3);
  2825. if (nclears > 9)
  2826. return memset (d, 0, clearsize);
  2827. else
  2828. {
  2829. *(d + 0) = 0;
  2830. *(d + 1) = 0;
  2831. *(d + 2) = 0;
  2832. if (nclears > 4)
  2833. {
  2834. *(d + 3) = 0;
  2835. *(d + 4) = 0;
  2836. if (nclears > 6)
  2837. {
  2838. *(d + 5) = 0;
  2839. *(d + 6) = 0;
  2840. if (nclears > 8)
  2841. {
  2842. *(d + 7) = 0;
  2843. *(d + 8) = 0;
  2844. }
  2845. }
  2846. }
  2847. }
  2848. return mem;
  2849. }
  2850. /*
  2851. ------------------------------ malloc ------------------------------
  2852. */
  2853. static void *
  2854. _int_malloc (mstate av, size_t bytes)
  2855. {
  2856. INTERNAL_SIZE_T nb; /* normalized request size */
  2857. unsigned int idx; /* associated bin index */
  2858. mbinptr bin; /* associated bin */
  2859. mchunkptr victim; /* inspected/selected chunk */
  2860. INTERNAL_SIZE_T size; /* its size */
  2861. int victim_index; /* its bin index */
  2862. mchunkptr remainder; /* remainder from a split */
  2863. unsigned long remainder_size; /* its size */
  2864. unsigned int block; /* bit map traverser */
  2865. unsigned int bit; /* bit map traverser */
  2866. unsigned int map; /* current word of binmap */
  2867. mchunkptr fwd; /* misc temp for linking */
  2868. mchunkptr bck; /* misc temp for linking */
  2869. #if USE_TCACHE
  2870. size_t tcache_unsorted_count; /* count of unsorted chunks processed */
  2871. #endif
  2872. /*
  2873. Convert request size to internal form by adding SIZE_SZ bytes
  2874. overhead plus possibly more to obtain necessary alignment and/or
  2875. to obtain a size of at least MINSIZE, the smallest allocatable
  2876. size. Also, checked_request2size traps (returning 0) request sizes
  2877. that are so large that they wrap around zero when padded and
  2878. aligned.
  2879. */
  2880. checked_request2size (bytes, nb);
  2881. /* There are no usable arenas. Fall back to sysmalloc to get a chunk from
  2882. mmap. */
  2883. if (__glibc_unlikely (av == NULL))
  2884. {
  2885. void *p = sysmalloc (nb, av);
  2886. if (p != NULL)
  2887. alloc_perturb (p, bytes);
  2888. return p;
  2889. }
  2890. /*
  2891. If the size qualifies as a fastbin, first check corresponding bin.
  2892. This code is safe to execute even if av is not yet initialized, so we
  2893. can try it without checking, which saves some time on this fast path.
  2894. */
  2895. #define REMOVE_FB(fb, victim, pp) \
  2896. do \
  2897. { \
  2898. victim = pp; \
  2899. if (victim == NULL) \
  2900. break; \
  2901. } \
  2902. while ((pp = catomic_compare_and_exchange_val_acq (fb, victim->fd, victim)) \
  2903. != victim); \
  2904. if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ()))
  2905. {
  2906. idx = fastbin_index (nb);
  2907. mfastbinptr *fb = &fastbin (av, idx);
  2908. mchunkptr pp;
  2909. victim = *fb;
  2910. if (victim != NULL)
  2911. {
  2912. if (SINGLE_THREAD_P)
  2913. *fb = victim->fd;
  2914. else
  2915. REMOVE_FB (fb, pp, victim);
  2916. if (__glibc_likely (victim != NULL))
  2917. {
  2918. size_t victim_idx = fastbin_index (chunksize (victim));
  2919. if (__builtin_expect (victim_idx != idx, 0))
  2920. malloc_printerr ("malloc(): memory corruption (fast)");
  2921. check_remalloced_chunk (av, victim, nb);
  2922. #if USE_TCACHE
  2923. /* While we're here, if we see other chunks of the same size,
  2924. stash them in the tcache. */
  2925. size_t tc_idx = csize2tidx (nb);
  2926. if (tcache && tc_idx < mp_.tcache_bins)
  2927. {
  2928. mchunkptr tc_victim;
  2929. /* While bin not empty and tcache not full, copy chunks. */
  2930. while (tcache->counts[tc_idx] < mp_.tcache_count
  2931. && (tc_victim = *fb) != NULL)
  2932. {
  2933. if (SINGLE_THREAD_P)
  2934. *fb = tc_victim->fd;
  2935. else
  2936. {
  2937. REMOVE_FB (fb, pp, tc_victim);
  2938. if (__glibc_unlikely (tc_victim == NULL))
  2939. break;
  2940. }
  2941. tcache_put (tc_victim, tc_idx);
  2942. }
  2943. }
  2944. #endif
  2945. void *p = chunk2mem (victim);
  2946. alloc_perturb (p, bytes);
  2947. return p;
  2948. }
  2949. }
  2950. }
  2951. /*
  2952. If a small request, check regular bin. Since these "smallbins"
  2953. hold one size each, no searching within bins is necessary.
  2954. (For a large request, we need to wait until unsorted chunks are
  2955. processed to find best fit. But for small ones, fits are exact
  2956. anyway, so we can check now, which is faster.)
  2957. */
  2958. if (in_smallbin_range (nb))
  2959. {
  2960. idx = smallbin_index (nb);
  2961. bin = bin_at (av, idx);
  2962. if ((victim = last (bin)) != bin)
  2963. {
  2964. bck = victim->bk;
  2965. if (__glibc_unlikely (bck->fd != victim))
  2966. malloc_printerr ("malloc(): smallbin double linked list corrupted");
  2967. set_inuse_bit_at_offset (victim, nb);
  2968. bin->bk = bck;
  2969. bck->fd = bin;
  2970. if (av != &main_arena)
  2971. set_non_main_arena (victim);
  2972. check_malloced_chunk (av, victim, nb);
  2973. #if USE_TCACHE
  2974. /* While we're here, if we see other chunks of the same size,
  2975. stash them in the tcache. */
  2976. size_t tc_idx = csize2tidx (nb);
  2977. if (tcache && tc_idx < mp_.tcache_bins)
  2978. {
  2979. mchunkptr tc_victim;
  2980. /* While bin not empty and tcache not full, copy chunks over. */
  2981. while (tcache->counts[tc_idx] < mp_.tcache_count
  2982. && (tc_victim = last (bin)) != bin)
  2983. {
  2984. if (tc_victim != 0)
  2985. {
  2986. bck = tc_victim->bk;
  2987. set_inuse_bit_at_offset (tc_victim, nb);
  2988. if (av != &main_arena)
  2989. set_non_main_arena (tc_victim);
  2990. bin->bk = bck;
  2991. bck->fd = bin;
  2992. tcache_put (tc_victim, tc_idx);
  2993. }
  2994. }
  2995. }
  2996. #endif
  2997. void *p = chunk2mem (victim);
  2998. alloc_perturb (p, bytes);
  2999. return p;
  3000. }
  3001. }
  3002. /*
  3003. If this is a large request, consolidate fastbins before continuing.
  3004. While it might look excessive to kill all fastbins before
  3005. even seeing if there is space available, this avoids
  3006. fragmentation problems normally associated with fastbins.
  3007. Also, in practice, programs tend to have runs of either small or
  3008. large requests, but less often mixtures, so consolidation is not
  3009. invoked all that often in most programs. And the programs that
  3010. it is called frequently in otherwise tend to fragment.
  3011. */
  3012. else
  3013. {
  3014. idx = largebin_index (nb);
  3015. if (atomic_load_relaxed (&av->have_fastchunks))
  3016. malloc_consolidate (av);
  3017. }
  3018. /*
  3019. Process recently freed or remaindered chunks, taking one only if
  3020. it is exact fit, or, if this a small request, the chunk is remainder from
  3021. the most recent non-exact fit. Place other traversed chunks in
  3022. bins. Note that this step is the only place in any routine where
  3023. chunks are placed in bins.
  3024. The outer loop here is needed because we might not realize until
  3025. near the end of malloc that we should have consolidated, so must
  3026. do so and retry. This happens at most once, and only when we would
  3027. otherwise need to expand memory to service a "small" request.
  3028. */
  3029. #if USE_TCACHE
  3030. INTERNAL_SIZE_T tcache_nb = 0;
  3031. size_t tc_idx = csize2tidx (nb);
  3032. if (tcache && tc_idx < mp_.tcache_bins)
  3033. tcache_nb = nb;
  3034. int return_cached = 0;
  3035. tcache_unsorted_count = 0;
  3036. #endif
  3037. for (;; )
  3038. {
  3039. int iters = 0;
  3040. while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))
  3041. {
  3042. bck = victim->bk;
  3043. size = chunksize (victim);
  3044. mchunkptr next = chunk_at_offset (victim, size);
  3045. if (__glibc_unlikely (size <= 2 * SIZE_SZ)
  3046. || __glibc_unlikely (size > av->system_mem))
  3047. malloc_printerr ("malloc(): invalid size (unsorted)");
  3048. if (__glibc_unlikely (chunksize_nomask (next) < 2 * SIZE_SZ)
  3049. || __glibc_unlikely (chunksize_nomask (next) > av->system_mem))
  3050. malloc_printerr ("malloc(): invalid next size (unsorted)");
  3051. if (__glibc_unlikely ((prev_size (next) & ~(SIZE_BITS)) != size))
  3052. malloc_printerr ("malloc(): mismatching next->prev_size (unsorted)");
  3053. if (__glibc_unlikely (bck->fd != victim)
  3054. || __glibc_unlikely (victim->fd != unsorted_chunks (av)))
  3055. malloc_printerr ("malloc(): unsorted double linked list corrupted");
  3056. if (__glibc_unlikely (prev_inuse (next)))
  3057. malloc_printerr ("malloc(): invalid next->prev_inuse (unsorted)");
  3058. /*
  3059. If a small request, try to use last remainder if it is the
  3060. only chunk in unsorted bin. This helps promote locality for
  3061. runs of consecutive small requests. This is the only
  3062. exception to best-fit, and applies only when there is
  3063. no exact fit for a small chunk.
  3064. */
  3065. if (in_smallbin_range (nb) &&
  3066. bck == unsorted_chunks (av) &&
  3067. victim == av->last_remainder &&
  3068. (unsigned long) (size) > (unsigned long) (nb + MINSIZE))
  3069. {
  3070. /* split and reattach remainder */
  3071. remainder_size = size - nb;
  3072. remainder = chunk_at_offset (victim, nb);
  3073. unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder;
  3074. av->last_remainder = remainder;
  3075. remainder->bk = remainder->fd = unsorted_chunks (av);
  3076. if (!in_smallbin_range (remainder_size))
  3077. {
  3078. remainder->fd_nextsize = NULL;
  3079. remainder->bk_nextsize = NULL;
  3080. }
  3081. set_head (victim, nb | PREV_INUSE |
  3082. (av != &main_arena ? NON_MAIN_ARENA : 0));
  3083. set_head (remainder, remainder_size | PREV_INUSE);
  3084. set_foot (remainder, remainder_size);
  3085. check_malloced_chunk (av, victim, nb);
  3086. void *p = chunk2mem (victim);
  3087. alloc_perturb (p, bytes);
  3088. return p;
  3089. }
  3090. /* remove from unsorted list */
  3091. if (__glibc_unlikely (bck->fd != victim))
  3092. malloc_printerr ("malloc(): corrupted unsorted chunks 3");
  3093. unsorted_chunks (av)->bk = bck;
  3094. bck->fd = unsorted_chunks (av);
  3095. /* Take now instead of binning if exact fit */
  3096. if (size == nb)
  3097. {
  3098. set_inuse_bit_at_offset (victim, size);
  3099. if (av != &main_arena)
  3100. set_non_main_arena (victim);
  3101. #if USE_TCACHE
  3102. /* Fill cache first, return to user only if cache fills.
  3103. We may return one of these chunks later. */
  3104. if (tcache_nb
  3105. && tcache->counts[tc_idx] < mp_.tcache_count)
  3106. {
  3107. tcache_put (victim, tc_idx);
  3108. return_cached = 1;
  3109. continue;
  3110. }
  3111. else
  3112. {
  3113. #endif
  3114. check_malloced_chunk (av, victim, nb);
  3115. void *p = chunk2mem (victim);
  3116. alloc_perturb (p, bytes);
  3117. return p;
  3118. #if USE_TCACHE
  3119. }
  3120. #endif
  3121. }
  3122. /* place chunk in bin */
  3123. if (in_smallbin_range (size))
  3124. {
  3125. victim_index = smallbin_index (size);
  3126. bck = bin_at (av, victim_index);
  3127. fwd = bck->fd;
  3128. }
  3129. else
  3130. {
  3131. victim_index = largebin_index (size);
  3132. bck = bin_at (av, victim_index);
  3133. fwd = bck->fd;
  3134. /* maintain large bins in sorted order */
  3135. if (fwd != bck)
  3136. {
  3137. /* Or with inuse bit to speed comparisons */
  3138. size |= PREV_INUSE;
  3139. /* if smaller than smallest, bypass loop below */
  3140. assert (chunk_main_arena (bck->bk));
  3141. if ((unsigned long) (size)
  3142. < (unsigned long) chunksize_nomask (bck->bk))
  3143. {
  3144. fwd = bck;
  3145. bck = bck->bk;
  3146. victim->fd_nextsize = fwd->fd;
  3147. victim->bk_nextsize = fwd->fd->bk_nextsize;
  3148. fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
  3149. }
  3150. else
  3151. {
  3152. assert (chunk_main_arena (fwd));
  3153. while ((unsigned long) size < chunksize_nomask (fwd))
  3154. {
  3155. fwd = fwd->fd_nextsize;
  3156. assert (chunk_main_arena (fwd));
  3157. }
  3158. if ((unsigned long) size
  3159. == (unsigned long) chunksize_nomask (fwd))
  3160. /* Always insert in the second position. */
  3161. fwd = fwd->fd;
  3162. else
  3163. {
  3164. victim->fd_nextsize = fwd;
  3165. victim->bk_nextsize = fwd->bk_nextsize;
  3166. fwd->bk_nextsize = victim;
  3167. victim->bk_nextsize->fd_nextsize = victim;
  3168. }
  3169. bck = fwd->bk;
  3170. }
  3171. }
  3172. else
  3173. victim->fd_nextsize = victim->bk_nextsize = victim;
  3174. }
  3175. mark_bin (av, victim_index);
  3176. victim->bk = bck;
  3177. victim->fd = fwd;
  3178. fwd->bk = victim;
  3179. bck->fd = victim;
  3180. #if USE_TCACHE
  3181. /* If we've processed as many chunks as we're allowed while
  3182. filling the cache, return one of the cached ones. */
  3183. ++tcache_unsorted_count;
  3184. if (return_cached
  3185. && mp_.tcache_unsorted_limit > 0
  3186. && tcache_unsorted_count > mp_.tcache_unsorted_limit)
  3187. {
  3188. return tcache_get (tc_idx);
  3189. }
  3190. #endif
  3191. #define MAX_ITERS 10000
  3192. if (++iters >= MAX_ITERS)
  3193. break;
  3194. }
  3195. #if USE_TCACHE
  3196. /* If all the small chunks we found ended up cached, return one now. */
  3197. if (return_cached)
  3198. {
  3199. return tcache_get (tc_idx);
  3200. }
  3201. #endif
  3202. /*
  3203. If a large request, scan through the chunks of current bin in
  3204. sorted order to find smallest that fits. Use the skip list for this.
  3205. */
  3206. if (!in_smallbin_range (nb))
  3207. {
  3208. bin = bin_at (av, idx);
  3209. /* skip scan if empty or largest chunk is too small */
  3210. if ((victim = first (bin)) != bin
  3211. && (unsigned long) chunksize_nomask (victim)
  3212. >= (unsigned long) (nb))
  3213. {
  3214. victim = victim->bk_nextsize;
  3215. while (((unsigned long) (size = chunksize (victim)) <
  3216. (unsigned long) (nb)))
  3217. victim = victim->bk_nextsize;
  3218. /* Avoid removing the first entry for a size so that the skip
  3219. list does not have to be rerouted. */
  3220. if (victim != last (bin)
  3221. && chunksize_nomask (victim)
  3222. == chunksize_nomask (victim->fd))
  3223. victim = victim->fd;
  3224. remainder_size = size - nb;
  3225. unlink_chunk (av, victim);
  3226. /* Exhaust */
  3227. if (remainder_size < MINSIZE)
  3228. {
  3229. set_inuse_bit_at_offset (victim, size);
  3230. if (av != &main_arena)
  3231. set_non_main_arena (victim);
  3232. }
  3233. /* Split */
  3234. else
  3235. {
  3236. remainder = chunk_at_offset (victim, nb);
  3237. /* We cannot assume the unsorted list is empty and therefore
  3238. have to perform a complete insert here. */
  3239. bck = unsorted_chunks (av);
  3240. fwd = bck->fd;
  3241. if (__glibc_unlikely (fwd->bk != bck))
  3242. malloc_printerr ("malloc(): corrupted unsorted chunks");
  3243. remainder->bk = bck;
  3244. remainder->fd = fwd;
  3245. bck->fd = remainder;
  3246. fwd->bk = remainder;
  3247. if (!in_smallbin_range (remainder_size))
  3248. {
  3249. remainder->fd_nextsize = NULL;
  3250. remainder->bk_nextsize = NULL;
  3251. }
  3252. set_head (victim, nb | PREV_INUSE |
  3253. (av != &main_arena ? NON_MAIN_ARENA : 0));
  3254. set_head (remainder, remainder_size | PREV_INUSE);
  3255. set_foot (remainder, remainder_size);
  3256. }
  3257. check_malloced_chunk (av, victim, nb);
  3258. void *p = chunk2mem (victim);
  3259. alloc_perturb (p, bytes);
  3260. return p;
  3261. }
  3262. }
  3263. /*
  3264. Search for a chunk by scanning bins, starting with next largest
  3265. bin. This search is strictly by best-fit; i.e., the smallest
  3266. (with ties going to approximately the least recently used) chunk
  3267. that fits is selected.
  3268. The bitmap avoids needing to check that most blocks are nonempty.
  3269. The particular case of skipping all bins during warm-up phases
  3270. when no chunks have been returned yet is faster than it might look.
  3271. */
  3272. ++idx;
  3273. bin = bin_at (av, idx);
  3274. block = idx2block (idx);
  3275. map = av->binmap[block];
  3276. bit = idx2bit (idx);
  3277. for (;; )
  3278. {
  3279. /* Skip rest of block if there are no more set bits in this block. */
  3280. if (bit > map || bit == 0)
  3281. {
  3282. do
  3283. {
  3284. if (++block >= BINMAPSIZE) /* out of bins */
  3285. goto use_top;
  3286. }
  3287. while ((map = av->binmap[block]) == 0);
  3288. bin = bin_at (av, (block << BINMAPSHIFT));
  3289. bit = 1;
  3290. }
  3291. /* Advance to bin with set bit. There must be one. */
  3292. while ((bit & map) == 0)
  3293. {
  3294. bin = next_bin (bin);
  3295. bit <<= 1;
  3296. assert (bit != 0);
  3297. }
  3298. /* Inspect the bin. It is likely to be non-empty */
  3299. victim = last (bin);
  3300. /* If a false alarm (empty bin), clear the bit. */
  3301. if (victim == bin)
  3302. {
  3303. av->binmap[block] = map &= ~bit; /* Write through */
  3304. bin = next_bin (bin);
  3305. bit <<= 1;
  3306. }
  3307. else
  3308. {
  3309. size = chunksize (victim);
  3310. /* We know the first chunk in this bin is big enough to use. */
  3311. assert ((unsigned long) (size) >= (unsigned long) (nb));
  3312. remainder_size = size - nb;
  3313. /* unlink */
  3314. unlink_chunk (av, victim);
  3315. /* Exhaust */
  3316. if (remainder_size < MINSIZE)
  3317. {
  3318. set_inuse_bit_at_offset (victim, size);
  3319. if (av != &main_arena)
  3320. set_non_main_arena (victim);
  3321. }
  3322. /* Split */
  3323. else
  3324. {
  3325. remainder = chunk_at_offset (victim, nb);
  3326. /* We cannot assume the unsorted list is empty and therefore
  3327. have to perform a complete insert here. */
  3328. bck = unsorted_chunks (av);
  3329. fwd = bck->fd;
  3330. if (__glibc_unlikely (fwd->bk != bck))
  3331. malloc_printerr ("malloc(): corrupted unsorted chunks 2");
  3332. remainder->bk = bck;
  3333. remainder->fd = fwd;
  3334. bck->fd = remainder;
  3335. fwd->bk = remainder;
  3336. /* advertise as last remainder */
  3337. if (in_smallbin_range (nb))
  3338. av->last_remainder = remainder;
  3339. if (!in_smallbin_range (remainder_size))
  3340. {
  3341. remainder->fd_nextsize = NULL;
  3342. remainder->bk_nextsize = NULL;
  3343. }
  3344. set_head (victim, nb | PREV_INUSE |
  3345. (av != &main_arena ? NON_MAIN_ARENA : 0));
  3346. set_head (remainder, remainder_size | PREV_INUSE);
  3347. set_foot (remainder, remainder_size);
  3348. }
  3349. check_malloced_chunk (av, victim, nb);
  3350. void *p = chunk2mem (victim);
  3351. alloc_perturb (p, bytes);
  3352. return p;
  3353. }
  3354. }
  3355. use_top:
  3356. /*
  3357. If large enough, split off the chunk bordering the end of memory
  3358. (held in av->top). Note that this is in accord with the best-fit
  3359. search rule. In effect, av->top is treated as larger (and thus
  3360. less well fitting) than any other available chunk since it can
  3361. be extended to be as large as necessary (up to system
  3362. limitations).
  3363. We require that av->top always exists (i.e., has size >=
  3364. MINSIZE) after initialization, so if it would otherwise be
  3365. exhausted by current request, it is replenished. (The main
  3366. reason for ensuring it exists is that we may need MINSIZE space
  3367. to put in fenceposts in sysmalloc.)
  3368. */
  3369. victim = av->top;
  3370. size = chunksize (victim);
  3371. if (__glibc_unlikely (size > av->system_mem))
  3372. malloc_printerr ("malloc(): corrupted top size");
  3373. if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
  3374. {
  3375. remainder_size = size - nb;
  3376. remainder = chunk_at_offset (victim, nb);
  3377. av->top = remainder;
  3378. set_head (victim, nb | PREV_INUSE |
  3379. (av != &main_arena ? NON_MAIN_ARENA : 0));
  3380. set_head (remainder, remainder_size | PREV_INUSE);
  3381. check_malloced_chunk (av, victim, nb);
  3382. void *p = chunk2mem (victim);
  3383. alloc_perturb (p, bytes);
  3384. return p;
  3385. }
  3386. /* When we are using atomic ops to free fast chunks we can get
  3387. here for all block sizes. */
  3388. else if (atomic_load_relaxed (&av->have_fastchunks))
  3389. {
  3390. malloc_consolidate (av);
  3391. /* restore original bin index */
  3392. if (in_smallbin_range (nb))
  3393. idx = smallbin_index (nb);
  3394. else
  3395. idx = largebin_index (nb);
  3396. }
  3397. /*
  3398. Otherwise, relay to handle system-dependent cases
  3399. */
  3400. else
  3401. {
  3402. void *p = sysmalloc (nb, av);
  3403. if (p != NULL)
  3404. alloc_perturb (p, bytes);
  3405. return p;
  3406. }
  3407. }
  3408. }
  3409. /*
  3410. ------------------------------ free ------------------------------
  3411. */
  3412. static void
  3413. _int_free (mstate av, mchunkptr p, int have_lock)
  3414. {
  3415. INTERNAL_SIZE_T size; /* its size */
  3416. mfastbinptr *fb; /* associated fastbin */
  3417. mchunkptr nextchunk; /* next contiguous chunk */
  3418. INTERNAL_SIZE_T nextsize; /* its size */
  3419. int nextinuse; /* true if nextchunk is used */
  3420. INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
  3421. mchunkptr bck; /* misc temp for linking */
  3422. mchunkptr fwd; /* misc temp for linking */
  3423. size = chunksize (p);
  3424. /* Little security check which won't hurt performance: the
  3425. allocator never wrapps around at the end of the address space.
  3426. Therefore we can exclude some size values which might appear
  3427. here by accident or by "design" from some intruder. */
  3428. if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
  3429. || __builtin_expect (misaligned_chunk (p), 0))
  3430. malloc_printerr ("free(): invalid pointer");
  3431. /* We know that each chunk is at least MINSIZE bytes in size or a
  3432. multiple of MALLOC_ALIGNMENT. */
  3433. if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size)))
  3434. malloc_printerr ("free(): invalid size");
  3435. check_inuse_chunk(av, p);
  3436. #if USE_TCACHE
  3437. {
  3438. size_t tc_idx = csize2tidx (size);
  3439. if (tcache != NULL && tc_idx < mp_.tcache_bins)
  3440. {
  3441. /* Check to see if it's already in the tcache. */
  3442. tcache_entry *e = (tcache_entry *) chunk2mem (p);
  3443. /* This test succeeds on double free. However, we don't 100%
  3444. trust it (it also matches random payload data at a 1 in
  3445. 2^<size_t> chance), so verify it's not an unlikely
  3446. coincidence before aborting. */
  3447. if (__glibc_unlikely (e->key == tcache))
  3448. {
  3449. tcache_entry *tmp;
  3450. LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx);
  3451. for (tmp = tcache->entries[tc_idx];
  3452. tmp;
  3453. tmp = tmp->next)
  3454. if (tmp == e)
  3455. malloc_printerr ("free(): double free detected in tcache 2");
  3456. /* If we get here, it was a coincidence. We've wasted a
  3457. few cycles, but don't abort. */
  3458. }
  3459. if (tcache->counts[tc_idx] < mp_.tcache_count)
  3460. {
  3461. tcache_put (p, tc_idx);
  3462. return;
  3463. }
  3464. }
  3465. }
  3466. #endif
  3467. /*
  3468. If eligible, place chunk on a fastbin so it can be found
  3469. and used quickly in malloc.
  3470. */
  3471. if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
  3472. #if TRIM_FASTBINS
  3473. /*
  3474. If TRIM_FASTBINS set, don't place chunks
  3475. bordering top into fastbins
  3476. */
  3477. && (chunk_at_offset(p, size) != av->top)
  3478. #endif
  3479. ) {
  3480. if (__builtin_expect (chunksize_nomask (chunk_at_offset (p, size))
  3481. <= 2 * SIZE_SZ, 0)
  3482. || __builtin_expect (chunksize (chunk_at_offset (p, size))
  3483. >= av->system_mem, 0))
  3484. {
  3485. bool fail = true;
  3486. /* We might not have a lock at this point and concurrent modifications
  3487. of system_mem might result in a false positive. Redo the test after
  3488. getting the lock. */
  3489. if (!have_lock)
  3490. {
  3491. __libc_lock_lock (av->mutex);
  3492. fail = (chunksize_nomask (chunk_at_offset (p, size)) <= 2 * SIZE_SZ
  3493. || chunksize (chunk_at_offset (p, size)) >= av->system_mem);
  3494. __libc_lock_unlock (av->mutex);
  3495. }
  3496. if (fail)
  3497. malloc_printerr ("free(): invalid next size (fast)");
  3498. }
  3499. free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
  3500. atomic_store_relaxed (&av->have_fastchunks, true);
  3501. unsigned int idx = fastbin_index(size);
  3502. fb = &fastbin (av, idx);
  3503. /* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */
  3504. mchunkptr old = *fb, old2;
  3505. if (SINGLE_THREAD_P)
  3506. {
  3507. /* Check that the top of the bin is not the record we are going to
  3508. add (i.e., double free). */
  3509. if (__builtin_expect (old == p, 0))
  3510. malloc_printerr ("double free or corruption (fasttop)");
  3511. p->fd = old;
  3512. *fb = p;
  3513. }
  3514. else
  3515. do
  3516. {
  3517. /* Check that the top of the bin is not the record we are going to
  3518. add (i.e., double free). */
  3519. if (__builtin_expect (old == p, 0))
  3520. malloc_printerr ("double free or corruption (fasttop)");
  3521. p->fd = old2 = old;
  3522. }
  3523. while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2))
  3524. != old2);
  3525. /* Check that size of fastbin chunk at the top is the same as
  3526. size of the chunk that we are adding. We can dereference OLD
  3527. only if we have the lock, otherwise it might have already been
  3528. allocated again. */
  3529. if (have_lock && old != NULL
  3530. && __builtin_expect (fastbin_index (chunksize (old)) != idx, 0))
  3531. malloc_printerr ("invalid fastbin entry (free)");
  3532. }
  3533. /*
  3534. Consolidate other non-mmapped chunks as they arrive.
  3535. */
  3536. else if (!chunk_is_mmapped(p)) {
  3537. /* If we're single-threaded, don't lock the arena. */
  3538. if (SINGLE_THREAD_P)
  3539. have_lock = true;
  3540. if (!have_lock)
  3541. __libc_lock_lock (av->mutex);
  3542. nextchunk = chunk_at_offset(p, size);
  3543. /* Lightweight tests: check whether the block is already the
  3544. top block. */
  3545. if (__glibc_unlikely (p == av->top))
  3546. malloc_printerr ("double free or corruption (top)");
  3547. /* Or whether the next chunk is beyond the boundaries of the arena. */
  3548. if (__builtin_expect (contiguous (av)
  3549. && (char *) nextchunk
  3550. >= ((char *) av->top + chunksize(av->top)), 0))
  3551. malloc_printerr ("double free or corruption (out)");
  3552. /* Or whether the block is actually not marked used. */
  3553. if (__glibc_unlikely (!prev_inuse(nextchunk)))
  3554. malloc_printerr ("double free or corruption (!prev)");
  3555. nextsize = chunksize(nextchunk);
  3556. if (__builtin_expect (chunksize_nomask (nextchunk) <= 2 * SIZE_SZ, 0)
  3557. || __builtin_expect (nextsize >= av->system_mem, 0))
  3558. malloc_printerr ("free(): invalid next size (normal)");
  3559. free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
  3560. /* consolidate backward */
  3561. if (!prev_inuse(p)) {
  3562. prevsize = prev_size (p);
  3563. size += prevsize;
  3564. p = chunk_at_offset(p, -((long) prevsize));
  3565. if (__glibc_unlikely (chunksize(p) != prevsize))
  3566. malloc_printerr ("corrupted size vs. prev_size while consolidating");
  3567. unlink_chunk (av, p);
  3568. }
  3569. if (nextchunk != av->top) {
  3570. /* get and clear inuse bit */
  3571. nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
  3572. /* consolidate forward */
  3573. if (!nextinuse) {
  3574. unlink_chunk (av, nextchunk);
  3575. size += nextsize;
  3576. } else
  3577. clear_inuse_bit_at_offset(nextchunk, 0);
  3578. /*
  3579. Place the chunk in unsorted chunk list. Chunks are
  3580. not placed into regular bins until after they have
  3581. been given one chance to be used in malloc.
  3582. */
  3583. bck = unsorted_chunks(av);
  3584. fwd = bck->fd;
  3585. if (__glibc_unlikely (fwd->bk != bck))
  3586. malloc_printerr ("free(): corrupted unsorted chunks");
  3587. p->fd = fwd;
  3588. p->bk = bck;
  3589. if (!in_smallbin_range(size))
  3590. {
  3591. p->fd_nextsize = NULL;
  3592. p->bk_nextsize = NULL;
  3593. }
  3594. bck->fd = p;
  3595. fwd->bk = p;
  3596. set_head(p, size | PREV_INUSE);
  3597. set_foot(p, size);
  3598. check_free_chunk(av, p);
  3599. }
  3600. /*
  3601. If the chunk borders the current high end of memory,
  3602. consolidate into top
  3603. */
  3604. else {
  3605. size += nextsize;
  3606. set_head(p, size | PREV_INUSE);
  3607. av->top = p;
  3608. check_chunk(av, p);
  3609. }
  3610. /*
  3611. If freeing a large space, consolidate possibly-surrounding
  3612. chunks. Then, if the total unused topmost memory exceeds trim
  3613. threshold, ask malloc_trim to reduce top.
  3614. Unless max_fast is 0, we don't know if there are fastbins
  3615. bordering top, so we cannot tell for sure whether threshold
  3616. has been reached unless fastbins are consolidated. But we
  3617. don't want to consolidate on each free. As a compromise,
  3618. consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
  3619. is reached.
  3620. */
  3621. if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
  3622. if (atomic_load_relaxed (&av->have_fastchunks))
  3623. malloc_consolidate(av);
  3624. if (av == &main_arena) {
  3625. #ifndef MORECORE_CANNOT_TRIM
  3626. if ((unsigned long)(chunksize(av->top)) >=
  3627. (unsigned long)(mp_.trim_threshold))
  3628. systrim(mp_.top_pad, av);
  3629. #endif
  3630. } else {
  3631. /* Always try heap_trim(), even if the top chunk is not
  3632. large, because the corresponding heap might go away. */
  3633. heap_info *heap = heap_for_ptr(top(av));
  3634. assert(heap->ar_ptr == av);
  3635. heap_trim(heap, mp_.top_pad);
  3636. }
  3637. }
  3638. if (!have_lock)
  3639. __libc_lock_unlock (av->mutex);
  3640. }
  3641. /*
  3642. If the chunk was allocated via mmap, release via munmap().
  3643. */
  3644. else {
  3645. munmap_chunk (p);
  3646. }
  3647. }
  3648. /*
  3649. ------------------------- malloc_consolidate -------------------------
  3650. malloc_consolidate is a specialized version of free() that tears
  3651. down chunks held in fastbins. Free itself cannot be used for this
  3652. purpose since, among other things, it might place chunks back onto
  3653. fastbins. So, instead, we need to use a minor variant of the same
  3654. code.
  3655. */
  3656. static void malloc_consolidate(mstate av)
  3657. {
  3658. mfastbinptr* fb; /* current fastbin being consolidated */
  3659. mfastbinptr* maxfb; /* last fastbin (for loop control) */
  3660. mchunkptr p; /* current chunk being consolidated */
  3661. mchunkptr nextp; /* next chunk to consolidate */
  3662. mchunkptr unsorted_bin; /* bin header */
  3663. mchunkptr first_unsorted; /* chunk to link to */
  3664. /* These have same use as in free() */
  3665. mchunkptr nextchunk;
  3666. INTERNAL_SIZE_T size;
  3667. INTERNAL_SIZE_T nextsize;
  3668. INTERNAL_SIZE_T prevsize;
  3669. int nextinuse;
  3670. atomic_store_relaxed (&av->have_fastchunks, false);
  3671. unsorted_bin = unsorted_chunks(av);
  3672. /*
  3673. Remove each chunk from fast bin and consolidate it, placing it
  3674. then in unsorted bin. Among other reasons for doing this,
  3675. placing in unsorted bin avoids needing to calculate actual bins
  3676. until malloc is sure that chunks aren't immediately going to be
  3677. reused anyway.
  3678. */
  3679. maxfb = &fastbin (av, NFASTBINS - 1);
  3680. fb = &fastbin (av, 0);
  3681. do {
  3682. p = atomic_exchange_acq (fb, NULL);
  3683. if (p != 0) {
  3684. do {
  3685. {
  3686. unsigned int idx = fastbin_index (chunksize (p));
  3687. if ((&fastbin (av, idx)) != fb)
  3688. malloc_printerr ("malloc_consolidate(): invalid chunk size");
  3689. }
  3690. check_inuse_chunk(av, p);
  3691. nextp = p->fd;
  3692. /* Slightly streamlined version of consolidation code in free() */
  3693. size = chunksize (p);
  3694. nextchunk = chunk_at_offset(p, size);
  3695. nextsize = chunksize(nextchunk);
  3696. if (!prev_inuse(p)) {
  3697. prevsize = prev_size (p);
  3698. size += prevsize;
  3699. p = chunk_at_offset(p, -((long) prevsize));
  3700. if (__glibc_unlikely (chunksize(p) != prevsize))
  3701. malloc_printerr ("corrupted size vs. prev_size in fastbins");
  3702. unlink_chunk (av, p);
  3703. }
  3704. if (nextchunk != av->top) {
  3705. nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
  3706. if (!nextinuse) {
  3707. size += nextsize;
  3708. unlink_chunk (av, nextchunk);
  3709. } else
  3710. clear_inuse_bit_at_offset(nextchunk, 0);
  3711. first_unsorted = unsorted_bin->fd;
  3712. unsorted_bin->fd = p;
  3713. first_unsorted->bk = p;
  3714. if (!in_smallbin_range (size)) {
  3715. p->fd_nextsize = NULL;
  3716. p->bk_nextsize = NULL;
  3717. }
  3718. set_head(p, size | PREV_INUSE);
  3719. p->bk = unsorted_bin;
  3720. p->fd = first_unsorted;
  3721. set_foot(p, size);
  3722. }
  3723. else {
  3724. size += nextsize;
  3725. set_head(p, size | PREV_INUSE);
  3726. av->top = p;
  3727. }
  3728. } while ( (p = nextp) != 0);
  3729. }
  3730. } while (fb++ != maxfb);
  3731. }
  3732. /*
  3733. ------------------------------ realloc ------------------------------
  3734. */
  3735. void*
  3736. _int_realloc(mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
  3737. INTERNAL_SIZE_T nb)
  3738. {
  3739. mchunkptr newp; /* chunk to return */
  3740. INTERNAL_SIZE_T newsize; /* its size */
  3741. void* newmem; /* corresponding user mem */
  3742. mchunkptr next; /* next contiguous chunk after oldp */
  3743. mchunkptr remainder; /* extra space at end of newp */
  3744. unsigned long remainder_size; /* its size */
  3745. /* oldmem size */
  3746. if (__builtin_expect (chunksize_nomask (oldp) <= 2 * SIZE_SZ, 0)
  3747. || __builtin_expect (oldsize >= av->system_mem, 0))
  3748. malloc_printerr ("realloc(): invalid old size");
  3749. check_inuse_chunk (av, oldp);
  3750. /* All callers already filter out mmap'ed chunks. */
  3751. assert (!chunk_is_mmapped (oldp));
  3752. next = chunk_at_offset (oldp, oldsize);
  3753. INTERNAL_SIZE_T nextsize = chunksize (next);
  3754. if (__builtin_expect (chunksize_nomask (next) <= 2 * SIZE_SZ, 0)
  3755. || __builtin_expect (nextsize >= av->system_mem, 0))
  3756. malloc_printerr ("realloc(): invalid next size");
  3757. if ((unsigned long) (oldsize) >= (unsigned long) (nb))
  3758. {
  3759. /* already big enough; split below */
  3760. newp = oldp;
  3761. newsize = oldsize;
  3762. }
  3763. else
  3764. {
  3765. /* Try to expand forward into top */
  3766. if (next == av->top &&
  3767. (unsigned long) (newsize = oldsize + nextsize) >=
  3768. (unsigned long) (nb + MINSIZE))
  3769. {
  3770. set_head_size (oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
  3771. av->top = chunk_at_offset (oldp, nb);
  3772. set_head (av->top, (newsize - nb) | PREV_INUSE);
  3773. check_inuse_chunk (av, oldp);
  3774. return chunk2mem (oldp);
  3775. }
  3776. /* Try to expand forward into next chunk; split off remainder below */
  3777. else if (next != av->top &&
  3778. !inuse (next) &&
  3779. (unsigned long) (newsize = oldsize + nextsize) >=
  3780. (unsigned long) (nb))
  3781. {
  3782. newp = oldp;
  3783. unlink_chunk (av, next);
  3784. }
  3785. /* allocate, copy, free */
  3786. else
  3787. {
  3788. newmem = _int_malloc (av, nb - MALLOC_ALIGN_MASK);
  3789. if (newmem == 0)
  3790. return 0; /* propagate failure */
  3791. newp = mem2chunk (newmem);
  3792. newsize = chunksize (newp);
  3793. /*
  3794. Avoid copy if newp is next chunk after oldp.
  3795. */
  3796. if (newp == next)
  3797. {
  3798. newsize += oldsize;
  3799. newp = oldp;
  3800. }
  3801. else
  3802. {
  3803. memcpy (newmem, chunk2mem (oldp), oldsize - SIZE_SZ);
  3804. _int_free (av, oldp, 1);
  3805. check_inuse_chunk (av, newp);
  3806. return chunk2mem (newp);
  3807. }
  3808. }
  3809. }
  3810. /* If possible, free extra space in old or extended chunk */
  3811. assert ((unsigned long) (newsize) >= (unsigned long) (nb));
  3812. remainder_size = newsize - nb;
  3813. if (remainder_size < MINSIZE) /* not enough extra to split off */
  3814. {
  3815. set_head_size (newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
  3816. set_inuse_bit_at_offset (newp, newsize);
  3817. }
  3818. else /* split remainder */
  3819. {
  3820. remainder = chunk_at_offset (newp, nb);
  3821. set_head_size (newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
  3822. set_head (remainder, remainder_size | PREV_INUSE |
  3823. (av != &main_arena ? NON_MAIN_ARENA : 0));
  3824. /* Mark remainder as inuse so free() won't complain */
  3825. set_inuse_bit_at_offset (remainder, remainder_size);
  3826. _int_free (av, remainder, 1);
  3827. }
  3828. check_inuse_chunk (av, newp);
  3829. return chunk2mem (newp);
  3830. }
  3831. /*
  3832. ------------------------------ memalign ------------------------------
  3833. */
  3834. static void *
  3835. _int_memalign (mstate av, size_t alignment, size_t bytes)
  3836. {
  3837. INTERNAL_SIZE_T nb; /* padded request size */
  3838. char *m; /* memory returned by malloc call */
  3839. mchunkptr p; /* corresponding chunk */
  3840. char *brk; /* alignment point within p */
  3841. mchunkptr newp; /* chunk to return */
  3842. INTERNAL_SIZE_T newsize; /* its size */
  3843. INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
  3844. mchunkptr remainder; /* spare room at end to split off */
  3845. unsigned long remainder_size; /* its size */
  3846. INTERNAL_SIZE_T size;
  3847. checked_request2size (bytes, nb);
  3848. /*
  3849. Strategy: find a spot within that chunk that meets the alignment
  3850. request, and then possibly free the leading and trailing space.
  3851. */
  3852. /* Check for overflow. */
  3853. if (nb > SIZE_MAX - alignment - MINSIZE)
  3854. {
  3855. __set_errno (ENOMEM);
  3856. return 0;
  3857. }
  3858. /* Call malloc with worst case padding to hit alignment. */
  3859. m = (char *) (_int_malloc (av, nb + alignment + MINSIZE));
  3860. if (m == 0)
  3861. return 0; /* propagate failure */
  3862. p = mem2chunk (m);
  3863. if ((((unsigned long) (m)) % alignment) != 0) /* misaligned */
  3864. { /*
  3865. Find an aligned spot inside chunk. Since we need to give back
  3866. leading space in a chunk of at least MINSIZE, if the first
  3867. calculation places us at a spot with less than MINSIZE leader,
  3868. we can move to the next aligned spot -- we've allocated enough
  3869. total room so that this is always possible.
  3870. */
  3871. brk = (char *) mem2chunk (((unsigned long) (m + alignment - 1)) &
  3872. - ((signed long) alignment));
  3873. if ((unsigned long) (brk - (char *) (p)) < MINSIZE)
  3874. brk += alignment;
  3875. newp = (mchunkptr) brk;
  3876. leadsize = brk - (char *) (p);
  3877. newsize = chunksize (p) - leadsize;
  3878. /* For mmapped chunks, just adjust offset */
  3879. if (chunk_is_mmapped (p))
  3880. {
  3881. set_prev_size (newp, prev_size (p) + leadsize);
  3882. set_head (newp, newsize | IS_MMAPPED);
  3883. return chunk2mem (newp);
  3884. }
  3885. /* Otherwise, give back leader, use the rest */
  3886. set_head (newp, newsize | PREV_INUSE |
  3887. (av != &main_arena ? NON_MAIN_ARENA : 0));
  3888. set_inuse_bit_at_offset (newp, newsize);
  3889. set_head_size (p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
  3890. _int_free (av, p, 1);
  3891. p = newp;
  3892. assert (newsize >= nb &&
  3893. (((unsigned long) (chunk2mem (p))) % alignment) == 0);
  3894. }
  3895. /* Also give back spare room at the end */
  3896. if (!chunk_is_mmapped (p))
  3897. {
  3898. size = chunksize (p);
  3899. if ((unsigned long) (size) > (unsigned long) (nb + MINSIZE))
  3900. {
  3901. remainder_size = size - nb;
  3902. remainder = chunk_at_offset (p, nb);
  3903. set_head (remainder, remainder_size | PREV_INUSE |
  3904. (av != &main_arena ? NON_MAIN_ARENA : 0));
  3905. set_head_size (p, nb);
  3906. _int_free (av, remainder, 1);
  3907. }
  3908. }
  3909. check_inuse_chunk (av, p);
  3910. return chunk2mem (p);
  3911. }
  3912. /*
  3913. ------------------------------ malloc_trim ------------------------------
  3914. */
  3915. static int
  3916. mtrim (mstate av, size_t pad)
  3917. {
  3918. /* Ensure all blocks are consolidated. */
  3919. malloc_consolidate (av);
  3920. const size_t ps = GLRO (dl_pagesize);
  3921. int psindex = bin_index (ps);
  3922. const size_t psm1 = ps - 1;
  3923. int result = 0;
  3924. for (int i = 1; i < NBINS; ++i)
  3925. if (i == 1 || i >= psindex)
  3926. {
  3927. mbinptr bin = bin_at (av, i);
  3928. for (mchunkptr p = last (bin); p != bin; p = p->bk)
  3929. {
  3930. INTERNAL_SIZE_T size = chunksize (p);
  3931. if (size > psm1 + sizeof (struct malloc_chunk))
  3932. {
  3933. /* See whether the chunk contains at least one unused page. */
  3934. char *paligned_mem = (char *) (((uintptr_t) p
  3935. + sizeof (struct malloc_chunk)
  3936. + psm1) & ~psm1);
  3937. assert ((char *) chunk2mem (p) + 4 * SIZE_SZ <= paligned_mem);
  3938. assert ((char *) p + size > paligned_mem);
  3939. /* This is the size we could potentially free. */
  3940. size -= paligned_mem - (char *) p;
  3941. if (size > psm1)
  3942. {
  3943. #if MALLOC_DEBUG
  3944. /* When debugging we simulate destroying the memory
  3945. content. */
  3946. memset (paligned_mem, 0x89, size & ~psm1);
  3947. #endif
  3948. __madvise (paligned_mem, size & ~psm1, MADV_DONTNEED);
  3949. result = 1;
  3950. }
  3951. }
  3952. }
  3953. }
  3954. #ifndef MORECORE_CANNOT_TRIM
  3955. return result | (av == &main_arena ? systrim (pad, av) : 0);
  3956. #else
  3957. return result;
  3958. #endif
  3959. }
  3960. int
  3961. __malloc_trim (size_t s)
  3962. {
  3963. int result = 0;
  3964. if (__malloc_initialized < 0)
  3965. ptmalloc_init ();
  3966. mstate ar_ptr = &main_arena;
  3967. do
  3968. {
  3969. __libc_lock_lock (ar_ptr->mutex);
  3970. result |= mtrim (ar_ptr, s);
  3971. __libc_lock_unlock (ar_ptr->mutex);
  3972. ar_ptr = ar_ptr->next;
  3973. }
  3974. while (ar_ptr != &main_arena);
  3975. return result;
  3976. }
  3977. /*
  3978. ------------------------- malloc_usable_size -------------------------
  3979. */
  3980. static size_t
  3981. musable (void *mem)
  3982. {
  3983. mchunkptr p;
  3984. if (mem != 0)
  3985. {
  3986. p = mem2chunk (mem);
  3987. if (__builtin_expect (using_malloc_checking == 1, 0))
  3988. return malloc_check_get_size (p);
  3989. if (chunk_is_mmapped (p))
  3990. {
  3991. if (DUMPED_MAIN_ARENA_CHUNK (p))
  3992. return chunksize (p) - SIZE_SZ;
  3993. else
  3994. return chunksize (p) - 2 * SIZE_SZ;
  3995. }
  3996. else if (inuse (p))
  3997. return chunksize (p) - SIZE_SZ;
  3998. }
  3999. return 0;
  4000. }
  4001. size_t
  4002. __malloc_usable_size (void *m)
  4003. {
  4004. size_t result;
  4005. result = musable (m);
  4006. return result;
  4007. }
  4008. /*
  4009. ------------------------------ mallinfo ------------------------------
  4010. Accumulate malloc statistics for arena AV into M.
  4011. */
  4012. static void
  4013. int_mallinfo (mstate av, struct mallinfo *m)
  4014. {
  4015. size_t i;
  4016. mbinptr b;
  4017. mchunkptr p;
  4018. INTERNAL_SIZE_T avail;
  4019. INTERNAL_SIZE_T fastavail;
  4020. int nblocks;
  4021. int nfastblocks;
  4022. check_malloc_state (av);
  4023. /* Account for top */
  4024. avail = chunksize (av->top);
  4025. nblocks = 1; /* top always exists */
  4026. /* traverse fastbins */
  4027. nfastblocks = 0;
  4028. fastavail = 0;
  4029. for (i = 0; i < NFASTBINS; ++i)
  4030. {
  4031. for (p = fastbin (av, i); p != 0; p = p->fd)
  4032. {
  4033. ++nfastblocks;
  4034. fastavail += chunksize (p);
  4035. }
  4036. }
  4037. avail += fastavail;
  4038. /* traverse regular bins */
  4039. for (i = 1; i < NBINS; ++i)
  4040. {
  4041. b = bin_at (av, i);
  4042. for (p = last (b); p != b; p = p->bk)
  4043. {
  4044. ++nblocks;
  4045. avail += chunksize (p);
  4046. }
  4047. }
  4048. m->smblks += nfastblocks;
  4049. m->ordblks += nblocks;
  4050. m->fordblks += avail;
  4051. m->uordblks += av->system_mem - avail;
  4052. m->arena += av->system_mem;
  4053. m->fsmblks += fastavail;
  4054. if (av == &main_arena)
  4055. {
  4056. m->hblks = mp_.n_mmaps;
  4057. m->hblkhd = mp_.mmapped_mem;
  4058. m->usmblks = 0;
  4059. m->keepcost = chunksize (av->top);
  4060. }
  4061. }
  4062. struct mallinfo
  4063. __libc_mallinfo (void)
  4064. {
  4065. struct mallinfo m;
  4066. mstate ar_ptr;
  4067. if (__malloc_initialized < 0)
  4068. ptmalloc_init ();
  4069. memset (&m, 0, sizeof (m));
  4070. ar_ptr = &main_arena;
  4071. do
  4072. {
  4073. __libc_lock_lock (ar_ptr->mutex);
  4074. int_mallinfo (ar_ptr, &m);
  4075. __libc_lock_unlock (ar_ptr->mutex);
  4076. ar_ptr = ar_ptr->next;
  4077. }
  4078. while (ar_ptr != &main_arena);
  4079. return m;
  4080. }
  4081. /*
  4082. ------------------------------ malloc_stats ------------------------------
  4083. */
  4084. void
  4085. __malloc_stats (void)
  4086. {
  4087. int i;
  4088. mstate ar_ptr;
  4089. unsigned int in_use_b = mp_.mmapped_mem, system_b = in_use_b;
  4090. if (__malloc_initialized < 0)
  4091. ptmalloc_init ();
  4092. _IO_flockfile (stderr);
  4093. int old_flags2 = stderr->_flags2;
  4094. stderr->_flags2 |= _IO_FLAGS2_NOTCANCEL;
  4095. for (i = 0, ar_ptr = &main_arena;; i++)
  4096. {
  4097. struct mallinfo mi;
  4098. memset (&mi, 0, sizeof (mi));
  4099. __libc_lock_lock (ar_ptr->mutex);
  4100. int_mallinfo (ar_ptr, &mi);
  4101. fprintf (stderr, "Arena %d:\n", i);
  4102. fprintf (stderr, "system bytes = %10u\n", (unsigned int) mi.arena);
  4103. fprintf (stderr, "in use bytes = %10u\n", (unsigned int) mi.uordblks);
  4104. #if MALLOC_DEBUG > 1
  4105. if (i > 0)
  4106. dump_heap (heap_for_ptr (top (ar_ptr)));
  4107. #endif
  4108. system_b += mi.arena;
  4109. in_use_b += mi.uordblks;
  4110. __libc_lock_unlock (ar_ptr->mutex);
  4111. ar_ptr = ar_ptr->next;
  4112. if (ar_ptr == &main_arena)
  4113. break;
  4114. }
  4115. fprintf (stderr, "Total (incl. mmap):\n");
  4116. fprintf (stderr, "system bytes = %10u\n", system_b);
  4117. fprintf (stderr, "in use bytes = %10u\n", in_use_b);
  4118. fprintf (stderr, "max mmap regions = %10u\n", (unsigned int) mp_.max_n_mmaps);
  4119. fprintf (stderr, "max mmap bytes = %10lu\n",
  4120. (unsigned long) mp_.max_mmapped_mem);
  4121. stderr->_flags2 = old_flags2;
  4122. _IO_funlockfile (stderr);
  4123. }
  4124. /*
  4125. ------------------------------ mallopt ------------------------------
  4126. */
  4127. static inline int
  4128. __always_inline
  4129. do_set_trim_threshold (size_t value)
  4130. {
  4131. LIBC_PROBE (memory_mallopt_trim_threshold, 3, value, mp_.trim_threshold,
  4132. mp_.no_dyn_threshold);
  4133. mp_.trim_threshold = value;
  4134. mp_.no_dyn_threshold = 1;
  4135. return 1;
  4136. }
  4137. static inline int
  4138. __always_inline
  4139. do_set_top_pad (size_t value)
  4140. {
  4141. LIBC_PROBE (memory_mallopt_top_pad, 3, value, mp_.top_pad,
  4142. mp_.no_dyn_threshold);
  4143. mp_.top_pad = value;
  4144. mp_.no_dyn_threshold = 1;
  4145. return 1;
  4146. }
  4147. static inline int
  4148. __always_inline
  4149. do_set_mmap_threshold (size_t value)
  4150. {
  4151. /* Forbid setting the threshold too high. */
  4152. if (value <= HEAP_MAX_SIZE / 2)
  4153. {
  4154. LIBC_PROBE (memory_mallopt_mmap_threshold, 3, value, mp_.mmap_threshold,
  4155. mp_.no_dyn_threshold);
  4156. mp_.mmap_threshold = value;
  4157. mp_.no_dyn_threshold = 1;
  4158. return 1;
  4159. }
  4160. return 0;
  4161. }
  4162. static inline int
  4163. __always_inline
  4164. do_set_mmaps_max (int32_t value)
  4165. {
  4166. LIBC_PROBE (memory_mallopt_mmap_max, 3, value, mp_.n_mmaps_max,
  4167. mp_.no_dyn_threshold);
  4168. mp_.n_mmaps_max = value;
  4169. mp_.no_dyn_threshold = 1;
  4170. return 1;
  4171. }
  4172. static inline int
  4173. __always_inline
  4174. do_set_mallopt_check (int32_t value)
  4175. {
  4176. return 1;
  4177. }
  4178. static inline int
  4179. __always_inline
  4180. do_set_perturb_byte (int32_t value)
  4181. {
  4182. LIBC_PROBE (memory_mallopt_perturb, 2, value, perturb_byte);
  4183. perturb_byte = value;
  4184. return 1;
  4185. }
  4186. static inline int
  4187. __always_inline
  4188. do_set_arena_test (size_t value)
  4189. {
  4190. LIBC_PROBE (memory_mallopt_arena_test, 2, value, mp_.arena_test);
  4191. mp_.arena_test = value;
  4192. return 1;
  4193. }
  4194. static inline int
  4195. __always_inline
  4196. do_set_arena_max (size_t value)
  4197. {
  4198. LIBC_PROBE (memory_mallopt_arena_max, 2, value, mp_.arena_max);
  4199. mp_.arena_max = value;
  4200. return 1;
  4201. }
  4202. #if USE_TCACHE
  4203. static inline int
  4204. __always_inline
  4205. do_set_tcache_max (size_t value)
  4206. {
  4207. if (value >= 0 && value <= MAX_TCACHE_SIZE)
  4208. {
  4209. LIBC_PROBE (memory_tunable_tcache_max_bytes, 2, value, mp_.tcache_max_bytes);
  4210. mp_.tcache_max_bytes = value;
  4211. mp_.tcache_bins = csize2tidx (request2size(value)) + 1;
  4212. }
  4213. return 1;
  4214. }
  4215. static inline int
  4216. __always_inline
  4217. do_set_tcache_count (size_t value)
  4218. {
  4219. LIBC_PROBE (memory_tunable_tcache_count, 2, value, mp_.tcache_count);
  4220. mp_.tcache_count = value;
  4221. return 1;
  4222. }
  4223. static inline int
  4224. __always_inline
  4225. do_set_tcache_unsorted_limit (size_t value)
  4226. {
  4227. LIBC_PROBE (memory_tunable_tcache_unsorted_limit, 2, value, mp_.tcache_unsorted_limit);
  4228. mp_.tcache_unsorted_limit = value;
  4229. return 1;
  4230. }
  4231. #endif
  4232. int
  4233. __libc_mallopt (int param_number, int value)
  4234. {
  4235. mstate av = &main_arena;
  4236. int res = 1;
  4237. if (__malloc_initialized < 0)
  4238. ptmalloc_init ();
  4239. __libc_lock_lock (av->mutex);
  4240. LIBC_PROBE (memory_mallopt, 2, param_number, value);
  4241. /* We must consolidate main arena before changing max_fast
  4242. (see definition of set_max_fast). */
  4243. malloc_consolidate (av);
  4244. switch (param_number)
  4245. {
  4246. case M_MXFAST:
  4247. if (value >= 0 && value <= MAX_FAST_SIZE)
  4248. {
  4249. LIBC_PROBE (memory_mallopt_mxfast, 2, value, get_max_fast ());
  4250. set_max_fast (value);
  4251. }
  4252. else
  4253. res = 0;
  4254. break;
  4255. case M_TRIM_THRESHOLD:
  4256. do_set_trim_threshold (value);
  4257. break;
  4258. case M_TOP_PAD:
  4259. do_set_top_pad (value);
  4260. break;
  4261. case M_MMAP_THRESHOLD:
  4262. res = do_set_mmap_threshold (value);
  4263. break;
  4264. case M_MMAP_MAX:
  4265. do_set_mmaps_max (value);
  4266. break;
  4267. case M_CHECK_ACTION:
  4268. do_set_mallopt_check (value);
  4269. break;
  4270. case M_PERTURB:
  4271. do_set_perturb_byte (value);
  4272. break;
  4273. case M_ARENA_TEST:
  4274. if (value > 0)
  4275. do_set_arena_test (value);
  4276. break;
  4277. case M_ARENA_MAX:
  4278. if (value > 0)
  4279. do_set_arena_max (value);
  4280. break;
  4281. }
  4282. __libc_lock_unlock (av->mutex);
  4283. return res;
  4284. }
  4285. libc_hidden_def (__libc_mallopt)
  4286. /*
  4287. -------------------- Alternative MORECORE functions --------------------
  4288. */
  4289. /*
  4290. General Requirements for MORECORE.
  4291. The MORECORE function must have the following properties:
  4292. If MORECORE_CONTIGUOUS is false:
  4293. * MORECORE must allocate in multiples of pagesize. It will
  4294. only be called with arguments that are multiples of pagesize.
  4295. * MORECORE(0) must return an address that is at least
  4296. MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)
  4297. else (i.e. If MORECORE_CONTIGUOUS is true):
  4298. * Consecutive calls to MORECORE with positive arguments
  4299. return increasing addresses, indicating that space has been
  4300. contiguously extended.
  4301. * MORECORE need not allocate in multiples of pagesize.
  4302. Calls to MORECORE need not have args of multiples of pagesize.
  4303. * MORECORE need not page-align.
  4304. In either case:
  4305. * MORECORE may allocate more memory than requested. (Or even less,
  4306. but this will generally result in a malloc failure.)
  4307. * MORECORE must not allocate memory when given argument zero, but
  4308. instead return one past the end address of memory from previous
  4309. nonzero call. This malloc does NOT call MORECORE(0)
  4310. until at least one call with positive arguments is made, so
  4311. the initial value returned is not important.
  4312. * Even though consecutive calls to MORECORE need not return contiguous
  4313. addresses, it must be OK for malloc'ed chunks to span multiple
  4314. regions in those cases where they do happen to be contiguous.
  4315. * MORECORE need not handle negative arguments -- it may instead
  4316. just return MORECORE_FAILURE when given negative arguments.
  4317. Negative arguments are always multiples of pagesize. MORECORE
  4318. must not misinterpret negative args as large positive unsigned
  4319. args. You can suppress all such calls from even occurring by defining
  4320. MORECORE_CANNOT_TRIM,
  4321. There is some variation across systems about the type of the
  4322. argument to sbrk/MORECORE. If size_t is unsigned, then it cannot
  4323. actually be size_t, because sbrk supports negative args, so it is
  4324. normally the signed type of the same width as size_t (sometimes
  4325. declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much
  4326. matter though. Internally, we use "long" as arguments, which should
  4327. work across all reasonable possibilities.
  4328. Additionally, if MORECORE ever returns failure for a positive
  4329. request, then mmap is used as a noncontiguous system allocator. This
  4330. is a useful backup strategy for systems with holes in address spaces
  4331. -- in this case sbrk cannot contiguously expand the heap, but mmap
  4332. may be able to map noncontiguous space.
  4333. If you'd like mmap to ALWAYS be used, you can define MORECORE to be
  4334. a function that always returns MORECORE_FAILURE.
  4335. If you are using this malloc with something other than sbrk (or its
  4336. emulation) to supply memory regions, you probably want to set
  4337. MORECORE_CONTIGUOUS as false. As an example, here is a custom
  4338. allocator kindly contributed for pre-OSX macOS. It uses virtually
  4339. but not necessarily physically contiguous non-paged memory (locked
  4340. in, present and won't get swapped out). You can use it by
  4341. uncommenting this section, adding some #includes, and setting up the
  4342. appropriate defines above:
  4343. *#define MORECORE osMoreCore
  4344. *#define MORECORE_CONTIGUOUS 0
  4345. There is also a shutdown routine that should somehow be called for
  4346. cleanup upon program exit.
  4347. *#define MAX_POOL_ENTRIES 100
  4348. *#define MINIMUM_MORECORE_SIZE (64 * 1024)
  4349. static int next_os_pool;
  4350. void *our_os_pools[MAX_POOL_ENTRIES];
  4351. void *osMoreCore(int size)
  4352. {
  4353. void *ptr = 0;
  4354. static void *sbrk_top = 0;
  4355. if (size > 0)
  4356. {
  4357. if (size < MINIMUM_MORECORE_SIZE)
  4358. size = MINIMUM_MORECORE_SIZE;
  4359. if (CurrentExecutionLevel() == kTaskLevel)
  4360. ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
  4361. if (ptr == 0)
  4362. {
  4363. return (void *) MORECORE_FAILURE;
  4364. }
  4365. // save ptrs so they can be freed during cleanup
  4366. our_os_pools[next_os_pool] = ptr;
  4367. next_os_pool++;
  4368. ptr = (void *) ((((unsigned long) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
  4369. sbrk_top = (char *) ptr + size;
  4370. return ptr;
  4371. }
  4372. else if (size < 0)
  4373. {
  4374. // we don't currently support shrink behavior
  4375. return (void *) MORECORE_FAILURE;
  4376. }
  4377. else
  4378. {
  4379. return sbrk_top;
  4380. }
  4381. }
  4382. // cleanup any allocated memory pools
  4383. // called as last thing before shutting down driver
  4384. void osCleanupMem(void)
  4385. {
  4386. void **ptr;
  4387. for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
  4388. if (*ptr)
  4389. {
  4390. PoolDeallocate(*ptr);
  4391. * ptr = 0;
  4392. }
  4393. }
  4394. */
  4395. /* Helper code. */
  4396. extern char **__libc_argv attribute_hidden;
  4397. static void
  4398. malloc_printerr (const char *str)
  4399. {
  4400. __libc_message (do_abort, "%s\n", str);
  4401. __builtin_unreachable ();
  4402. }
  4403. /* We need a wrapper function for one of the additions of POSIX. */
  4404. int
  4405. __posix_memalign (void **memptr, size_t alignment, size_t size)
  4406. {
  4407. void *mem;
  4408. /* Test whether the SIZE argument is valid. It must be a power of
  4409. two multiple of sizeof (void *). */
  4410. if (alignment % sizeof (void *) != 0
  4411. || !powerof2 (alignment / sizeof (void *))
  4412. || alignment == 0)
  4413. return EINVAL;
  4414. void *address = RETURN_ADDRESS (0);
  4415. mem = _mid_memalign (alignment, size, address);
  4416. if (mem != NULL)
  4417. {
  4418. *memptr = mem;
  4419. return 0;
  4420. }
  4421. return ENOMEM;
  4422. }
  4423. weak_alias (__posix_memalign, posix_memalign)
  4424. int
  4425. __malloc_info (int options, FILE *fp)
  4426. {
  4427. /* For now, at least. */
  4428. if (options != 0)
  4429. return EINVAL;
  4430. int n = 0;
  4431. size_t total_nblocks = 0;
  4432. size_t total_nfastblocks = 0;
  4433. size_t total_avail = 0;
  4434. size_t total_fastavail = 0;
  4435. size_t total_system = 0;
  4436. size_t total_max_system = 0;
  4437. size_t total_aspace = 0;
  4438. size_t total_aspace_mprotect = 0;
  4439. if (__malloc_initialized < 0)
  4440. ptmalloc_init ();
  4441. fputs ("<malloc version=\"1\">\n", fp);
  4442. /* Iterate over all arenas currently in use. */
  4443. mstate ar_ptr = &main_arena;
  4444. do
  4445. {
  4446. fprintf (fp, "<heap nr=\"%d\">\n<sizes>\n", n++);
  4447. size_t nblocks = 0;
  4448. size_t nfastblocks = 0;
  4449. size_t avail = 0;
  4450. size_t fastavail = 0;
  4451. struct
  4452. {
  4453. size_t from;
  4454. size_t to;
  4455. size_t total;
  4456. size_t count;
  4457. } sizes[NFASTBINS + NBINS - 1];
  4458. #define nsizes (sizeof (sizes) / sizeof (sizes[0]))
  4459. __libc_lock_lock (ar_ptr->mutex);
  4460. for (size_t i = 0; i < NFASTBINS; ++i)
  4461. {
  4462. mchunkptr p = fastbin (ar_ptr, i);
  4463. if (p != NULL)
  4464. {
  4465. size_t nthissize = 0;
  4466. size_t thissize = chunksize (p);
  4467. while (p != NULL)
  4468. {
  4469. ++nthissize;
  4470. p = p->fd;
  4471. }
  4472. fastavail += nthissize * thissize;
  4473. nfastblocks += nthissize;
  4474. sizes[i].from = thissize - (MALLOC_ALIGNMENT - 1);
  4475. sizes[i].to = thissize;
  4476. sizes[i].count = nthissize;
  4477. }
  4478. else
  4479. sizes[i].from = sizes[i].to = sizes[i].count = 0;
  4480. sizes[i].total = sizes[i].count * sizes[i].to;
  4481. }
  4482. mbinptr bin;
  4483. struct malloc_chunk *r;
  4484. for (size_t i = 1; i < NBINS; ++i)
  4485. {
  4486. bin = bin_at (ar_ptr, i);
  4487. r = bin->fd;
  4488. sizes[NFASTBINS - 1 + i].from = ~((size_t) 0);
  4489. sizes[NFASTBINS - 1 + i].to = sizes[NFASTBINS - 1 + i].total
  4490. = sizes[NFASTBINS - 1 + i].count = 0;
  4491. if (r != NULL)
  4492. while (r != bin)
  4493. {
  4494. size_t r_size = chunksize_nomask (r);
  4495. ++sizes[NFASTBINS - 1 + i].count;
  4496. sizes[NFASTBINS - 1 + i].total += r_size;
  4497. sizes[NFASTBINS - 1 + i].from
  4498. = MIN (sizes[NFASTBINS - 1 + i].from, r_size);
  4499. sizes[NFASTBINS - 1 + i].to = MAX (sizes[NFASTBINS - 1 + i].to,
  4500. r_size);
  4501. r = r->fd;
  4502. }
  4503. if (sizes[NFASTBINS - 1 + i].count == 0)
  4504. sizes[NFASTBINS - 1 + i].from = 0;
  4505. nblocks += sizes[NFASTBINS - 1 + i].count;
  4506. avail += sizes[NFASTBINS - 1 + i].total;
  4507. }
  4508. size_t heap_size = 0;
  4509. size_t heap_mprotect_size = 0;
  4510. size_t heap_count = 0;
  4511. if (ar_ptr != &main_arena)
  4512. {
  4513. /* Iterate over the arena heaps from back to front. */
  4514. heap_info *heap = heap_for_ptr (top (ar_ptr));
  4515. do
  4516. {
  4517. heap_size += heap->size;
  4518. heap_mprotect_size += heap->mprotect_size;
  4519. heap = heap->prev;
  4520. ++heap_count;
  4521. }
  4522. while (heap != NULL);
  4523. }
  4524. __libc_lock_unlock (ar_ptr->mutex);
  4525. total_nfastblocks += nfastblocks;
  4526. total_fastavail += fastavail;
  4527. total_nblocks += nblocks;
  4528. total_avail += avail;
  4529. for (size_t i = 0; i < nsizes; ++i)
  4530. if (sizes[i].count != 0 && i != NFASTBINS)
  4531. fprintf (fp, " \
  4532. <size from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
  4533. sizes[i].from, sizes[i].to, sizes[i].total, sizes[i].count);
  4534. if (sizes[NFASTBINS].count != 0)
  4535. fprintf (fp, "\
  4536. <unsorted from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
  4537. sizes[NFASTBINS].from, sizes[NFASTBINS].to,
  4538. sizes[NFASTBINS].total, sizes[NFASTBINS].count);
  4539. total_system += ar_ptr->system_mem;
  4540. total_max_system += ar_ptr->max_system_mem;
  4541. fprintf (fp,
  4542. "</sizes>\n<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
  4543. "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
  4544. "<system type=\"current\" size=\"%zu\"/>\n"
  4545. "<system type=\"max\" size=\"%zu\"/>\n",
  4546. nfastblocks, fastavail, nblocks, avail,
  4547. ar_ptr->system_mem, ar_ptr->max_system_mem);
  4548. if (ar_ptr != &main_arena)
  4549. {
  4550. fprintf (fp,
  4551. "<aspace type=\"total\" size=\"%zu\"/>\n"
  4552. "<aspace type=\"mprotect\" size=\"%zu\"/>\n"
  4553. "<aspace type=\"subheaps\" size=\"%zu\"/>\n",
  4554. heap_size, heap_mprotect_size, heap_count);
  4555. total_aspace += heap_size;
  4556. total_aspace_mprotect += heap_mprotect_size;
  4557. }
  4558. else
  4559. {
  4560. fprintf (fp,
  4561. "<aspace type=\"total\" size=\"%zu\"/>\n"
  4562. "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
  4563. ar_ptr->system_mem, ar_ptr->system_mem);
  4564. total_aspace += ar_ptr->system_mem;
  4565. total_aspace_mprotect += ar_ptr->system_mem;
  4566. }
  4567. fputs ("</heap>\n", fp);
  4568. ar_ptr = ar_ptr->next;
  4569. }
  4570. while (ar_ptr != &main_arena);
  4571. fprintf (fp,
  4572. "<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
  4573. "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
  4574. "<total type=\"mmap\" count=\"%d\" size=\"%zu\"/>\n"
  4575. "<system type=\"current\" size=\"%zu\"/>\n"
  4576. "<system type=\"max\" size=\"%zu\"/>\n"
  4577. "<aspace type=\"total\" size=\"%zu\"/>\n"
  4578. "<aspace type=\"mprotect\" size=\"%zu\"/>\n"
  4579. "</malloc>\n",
  4580. total_nfastblocks, total_fastavail, total_nblocks, total_avail,
  4581. mp_.n_mmaps, mp_.mmapped_mem,
  4582. total_system, total_max_system,
  4583. total_aspace, total_aspace_mprotect);
  4584. return 0;
  4585. }
  4586. weak_alias (__malloc_info, malloc_info)
  4587. strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
  4588. strong_alias (__libc_free, __free) strong_alias (__libc_free, free)
  4589. strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)
  4590. strong_alias (__libc_memalign, __memalign)
  4591. weak_alias (__libc_memalign, memalign)
  4592. strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)
  4593. strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
  4594. strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
  4595. strong_alias (__libc_mallinfo, __mallinfo)
  4596. weak_alias (__libc_mallinfo, mallinfo)
  4597. strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
  4598. weak_alias (__malloc_stats, malloc_stats)
  4599. weak_alias (__malloc_usable_size, malloc_usable_size)
  4600. weak_alias (__malloc_trim, malloc_trim)
  4601. #if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_26)
  4602. compat_symbol (libc, __libc_free, cfree, GLIBC_2_0);
  4603. #endif
  4604. /* ------------------------------------------------------------
  4605. History:
  4606. [see ftp://g.oswego.edu/pub/misc/malloc.c for the history of dlmalloc]
  4607. */
  4608. /*
  4609. * Local variables:
  4610. * c-basic-offset: 2
  4611. * End:
  4612. */