SDL_malloc.c 183 KB

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