malloc.c 177 KB

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