memory.texi 152 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917
  1. @node Memory, Character Handling, Error Reporting, Top
  2. @chapter Virtual Memory Allocation And Paging
  3. @c %MENU% Allocating virtual memory and controlling paging
  4. @cindex memory allocation
  5. @cindex storage allocation
  6. This chapter describes how processes manage and use memory in a system
  7. that uses @theglibc{}.
  8. @Theglibc{} has several functions for dynamically allocating
  9. virtual memory in various ways. They vary in generality and in
  10. efficiency. The library also provides functions for controlling paging
  11. and allocation of real memory.
  12. @menu
  13. * Memory Concepts:: An introduction to concepts and terminology.
  14. * Memory Allocation:: Allocating storage for your program data
  15. * Resizing the Data Segment:: @code{brk}, @code{sbrk}
  16. * Memory Protection:: Controlling access to memory regions.
  17. * Locking Pages:: Preventing page faults
  18. @end menu
  19. Memory mapped I/O is not discussed in this chapter. @xref{Memory-mapped I/O}.
  20. @node Memory Concepts
  21. @section Process Memory Concepts
  22. One of the most basic resources a process has available to it is memory.
  23. There are a lot of different ways systems organize memory, but in a
  24. typical one, each process has one linear virtual address space, with
  25. addresses running from zero to some huge maximum. It need not be
  26. contiguous; i.e., not all of these addresses actually can be used to
  27. store data.
  28. The virtual memory is divided into pages (4 kilobytes is typical).
  29. Backing each page of virtual memory is a page of real memory (called a
  30. @dfn{frame}) or some secondary storage, usually disk space. The disk
  31. space might be swap space or just some ordinary disk file. Actually, a
  32. page of all zeroes sometimes has nothing at all backing it -- there's
  33. just a flag saying it is all zeroes.
  34. @cindex page frame
  35. @cindex frame, real memory
  36. @cindex swap space
  37. @cindex page, virtual memory
  38. The same frame of real memory or backing store can back multiple virtual
  39. pages belonging to multiple processes. This is normally the case, for
  40. example, with virtual memory occupied by @glibcadj{} code. The same
  41. real memory frame containing the @code{printf} function backs a virtual
  42. memory page in each of the existing processes that has a @code{printf}
  43. call in its program.
  44. In order for a program to access any part of a virtual page, the page
  45. must at that moment be backed by (``connected to'') a real frame. But
  46. because there is usually a lot more virtual memory than real memory, the
  47. pages must move back and forth between real memory and backing store
  48. regularly, coming into real memory when a process needs to access them
  49. and then retreating to backing store when not needed anymore. This
  50. movement is called @dfn{paging}.
  51. When a program attempts to access a page which is not at that moment
  52. backed by real memory, this is known as a @dfn{page fault}. When a page
  53. fault occurs, the kernel suspends the process, places the page into a
  54. real page frame (this is called ``paging in'' or ``faulting in''), then
  55. resumes the process so that from the process' point of view, the page
  56. was in real memory all along. In fact, to the process, all pages always
  57. seem to be in real memory. Except for one thing: the elapsed execution
  58. time of an instruction that would normally be a few nanoseconds is
  59. suddenly much, much, longer (because the kernel normally has to do I/O
  60. to complete the page-in). For programs sensitive to that, the functions
  61. described in @ref{Locking Pages} can control it.
  62. @cindex page fault
  63. @cindex paging
  64. Within each virtual address space, a process has to keep track of what
  65. is at which addresses, and that process is called memory allocation.
  66. Allocation usually brings to mind meting out scarce resources, but in
  67. the case of virtual memory, that's not a major goal, because there is
  68. generally much more of it than anyone needs. Memory allocation within a
  69. process is mainly just a matter of making sure that the same byte of
  70. memory isn't used to store two different things.
  71. Processes allocate memory in two major ways: by exec and
  72. programmatically. Actually, forking is a third way, but it's not very
  73. interesting. @xref{Creating a Process}.
  74. Exec is the operation of creating a virtual address space for a process,
  75. loading its basic program into it, and executing the program. It is
  76. done by the ``exec'' family of functions (e.g. @code{execl}). The
  77. operation takes a program file (an executable), it allocates space to
  78. load all the data in the executable, loads it, and transfers control to
  79. it. That data is most notably the instructions of the program (the
  80. @dfn{text}), but also literals and constants in the program and even
  81. some variables: C variables with the static storage class (@pxref{Memory
  82. Allocation and C}).
  83. @cindex executable
  84. @cindex literals
  85. @cindex constants
  86. Once that program begins to execute, it uses programmatic allocation to
  87. gain additional memory. In a C program with @theglibc{}, there
  88. are two kinds of programmatic allocation: automatic and dynamic.
  89. @xref{Memory Allocation and C}.
  90. Memory-mapped I/O is another form of dynamic virtual memory allocation.
  91. Mapping memory to a file means declaring that the contents of certain
  92. range of a process' addresses shall be identical to the contents of a
  93. specified regular file. The system makes the virtual memory initially
  94. contain the contents of the file, and if you modify the memory, the
  95. system writes the same modification to the file. Note that due to the
  96. magic of virtual memory and page faults, there is no reason for the
  97. system to do I/O to read the file, or allocate real memory for its
  98. contents, until the program accesses the virtual memory.
  99. @xref{Memory-mapped I/O}.
  100. @cindex memory mapped I/O
  101. @cindex memory mapped file
  102. @cindex files, accessing
  103. Just as it programmatically allocates memory, the program can
  104. programmatically deallocate (@dfn{free}) it. You can't free the memory
  105. that was allocated by exec. When the program exits or execs, you might
  106. say that all its memory gets freed, but since in both cases the address
  107. space ceases to exist, the point is really moot. @xref{Program
  108. Termination}.
  109. @cindex execing a program
  110. @cindex freeing memory
  111. @cindex exiting a program
  112. A process' virtual address space is divided into segments. A segment is
  113. a contiguous range of virtual addresses. Three important segments are:
  114. @itemize @bullet
  115. @item
  116. The @dfn{text segment} contains a program's instructions and literals and
  117. static constants. It is allocated by exec and stays the same size for
  118. the life of the virtual address space.
  119. @item
  120. The @dfn{data segment} is working storage for the program. It can be
  121. preallocated and preloaded by exec and the process can extend or shrink
  122. it by calling functions as described in @xref{Resizing the Data
  123. Segment}. Its lower end is fixed.
  124. @item
  125. The @dfn{stack segment} contains a program stack. It grows as the stack
  126. grows, but doesn't shrink when the stack shrinks.
  127. @end itemize
  128. @node Memory Allocation
  129. @section Allocating Storage For Program Data
  130. This section covers how ordinary programs manage storage for their data,
  131. including the famous @code{malloc} function and some fancier facilities
  132. special to @theglibc{} and GNU Compiler.
  133. @menu
  134. * Memory Allocation and C:: How to get different kinds of allocation in C.
  135. * The GNU Allocator:: An overview of the GNU @code{malloc}
  136. implementation.
  137. * Unconstrained Allocation:: The @code{malloc} facility allows fully general
  138. dynamic allocation.
  139. * Allocation Debugging:: Finding memory leaks and not freed memory.
  140. * Replacing malloc:: Using your own @code{malloc}-style allocator.
  141. * Obstacks:: Obstacks are less general than malloc
  142. but more efficient and convenient.
  143. * Variable Size Automatic:: Allocation of variable-sized blocks
  144. of automatic storage that are freed when the
  145. calling function returns.
  146. @end menu
  147. @node Memory Allocation and C
  148. @subsection Memory Allocation in C Programs
  149. The C language supports two kinds of memory allocation through the
  150. variables in C programs:
  151. @itemize @bullet
  152. @item
  153. @dfn{Static allocation} is what happens when you declare a static or
  154. global variable. Each static or global variable defines one block of
  155. space, of a fixed size. The space is allocated once, when your program
  156. is started (part of the exec operation), and is never freed.
  157. @cindex static memory allocation
  158. @cindex static storage class
  159. @item
  160. @dfn{Automatic allocation} happens when you declare an automatic
  161. variable, such as a function argument or a local variable. The space
  162. for an automatic variable is allocated when the compound statement
  163. containing the declaration is entered, and is freed when that
  164. compound statement is exited.
  165. @cindex automatic memory allocation
  166. @cindex automatic storage class
  167. In GNU C, the size of the automatic storage can be an expression
  168. that varies. In other C implementations, it must be a constant.
  169. @end itemize
  170. A third important kind of memory allocation, @dfn{dynamic allocation},
  171. is not supported by C variables but is available via @glibcadj{}
  172. functions.
  173. @cindex dynamic memory allocation
  174. @subsubsection Dynamic Memory Allocation
  175. @cindex dynamic memory allocation
  176. @dfn{Dynamic memory allocation} is a technique in which programs
  177. determine as they are running where to store some information. You need
  178. dynamic allocation when the amount of memory you need, or how long you
  179. continue to need it, depends on factors that are not known before the
  180. program runs.
  181. For example, you may need a block to store a line read from an input
  182. file; since there is no limit to how long a line can be, you must
  183. allocate the memory dynamically and make it dynamically larger as you
  184. read more of the line.
  185. Or, you may need a block for each record or each definition in the input
  186. data; since you can't know in advance how many there will be, you must
  187. allocate a new block for each record or definition as you read it.
  188. When you use dynamic allocation, the allocation of a block of memory is
  189. an action that the program requests explicitly. You call a function or
  190. macro when you want to allocate space, and specify the size with an
  191. argument. If you want to free the space, you do so by calling another
  192. function or macro. You can do these things whenever you want, as often
  193. as you want.
  194. Dynamic allocation is not supported by C variables; there is no storage
  195. class ``dynamic'', and there can never be a C variable whose value is
  196. stored in dynamically allocated space. The only way to get dynamically
  197. allocated memory is via a system call (which is generally via a @glibcadj{}
  198. function call), and the only way to refer to dynamically
  199. allocated space is through a pointer. Because it is less convenient,
  200. and because the actual process of dynamic allocation requires more
  201. computation time, programmers generally use dynamic allocation only when
  202. neither static nor automatic allocation will serve.
  203. For example, if you want to allocate dynamically some space to hold a
  204. @code{struct foobar}, you cannot declare a variable of type @code{struct
  205. foobar} whose contents are the dynamically allocated space. But you can
  206. declare a variable of pointer type @code{struct foobar *} and assign it the
  207. address of the space. Then you can use the operators @samp{*} and
  208. @samp{->} on this pointer variable to refer to the contents of the space:
  209. @smallexample
  210. @{
  211. struct foobar *ptr = malloc (sizeof *ptr);
  212. ptr->name = x;
  213. ptr->next = current_foobar;
  214. current_foobar = ptr;
  215. @}
  216. @end smallexample
  217. @node The GNU Allocator
  218. @subsection The GNU Allocator
  219. @cindex gnu allocator
  220. The @code{malloc} implementation in @theglibc{} is derived from ptmalloc
  221. (pthreads malloc), which in turn is derived from dlmalloc (Doug Lea malloc).
  222. This @code{malloc} may allocate memory
  223. in two different ways depending on their size
  224. and certain parameters that may be controlled by users. The most common way is
  225. to allocate portions of memory (called chunks) from a large contiguous area of
  226. memory and manage these areas to optimize their use and reduce wastage in the
  227. form of unusable chunks. Traditionally the system heap was set up to be the one
  228. large memory area but the @glibcadj{} @code{malloc} implementation maintains
  229. multiple such areas to optimize their use in multi-threaded applications. Each
  230. such area is internally referred to as an @dfn{arena}.
  231. As opposed to other versions, the @code{malloc} in @theglibc{} does not round
  232. up chunk sizes to powers of two, neither for large nor for small sizes.
  233. Neighboring chunks can be coalesced on a @code{free} no matter what their size
  234. is. This makes the implementation suitable for all kinds of allocation
  235. patterns without generally incurring high memory waste through fragmentation.
  236. The presence of multiple arenas allows multiple threads to allocate
  237. memory simultaneously in separate arenas, thus improving performance.
  238. The other way of memory allocation is for very large blocks, i.e. much larger
  239. than a page. These requests are allocated with @code{mmap} (anonymous or via
  240. @file{/dev/zero}; @pxref{Memory-mapped I/O})). This has the great advantage
  241. that these chunks are returned to the system immediately when they are freed.
  242. Therefore, it cannot happen that a large chunk becomes ``locked'' in between
  243. smaller ones and even after calling @code{free} wastes memory. The size
  244. threshold for @code{mmap} to be used is dynamic and gets adjusted according to
  245. allocation patterns of the program. @code{mallopt} can be used to statically
  246. adjust the threshold using @code{M_MMAP_THRESHOLD} and the use of @code{mmap}
  247. can be disabled completely with @code{M_MMAP_MAX};
  248. @pxref{Malloc Tunable Parameters}.
  249. A more detailed technical description of the GNU Allocator is maintained in
  250. the @glibcadj{} wiki. See
  251. @uref{https://sourceware.org/glibc/wiki/MallocInternals}.
  252. It is possible to use your own custom @code{malloc} instead of the
  253. built-in allocator provided by @theglibc{}. @xref{Replacing malloc}.
  254. @node Unconstrained Allocation
  255. @subsection Unconstrained Allocation
  256. @cindex unconstrained memory allocation
  257. @cindex @code{malloc} function
  258. @cindex heap, dynamic allocation from
  259. The most general dynamic allocation facility is @code{malloc}. It
  260. allows you to allocate blocks of memory of any size at any time, make
  261. them bigger or smaller at any time, and free the blocks individually at
  262. any time (or never).
  263. @menu
  264. * Basic Allocation:: Simple use of @code{malloc}.
  265. * Malloc Examples:: Examples of @code{malloc}. @code{xmalloc}.
  266. * Freeing after Malloc:: Use @code{free} to free a block you
  267. got with @code{malloc}.
  268. * Changing Block Size:: Use @code{realloc} to make a block
  269. bigger or smaller.
  270. * Allocating Cleared Space:: Use @code{calloc} to allocate a
  271. block and clear it.
  272. * Aligned Memory Blocks:: Allocating specially aligned memory.
  273. * Malloc Tunable Parameters:: Use @code{mallopt} to adjust allocation
  274. parameters.
  275. * Heap Consistency Checking:: Automatic checking for errors.
  276. * Statistics of Malloc:: Getting information about how much
  277. memory your program is using.
  278. * Summary of Malloc:: Summary of @code{malloc} and related functions.
  279. @end menu
  280. @node Basic Allocation
  281. @subsubsection Basic Memory Allocation
  282. @cindex allocation of memory with @code{malloc}
  283. To allocate a block of memory, call @code{malloc}. The prototype for
  284. this function is in @file{stdlib.h}.
  285. @pindex stdlib.h
  286. @deftypefun {void *} malloc (size_t @var{size})
  287. @standards{ISO, malloc.h}
  288. @standards{ISO, stdlib.h}
  289. @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
  290. @c Malloc hooks and __morecore pointers, as well as such parameters as
  291. @c max_n_mmaps and max_mmapped_mem, are accessed without guards, so they
  292. @c could pose a thread safety issue; in order to not declare malloc
  293. @c MT-unsafe, it's modifying the hooks and parameters while multiple
  294. @c threads are active that is regarded as unsafe. An arena's next field
  295. @c is initialized and never changed again, except for main_arena's,
  296. @c that's protected by list_lock; next_free is only modified while
  297. @c list_lock is held too. All other data members of an arena, as well
  298. @c as the metadata of the memory areas assigned to it, are only modified
  299. @c while holding the arena's mutex (fastbin pointers use atomic ops
  300. @c because they may be modified by free without taking the arena's
  301. @c lock). Some reassurance was needed for fastbins, for it wasn't clear
  302. @c how they were initialized. It turns out they are always
  303. @c zero-initialized: main_arena's, for being static data, and other
  304. @c arena's, for being just-mmapped memory.
  305. @c Leaking file descriptors and memory in case of cancellation is
  306. @c unavoidable without disabling cancellation, but the lock situation is
  307. @c a bit more complicated: we don't have fallback arenas for malloc to
  308. @c be safe to call from within signal handlers. Error-checking mutexes
  309. @c or trylock could enable us to try and use alternate arenas, even with
  310. @c -DPER_THREAD (enabled by default), but supporting interruption
  311. @c (cancellation or signal handling) while holding the arena list mutex
  312. @c would require more work; maybe blocking signals and disabling async
  313. @c cancellation while manipulating the arena lists?
  314. @c __libc_malloc @asulock @aculock @acsfd @acsmem
  315. @c force_reg ok
  316. @c *malloc_hook unguarded
  317. @c arena_lock @asulock @aculock @acsfd @acsmem
  318. @c mutex_lock @asulock @aculock
  319. @c arena_get2 @asulock @aculock @acsfd @acsmem
  320. @c get_free_list @asulock @aculock
  321. @c mutex_lock (list_lock) dup @asulock @aculock
  322. @c mutex_unlock (list_lock) dup @aculock
  323. @c mutex_lock (arena lock) dup @asulock @aculock [returns locked]
  324. @c __get_nprocs ext ok @acsfd
  325. @c NARENAS_FROM_NCORES ok
  326. @c atomic_compare_and_exchange_bool_acq ok
  327. @c _int_new_arena ok @asulock @aculock @acsmem
  328. @c new_heap ok @acsmem
  329. @c mmap ok @acsmem
  330. @c munmap ok @acsmem
  331. @c mprotect ok
  332. @c chunk2mem ok
  333. @c set_head ok
  334. @c tsd_setspecific dup ok
  335. @c mutex_init ok
  336. @c mutex_lock (just-created mutex) ok, returns locked
  337. @c mutex_lock (list_lock) dup @asulock @aculock
  338. @c atomic_write_barrier ok
  339. @c mutex_unlock (list_lock) @aculock
  340. @c atomic_fetch_add ok
  341. @c reused_arena @asulock @aculock
  342. @c reads&writes next_to_use and iterates over arena next without guards
  343. @c those are harmless as long as we don't drop arenas from the
  344. @c NEXT list, and we never do; when a thread terminates,
  345. @c __malloc_arena_thread_freeres prepends the arena to the free_list
  346. @c NEXT_FREE list, but NEXT is never modified, so it's safe!
  347. @c mutex_trylock (arena lock) @asulock @aculock
  348. @c mutex_lock (arena lock) dup @asulock @aculock
  349. @c tsd_setspecific dup ok
  350. @c _int_malloc @acsfd @acsmem
  351. @c checked_request2size ok
  352. @c REQUEST_OUT_OF_RANGE ok
  353. @c request2size ok
  354. @c get_max_fast ok
  355. @c fastbin_index ok
  356. @c fastbin ok
  357. @c atomic_compare_and_exhange_val_acq ok
  358. @c malloc_printerr dup @mtsenv
  359. @c if we get to it, we're toast already, undefined behavior must have
  360. @c been invoked before
  361. @c libc_message @mtsenv [no leaks with cancellation disabled]
  362. @c FATAL_PREPARE ok
  363. @c pthread_setcancelstate disable ok
  364. @c libc_secure_getenv @mtsenv
  365. @c getenv @mtsenv
  366. @c open_not_cancel_2 dup @acsfd
  367. @c strchrnul ok
  368. @c WRITEV_FOR_FATAL ok
  369. @c writev ok
  370. @c mmap ok @acsmem
  371. @c munmap ok @acsmem
  372. @c BEFORE_ABORT @acsfd
  373. @c backtrace ok
  374. @c write_not_cancel dup ok
  375. @c backtrace_symbols_fd @aculock
  376. @c open_not_cancel_2 dup @acsfd
  377. @c read_not_cancel dup ok
  378. @c close_not_cancel_no_status dup @acsfd
  379. @c abort ok
  380. @c itoa_word ok
  381. @c abort ok
  382. @c check_remalloced_chunk ok/disabled
  383. @c chunk2mem dup ok
  384. @c alloc_perturb ok
  385. @c in_smallbin_range ok
  386. @c smallbin_index ok
  387. @c bin_at ok
  388. @c last ok
  389. @c malloc_consolidate ok
  390. @c get_max_fast dup ok
  391. @c clear_fastchunks ok
  392. @c unsorted_chunks dup ok
  393. @c fastbin dup ok
  394. @c atomic_exchange_acquire ok
  395. @c check_inuse_chunk dup ok/disabled
  396. @c chunk_at_offset dup ok
  397. @c chunksize dup ok
  398. @c inuse_bit_at_offset dup ok
  399. @c unlink dup ok
  400. @c clear_inuse_bit_at_offset dup ok
  401. @c in_smallbin_range dup ok
  402. @c set_head dup ok
  403. @c malloc_init_state ok
  404. @c bin_at dup ok
  405. @c set_noncontiguous dup ok
  406. @c set_max_fast dup ok
  407. @c initial_top ok
  408. @c unsorted_chunks dup ok
  409. @c check_malloc_state ok/disabled
  410. @c set_inuse_bit_at_offset ok
  411. @c check_malloced_chunk ok/disabled
  412. @c largebin_index ok
  413. @c have_fastchunks ok
  414. @c unsorted_chunks ok
  415. @c bin_at ok
  416. @c chunksize ok
  417. @c chunk_at_offset ok
  418. @c set_head ok
  419. @c set_foot ok
  420. @c mark_bin ok
  421. @c idx2bit ok
  422. @c first ok
  423. @c unlink ok
  424. @c malloc_printerr dup ok
  425. @c in_smallbin_range dup ok
  426. @c idx2block ok
  427. @c idx2bit dup ok
  428. @c next_bin ok
  429. @c sysmalloc @acsfd @acsmem
  430. @c MMAP @acsmem
  431. @c set_head dup ok
  432. @c check_chunk ok/disabled
  433. @c chunk2mem dup ok
  434. @c chunksize dup ok
  435. @c chunk_at_offset dup ok
  436. @c heap_for_ptr ok
  437. @c grow_heap ok
  438. @c mprotect ok
  439. @c set_head dup ok
  440. @c new_heap @acsmem
  441. @c MMAP dup @acsmem
  442. @c munmap @acsmem
  443. @c top ok
  444. @c set_foot dup ok
  445. @c contiguous ok
  446. @c MORECORE ok
  447. @c *__morecore ok unguarded
  448. @c __default_morecore
  449. @c sbrk ok
  450. @c force_reg dup ok
  451. @c *__after_morecore_hook unguarded
  452. @c set_noncontiguous ok
  453. @c malloc_printerr dup ok
  454. @c _int_free (have_lock) @acsfd @acsmem [@asulock @aculock]
  455. @c chunksize dup ok
  456. @c mutex_unlock dup @aculock/!have_lock
  457. @c malloc_printerr dup ok
  458. @c check_inuse_chunk ok/disabled
  459. @c chunk_at_offset dup ok
  460. @c mutex_lock dup @asulock @aculock/@have_lock
  461. @c chunk2mem dup ok
  462. @c free_perturb ok
  463. @c set_fastchunks ok
  464. @c fastbin_index dup ok
  465. @c fastbin dup ok
  466. @c atomic_compare_and_exchange_val_rel ok
  467. @c chunk_is_mmapped ok
  468. @c contiguous dup ok
  469. @c prev_inuse ok
  470. @c unlink dup ok
  471. @c inuse_bit_at_offset dup ok
  472. @c clear_inuse_bit_at_offset ok
  473. @c unsorted_chunks dup ok
  474. @c in_smallbin_range dup ok
  475. @c set_head dup ok
  476. @c set_foot dup ok
  477. @c check_free_chunk ok/disabled
  478. @c check_chunk dup ok/disabled
  479. @c have_fastchunks dup ok
  480. @c malloc_consolidate dup ok
  481. @c systrim ok
  482. @c MORECORE dup ok
  483. @c *__after_morecore_hook dup unguarded
  484. @c set_head dup ok
  485. @c check_malloc_state ok/disabled
  486. @c top dup ok
  487. @c heap_for_ptr dup ok
  488. @c heap_trim @acsfd @acsmem
  489. @c top dup ok
  490. @c chunk_at_offset dup ok
  491. @c prev_chunk ok
  492. @c chunksize dup ok
  493. @c prev_inuse dup ok
  494. @c delete_heap @acsmem
  495. @c munmap dup @acsmem
  496. @c unlink dup ok
  497. @c set_head dup ok
  498. @c shrink_heap @acsfd
  499. @c check_may_shrink_heap @acsfd
  500. @c open_not_cancel_2 @acsfd
  501. @c read_not_cancel ok
  502. @c close_not_cancel_no_status @acsfd
  503. @c MMAP dup ok
  504. @c madvise ok
  505. @c munmap_chunk @acsmem
  506. @c chunksize dup ok
  507. @c chunk_is_mmapped dup ok
  508. @c chunk2mem dup ok
  509. @c malloc_printerr dup ok
  510. @c munmap dup @acsmem
  511. @c check_malloc_state ok/disabled
  512. @c arena_get_retry @asulock @aculock @acsfd @acsmem
  513. @c mutex_unlock dup @aculock
  514. @c mutex_lock dup @asulock @aculock
  515. @c arena_get2 dup @asulock @aculock @acsfd @acsmem
  516. @c mutex_unlock @aculock
  517. @c mem2chunk ok
  518. @c chunk_is_mmapped ok
  519. @c arena_for_chunk ok
  520. @c chunk_non_main_arena ok
  521. @c heap_for_ptr ok
  522. This function returns a pointer to a newly allocated block @var{size}
  523. bytes long, or a null pointer (setting @code{errno})
  524. if the block could not be allocated.
  525. @end deftypefun
  526. The contents of the block are undefined; you must initialize it yourself
  527. (or use @code{calloc} instead; @pxref{Allocating Cleared Space}).
  528. Normally you would convert the value to a pointer to the kind of object
  529. that you want to store in the block. Here we show an example of doing
  530. so, and of initializing the space with zeros using the library function
  531. @code{memset} (@pxref{Copying Strings and Arrays}):
  532. @smallexample
  533. struct foo *ptr = malloc (sizeof *ptr);
  534. if (ptr == 0) abort ();
  535. memset (ptr, 0, sizeof (struct foo));
  536. @end smallexample
  537. You can store the result of @code{malloc} into any pointer variable
  538. without a cast, because @w{ISO C} automatically converts the type
  539. @code{void *} to another type of pointer when necessary. However, a cast
  540. is necessary if the type is needed but not specified by context.
  541. Remember that when allocating space for a string, the argument to
  542. @code{malloc} must be one plus the length of the string. This is
  543. because a string is terminated with a null character that doesn't count
  544. in the ``length'' of the string but does need space. For example:
  545. @smallexample
  546. char *ptr = malloc (length + 1);
  547. @end smallexample
  548. @noindent
  549. @xref{Representation of Strings}, for more information about this.
  550. @node Malloc Examples
  551. @subsubsection Examples of @code{malloc}
  552. If no more space is available, @code{malloc} returns a null pointer.
  553. You should check the value of @emph{every} call to @code{malloc}. It is
  554. useful to write a subroutine that calls @code{malloc} and reports an
  555. error if the value is a null pointer, returning only if the value is
  556. nonzero. This function is conventionally called @code{xmalloc}. Here
  557. it is:
  558. @cindex @code{xmalloc} function
  559. @smallexample
  560. void *
  561. xmalloc (size_t size)
  562. @{
  563. void *value = malloc (size);
  564. if (value == 0)
  565. fatal ("virtual memory exhausted");
  566. return value;
  567. @}
  568. @end smallexample
  569. Here is a real example of using @code{malloc} (by way of @code{xmalloc}).
  570. The function @code{savestring} will copy a sequence of characters into
  571. a newly allocated null-terminated string:
  572. @smallexample
  573. @group
  574. char *
  575. savestring (const char *ptr, size_t len)
  576. @{
  577. char *value = xmalloc (len + 1);
  578. value[len] = '\0';
  579. return memcpy (value, ptr, len);
  580. @}
  581. @end group
  582. @end smallexample
  583. The block that @code{malloc} gives you is guaranteed to be aligned so
  584. that it can hold any type of data. On @gnusystems{}, the address is
  585. always a multiple of eight on 32-bit systems, and a multiple of 16 on
  586. 64-bit systems. Only rarely is any higher boundary (such as a page
  587. boundary) necessary; for those cases, use @code{aligned_alloc} or
  588. @code{posix_memalign} (@pxref{Aligned Memory Blocks}).
  589. Note that the memory located after the end of the block is likely to be
  590. in use for something else; perhaps a block already allocated by another
  591. call to @code{malloc}. If you attempt to treat the block as longer than
  592. you asked for it to be, you are liable to destroy the data that
  593. @code{malloc} uses to keep track of its blocks, or you may destroy the
  594. contents of another block. If you have already allocated a block and
  595. discover you want it to be bigger, use @code{realloc} (@pxref{Changing
  596. Block Size}).
  597. @strong{Portability Notes:}
  598. @itemize @bullet
  599. @item
  600. In @theglibc{}, a successful @code{malloc (0)}
  601. returns a non-null pointer to a newly allocated size-zero block;
  602. other implementations may return @code{NULL} instead.
  603. POSIX and the ISO C standard allow both behaviors.
  604. @item
  605. In @theglibc{}, a failed @code{malloc} call sets @code{errno},
  606. but ISO C does not require this and non-POSIX implementations
  607. need not set @code{errno} when failing.
  608. @item
  609. In @theglibc{}, @code{malloc} always fails when @var{size} exceeds
  610. @code{PTRDIFF_MAX}, to avoid problems with programs that subtract
  611. pointers or use signed indexes. Other implementations may succeed in
  612. this case, leading to undefined behavior later.
  613. @end itemize
  614. @node Freeing after Malloc
  615. @subsubsection Freeing Memory Allocated with @code{malloc}
  616. @cindex freeing memory allocated with @code{malloc}
  617. @cindex heap, freeing memory from
  618. When you no longer need a block that you got with @code{malloc}, use the
  619. function @code{free} to make the block available to be allocated again.
  620. The prototype for this function is in @file{stdlib.h}.
  621. @pindex stdlib.h
  622. @deftypefun void free (void *@var{ptr})
  623. @standards{ISO, malloc.h}
  624. @standards{ISO, stdlib.h}
  625. @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
  626. @c __libc_free @asulock @aculock @acsfd @acsmem
  627. @c releasing memory into fastbins modifies the arena without taking
  628. @c its mutex, but atomic operations ensure safety. If two (or more)
  629. @c threads are running malloc and have their own arenas locked when
  630. @c each gets a signal whose handler free()s large (non-fastbin-able)
  631. @c blocks from each other's arena, we deadlock; this is a more general
  632. @c case of @asulock.
  633. @c *__free_hook unguarded
  634. @c mem2chunk ok
  635. @c chunk_is_mmapped ok, chunk bits not modified after allocation
  636. @c chunksize ok
  637. @c munmap_chunk dup @acsmem
  638. @c arena_for_chunk dup ok
  639. @c _int_free (!have_lock) dup @asulock @aculock @acsfd @acsmem
  640. The @code{free} function deallocates the block of memory pointed at
  641. by @var{ptr}.
  642. @end deftypefun
  643. Freeing a block alters the contents of the block. @strong{Do not expect to
  644. find any data (such as a pointer to the next block in a chain of blocks) in
  645. the block after freeing it.} Copy whatever you need out of the block before
  646. freeing it! Here is an example of the proper way to free all the blocks in
  647. a chain, and the strings that they point to:
  648. @smallexample
  649. struct chain
  650. @{
  651. struct chain *next;
  652. char *name;
  653. @}
  654. void
  655. free_chain (struct chain *chain)
  656. @{
  657. while (chain != 0)
  658. @{
  659. struct chain *next = chain->next;
  660. free (chain->name);
  661. free (chain);
  662. chain = next;
  663. @}
  664. @}
  665. @end smallexample
  666. Occasionally, @code{free} can actually return memory to the operating
  667. system and make the process smaller. Usually, all it can do is allow a
  668. later call to @code{malloc} to reuse the space. In the meantime, the
  669. space remains in your program as part of a free-list used internally by
  670. @code{malloc}.
  671. The @code{free} function preserves the value of @code{errno}, so that
  672. cleanup code need not worry about saving and restoring @code{errno}
  673. around a call to @code{free}. Although neither @w{ISO C} nor
  674. POSIX.1-2017 requires @code{free} to preserve @code{errno}, a future
  675. version of POSIX is planned to require it.
  676. There is no point in freeing blocks at the end of a program, because all
  677. of the program's space is given back to the system when the process
  678. terminates.
  679. @deftypefun void free_sized (void *@var{ptr}, size_t @var{size})
  680. @standards{ISO, stdlib.h}
  681. @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
  682. The @code{free_sized} function deallocates the block of memory pointed at
  683. by @var{ptr} that was previously allocated by @code{malloc}, @code{calloc}
  684. or @code{realloc}. The size @var{size} must match the previously requested
  685. total size provided to @code{malloc}, @code{calloc} or @code{realloc}.
  686. Attempting to deallocated memory allocated by @code{aligned_alloc},
  687. @code{memalign}, @code{posix_memalign}, @code{valloc} or @code{pvalloc} is
  688. undefined behavior. For @code{aligned_alloc}, @code{memalign} or
  689. @code{posix_memalign} use @code{free_aligned_sized} instead. Additionally
  690. it is also undefined behavior to call @code{free_sized} for allocations
  691. which the caller did not directly allocate but must still deallocate, such
  692. as the result of @code{strdup} or @code{strndup}. Instead continue using
  693. @code{free} for these cases.
  694. @end deftypefun
  695. @deftypefun void free_aligned_sized (void *@var{ptr}, size_t @var{alignment}, size_t @var{size})
  696. @standards{ISO, stdlib.h}
  697. @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
  698. The @code{free_aligned_sized} function deallocates the block of memory
  699. pointed at by @var{ptr} that was previously allocated by
  700. @code{aligned_alloc}, @code{memalign} or @code{posix_memalign}.
  701. The size @var{size} and alignment @var{alignment} must match the
  702. previously requested size and alignment provided to
  703. @code{aligned_alloc}, @code{memalign} or @code{posix_memalign}.
  704. @end deftypefun
  705. @node Changing Block Size
  706. @subsubsection Changing the Size of a Block
  707. @cindex changing the size of a block (@code{malloc})
  708. Often you do not know for certain how big a block you will ultimately need
  709. at the time you must begin to use the block. For example, the block might
  710. be a buffer that you use to hold a line being read from a file; no matter
  711. how long you make the buffer initially, you may encounter a line that is
  712. longer.
  713. You can make the block longer by calling @code{realloc} or
  714. @code{reallocarray}. These functions are declared in @file{stdlib.h}.
  715. @pindex stdlib.h
  716. @deftypefun {void *} realloc (void *@var{ptr}, size_t @var{newsize})
  717. @standards{ISO, malloc.h}
  718. @standards{ISO, stdlib.h}
  719. @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
  720. @c It may call the implementations of malloc and free, so all of their
  721. @c issues arise, plus the realloc hook, also accessed without guards.
  722. @c __libc_realloc @asulock @aculock @acsfd @acsmem
  723. @c *__realloc_hook unguarded
  724. @c __libc_free dup @asulock @aculock @acsfd @acsmem
  725. @c __libc_malloc dup @asulock @aculock @acsfd @acsmem
  726. @c mem2chunk dup ok
  727. @c chunksize dup ok
  728. @c malloc_printerr dup ok
  729. @c checked_request2size dup ok
  730. @c chunk_is_mmapped dup ok
  731. @c mremap_chunk
  732. @c chunksize dup ok
  733. @c __mremap ok
  734. @c set_head dup ok
  735. @c MALLOC_COPY ok
  736. @c memcpy ok
  737. @c munmap_chunk dup @acsmem
  738. @c arena_for_chunk dup ok
  739. @c mutex_lock (arena mutex) dup @asulock @aculock
  740. @c _int_realloc @acsfd @acsmem
  741. @c malloc_printerr dup ok
  742. @c check_inuse_chunk dup ok/disabled
  743. @c chunk_at_offset dup ok
  744. @c chunksize dup ok
  745. @c set_head_size dup ok
  746. @c chunk_at_offset dup ok
  747. @c set_head dup ok
  748. @c chunk2mem dup ok
  749. @c inuse dup ok
  750. @c unlink dup ok
  751. @c _int_malloc dup @acsfd @acsmem
  752. @c mem2chunk dup ok
  753. @c MALLOC_COPY dup ok
  754. @c _int_free (have_lock) dup @acsfd @acsmem
  755. @c set_inuse_bit_at_offset dup ok
  756. @c set_head dup ok
  757. @c mutex_unlock (arena mutex) dup @aculock
  758. @c _int_free (!have_lock) dup @asulock @aculock @acsfd @acsmem
  759. The @code{realloc} function changes the size of the block whose address is
  760. @var{ptr} to be @var{newsize}.
  761. Since the space after the end of the block may be in use, @code{realloc}
  762. may find it necessary to copy the block to a new address where more free
  763. space is available. The value of @code{realloc} is the new address of the
  764. block. If the block needs to be moved, @code{realloc} copies the old
  765. contents.
  766. If you pass a null pointer for @var{ptr}, @code{realloc} behaves just
  767. like @samp{malloc (@var{newsize})}.
  768. Otherwise, if @var{newsize} is zero
  769. @code{realloc} frees the block and returns @code{NULL}.
  770. Otherwise, if @code{realloc} cannot reallocate the requested size
  771. it returns @code{NULL} and sets @code{errno}; the original block
  772. is left undisturbed.
  773. @end deftypefun
  774. @deftypefun {void *} reallocarray (void *@var{ptr}, size_t @var{nmemb}, size_t @var{size})
  775. @standards{POSIX.1-2024, malloc.h}
  776. @standards{POSIX.1-2024, stdlib.h}
  777. @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
  778. The @code{reallocarray} function changes the size of the block whose address
  779. is @var{ptr} to be long enough to contain a vector of @var{nmemb} elements,
  780. each of size @var{size}. It is equivalent to @samp{realloc (@var{ptr},
  781. @var{nmemb} * @var{size})}, except that @code{reallocarray} fails safely if
  782. the multiplication overflows, by setting @code{errno} to @code{ENOMEM},
  783. returning a null pointer, and leaving the original block unchanged.
  784. @code{reallocarray} should be used instead of @code{realloc} when the new size
  785. of the allocated block is the result of a multiplication that might overflow.
  786. This function was originally derived from OpenBSD 5.6, but was added in
  787. POSIX.1-2024.
  788. @end deftypefun
  789. Like @code{malloc}, @code{realloc} and @code{reallocarray} may return a null
  790. pointer if no memory space is available to make the block bigger. When this
  791. happens, the original block is untouched; it has not been modified or
  792. relocated.
  793. In most cases it makes no difference what happens to the original block
  794. when @code{realloc} fails, because the application program cannot continue
  795. when it is out of memory, and the only thing to do is to give a fatal error
  796. message. Often it is convenient to write and use subroutines,
  797. conventionally called @code{xrealloc} and @code{xreallocarray},
  798. that take care of the error message
  799. as @code{xmalloc} does for @code{malloc}:
  800. @cindex @code{xrealloc} and @code{xreallocarray} functions
  801. @smallexample
  802. void *
  803. xreallocarray (void *ptr, size_t nmemb, size_t size)
  804. @{
  805. void *value = reallocarray (ptr, nmemb, size);
  806. if (value == 0)
  807. fatal ("Virtual memory exhausted");
  808. return value;
  809. @}
  810. void *
  811. xrealloc (void *ptr, size_t size)
  812. @{
  813. return xreallocarray (ptr, 1, size);
  814. @}
  815. @end smallexample
  816. You can also use @code{realloc} or @code{reallocarray} to make a block
  817. smaller. The reason you would do this is to avoid tying up a lot of memory
  818. space when only a little is needed.
  819. @comment The following is no longer true with the new malloc.
  820. @comment But it seems wise to keep the warning for other implementations.
  821. In several allocation implementations, making a block smaller sometimes
  822. necessitates copying it, so it can fail if no other space is available.
  823. @strong{Portability Notes:}
  824. @itemize @bullet
  825. @item
  826. Portable programs should not attempt to reallocate blocks to be size zero.
  827. On other implementations if @var{ptr} is non-null, @code{realloc (ptr, 0)}
  828. might free the block and return a non-null pointer to a size-zero
  829. object, or it might fail and return @code{NULL} without freeing the block.
  830. The ISO C17 standard allows these variations.
  831. @item
  832. In @theglibc{}, reallocation fails if the resulting block
  833. would exceed @code{PTRDIFF_MAX} in size, to avoid problems with programs
  834. that subtract pointers or use signed indexes. Other implementations may
  835. succeed, leading to undefined behavior later.
  836. @item
  837. In @theglibc{}, if the new size is the same as the old, @code{realloc} and
  838. @code{reallocarray} are guaranteed to change nothing and return the same
  839. address that you gave. However, POSIX and ISO C allow the functions
  840. to relocate the object or fail in this situation.
  841. @end itemize
  842. @node Allocating Cleared Space
  843. @subsubsection Allocating Cleared Space
  844. The function @code{calloc} allocates memory and clears it to zero. It
  845. is declared in @file{stdlib.h}.
  846. @pindex stdlib.h
  847. @deftypefun {void *} calloc (size_t @var{count}, size_t @var{eltsize})
  848. @standards{ISO, malloc.h}
  849. @standards{ISO, stdlib.h}
  850. @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
  851. @c Same caveats as malloc.
  852. @c __libc_calloc @asulock @aculock @acsfd @acsmem
  853. @c *__malloc_hook dup unguarded
  854. @c memset dup ok
  855. @c arena_get @asulock @aculock @acsfd @acsmem
  856. @c arena_lock dup @asulock @aculock @acsfd @acsmem
  857. @c top dup ok
  858. @c chunksize dup ok
  859. @c heap_for_ptr dup ok
  860. @c _int_malloc dup @acsfd @acsmem
  861. @c arena_get_retry dup @asulock @aculock @acsfd @acsmem
  862. @c mutex_unlock dup @aculock
  863. @c mem2chunk dup ok
  864. @c chunk_is_mmapped dup ok
  865. @c MALLOC_ZERO ok
  866. @c memset dup ok
  867. This function allocates a block long enough to contain a vector of
  868. @var{count} elements, each of size @var{eltsize}. Its contents are
  869. cleared to zero before @code{calloc} returns.
  870. @end deftypefun
  871. You could define @code{calloc} as follows:
  872. @smallexample
  873. void *
  874. calloc (size_t count, size_t eltsize)
  875. @{
  876. void *value = reallocarray (0, count, eltsize);
  877. if (value != 0)
  878. memset (value, 0, count * eltsize);
  879. return value;
  880. @}
  881. @end smallexample
  882. But in general, it is not guaranteed that @code{calloc} calls
  883. @code{reallocarray} and @code{memset} internally. For example, if the
  884. @code{calloc} implementation knows for other reasons that the new
  885. memory block is zero, it need not zero out the block again with
  886. @code{memset}. Also, if an application provides its own
  887. @code{reallocarray} outside the C library, @code{calloc} might not use
  888. that redefinition. @xref{Replacing malloc}.
  889. @node Aligned Memory Blocks
  890. @subsubsection Allocating Aligned Memory Blocks
  891. @cindex page boundary
  892. @cindex alignment (with @code{malloc})
  893. @pindex stdlib.h
  894. The address of a block returned by @code{malloc} or @code{realloc} in
  895. @gnusystems{} is always a multiple of eight (or sixteen on 64-bit
  896. systems). If you need a block whose address is a multiple of a higher
  897. power of two than that, use @code{aligned_alloc} or @code{posix_memalign}.
  898. @code{aligned_alloc} and @code{posix_memalign} are declared in
  899. @file{stdlib.h}.
  900. @deftypefun {void *} aligned_alloc (size_t @var{alignment}, size_t @var{size})
  901. @standards{???, stdlib.h}
  902. @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
  903. @c Alias to memalign.
  904. The @code{aligned_alloc} function allocates a block of @var{size} bytes whose
  905. address is a multiple of @var{alignment}. The @var{alignment} must be a
  906. power of two.
  907. The @code{aligned_alloc} function returns a null pointer on error and sets
  908. @code{errno} to one of the following values:
  909. @table @code
  910. @item ENOMEM
  911. There was insufficient memory available to satisfy the request.
  912. @item EINVAL
  913. @var{alignment} is not a power of two.
  914. This function was introduced in @w{ISO C11} and hence may have better
  915. portability to modern non-POSIX systems than @code{posix_memalign}.
  916. @end table
  917. @end deftypefun
  918. @deftypefun {void *} memalign (size_t @var{boundary}, size_t @var{size})
  919. @standards{BSD, malloc.h}
  920. @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
  921. @c Same issues as malloc. The padding bytes are safely freed in
  922. @c _int_memalign, with the arena still locked.
  923. @c __libc_memalign @asulock @aculock @acsfd @acsmem
  924. @c *__memalign_hook dup unguarded
  925. @c __libc_malloc dup @asulock @aculock @acsfd @acsmem
  926. @c arena_get dup @asulock @aculock @acsfd @acsmem
  927. @c _int_memalign @acsfd @acsmem
  928. @c _int_malloc dup @acsfd @acsmem
  929. @c checked_request2size dup ok
  930. @c mem2chunk dup ok
  931. @c chunksize dup ok
  932. @c chunk_is_mmapped dup ok
  933. @c set_head dup ok
  934. @c chunk2mem dup ok
  935. @c set_inuse_bit_at_offset dup ok
  936. @c set_head_size dup ok
  937. @c _int_free (have_lock) dup @acsfd @acsmem
  938. @c chunk_at_offset dup ok
  939. @c check_inuse_chunk dup ok
  940. @c arena_get_retry dup @asulock @aculock @acsfd @acsmem
  941. @c mutex_unlock dup @aculock
  942. The @code{memalign} function allocates a block of @var{size} bytes whose
  943. address is a multiple of @var{boundary}. The @var{boundary} must be a
  944. power of two! The function @code{memalign} works by allocating a
  945. somewhat larger block, and then returning an address within the block
  946. that is on the specified boundary.
  947. The @code{memalign} function returns a null pointer on error and sets
  948. @code{errno} to one of the following values:
  949. @table @code
  950. @item ENOMEM
  951. There was insufficient memory available to satisfy the request.
  952. @item EINVAL
  953. @var{boundary} is not a power of two.
  954. @end table
  955. The @code{memalign} function is obsolete and @code{aligned_alloc} or
  956. @code{posix_memalign} should be used instead.
  957. @end deftypefun
  958. @deftypefun int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
  959. @standards{POSIX, stdlib.h}
  960. @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
  961. @c Calls memalign unless the requirements are not met (powerof2 macro is
  962. @c safe given an automatic variable as an argument) or there's a
  963. @c memalign hook (accessed unguarded, but safely).
  964. The @code{posix_memalign} function is similar to the @code{memalign}
  965. function in that it returns a buffer of @var{size} bytes aligned to a
  966. multiple of @var{alignment}. But it adds one requirement to the
  967. parameter @var{alignment}: the value must be a power of two multiple of
  968. @code{sizeof (void *)}.
  969. If the function succeeds in allocation memory a pointer to the allocated
  970. memory is returned in @code{*@var{memptr}} and the return value is zero.
  971. Otherwise the function returns an error value indicating the problem.
  972. The possible error values returned are:
  973. @table @code
  974. @item ENOMEM
  975. There was insufficient memory available to satisfy the request.
  976. @item EINVAL
  977. @var{alignment} is not a power of two multiple of @code{sizeof (void *)}.
  978. @end table
  979. This function was introduced in POSIX 1003.1d. Although this function is
  980. superseded by @code{aligned_alloc}, it is more portable to older POSIX
  981. systems that do not support @w{ISO C11}.
  982. @end deftypefun
  983. @deftypefun {void *} valloc (size_t @var{size})
  984. @standards{BSD, malloc.h}
  985. @standards{BSD, stdlib.h}
  986. @safety{@prelim{}@mtunsafe{@mtuinit{}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{} @acsfd{} @acsmem{}}}
  987. @c __libc_valloc @mtuinit @asuinit @asulock @aculock @acsfd @acsmem
  988. @c ptmalloc_init (once) @mtsenv @asulock @aculock @acsfd @acsmem
  989. @c _dl_addr @asucorrupt? @aculock
  990. @c __rtld_lock_lock_recursive (dl_load_lock) @asucorrupt? @aculock
  991. @c _dl_find_dso_for_object ok, iterates over dl_ns and its _ns_loaded objs
  992. @c the ok above assumes no partial updates on dl_ns and _ns_loaded
  993. @c that could confuse a _dl_addr call in a signal handler
  994. @c _dl_addr_inside_object ok
  995. @c determine_info ok
  996. @c __rtld_lock_unlock_recursive (dl_load_lock) @aculock
  997. @c *_environ @mtsenv
  998. @c next_env_entry ok
  999. @c strcspn dup ok
  1000. @c __libc_mallopt dup @mtasuconst:mallopt [setting mp_]
  1001. @c *__malloc_initialize_hook unguarded, ok
  1002. @c *__memalign_hook dup ok, unguarded
  1003. @c arena_get dup @asulock @aculock @acsfd @acsmem
  1004. @c _int_valloc @acsfd @acsmem
  1005. @c malloc_consolidate dup ok
  1006. @c _int_memalign dup @acsfd @acsmem
  1007. @c arena_get_retry dup @asulock @aculock @acsfd @acsmem
  1008. @c _int_memalign dup @acsfd @acsmem
  1009. @c mutex_unlock dup @aculock
  1010. Using @code{valloc} is like using @code{memalign} and passing the page size
  1011. as the value of the first argument. It is implemented like this:
  1012. @smallexample
  1013. void *
  1014. valloc (size_t size)
  1015. @{
  1016. return memalign (getpagesize (), size);
  1017. @}
  1018. @end smallexample
  1019. @ref{Query Memory Parameters} for more information about the memory
  1020. subsystem.
  1021. The @code{valloc} function is obsolete and @code{aligned_alloc} or
  1022. @code{posix_memalign} should be used instead.
  1023. @end deftypefun
  1024. You can determine the alignment of a pointer with the
  1025. @code{memalignment} function.
  1026. @deftypefun size_t memalignment (void *@var{p})
  1027. @standards{C23, stdlib.h}
  1028. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1029. This function, defined in C23, returns the alignment of @var{p}, as a
  1030. power of two. If @var{p} is a null pointer, it returns zero. C23
  1031. requires @var{p} to be a valid pointer to an object or a null pointer;
  1032. as a GNU extension, @theglibc{} supports this function on arbitrary
  1033. bit patterns of pointer type.
  1034. This function was added to the C23 standard to support unconventional
  1035. platforms where a pointer's low-order bits are unrelated to alignment.
  1036. For conventional platforms, one can instead cast the pointer to
  1037. @code{uintptr_t} and then test the low order bits:
  1038. this is portable to pre-C23 and is typically a bit faster.
  1039. For example, if you want to read an @code{int}
  1040. addressed by possibly-misaligned pointer @code{p},
  1041. the following pre-C23 code works on all conventional platforms:
  1042. @smallexample
  1043. int i;
  1044. if (((uintptr_t) p & (alignof (int) - 1)) != 0)
  1045. memcpy (&i, p, sizeof i);
  1046. else
  1047. i = *p;
  1048. @end smallexample
  1049. However, it might not work on unconventional platforms, where one
  1050. would need something like the following C23 code:
  1051. @smallexample
  1052. int i;
  1053. if (memalignment (p) < alignof (int))
  1054. memcpy (&i, p, sizeof i);
  1055. else
  1056. i = *p;
  1057. @end smallexample
  1058. However, for this particular case, performance does not improve if
  1059. different code is used for aligned and unaligned pointers,
  1060. and the following code is preferable:
  1061. @smallexample
  1062. int i;
  1063. memcpy (&i, p, sizeof i);
  1064. @end smallexample
  1065. The compiler will generate the most efficient way to access unaligned
  1066. data for the architecture, optimizing away the @code{memcpy} call.
  1067. @end deftypefun
  1068. @node Malloc Tunable Parameters
  1069. @subsubsection Malloc Tunable Parameters
  1070. You can adjust some parameters for dynamic memory allocation with the
  1071. @code{mallopt} function. This function is the general SVID/XPG
  1072. interface, defined in @file{malloc.h}.
  1073. @pindex malloc.h
  1074. @deftypefun int mallopt (int @var{param}, int @var{value})
  1075. @safety{@prelim{}@mtunsafe{@mtuinit{} @mtasuconst{:mallopt}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{}}}
  1076. @c __libc_mallopt @mtuinit @mtasuconst:mallopt @asuinit @asulock @aculock
  1077. @c ptmalloc_init (once) dup @mtsenv @asulock @aculock @acsfd @acsmem
  1078. @c mutex_lock (main_arena->mutex) @asulock @aculock
  1079. @c malloc_consolidate dup ok
  1080. @c set_max_fast ok
  1081. @c mutex_unlock dup @aculock
  1082. When calling @code{mallopt}, the @var{param} argument specifies the
  1083. parameter to be set, and @var{value} the new value to be set. Possible
  1084. choices for @var{param}, as defined in @file{malloc.h}, are:
  1085. @vtable @code
  1086. @item M_MMAP_MAX
  1087. The maximum number of chunks to allocate with @code{mmap}. Setting this
  1088. to zero disables all use of @code{mmap}.
  1089. The default value of this parameter is @code{65536}.
  1090. This parameter can also be set for the process at startup by setting the
  1091. environment variable @env{MALLOC_MMAP_MAX_} to the desired value.
  1092. @item M_MMAP_THRESHOLD
  1093. All chunks larger than this value are allocated outside the normal
  1094. heap, using the @code{mmap} system call. This way it is guaranteed
  1095. that the memory for these chunks can be returned to the system on
  1096. @code{free}. Note that requests smaller than this threshold might still
  1097. be allocated via @code{mmap}.
  1098. If this parameter is not set, the default value is set as 128 KiB and the
  1099. threshold is adjusted dynamically to suit the allocation patterns of the
  1100. program. If the parameter is set, the dynamic adjustment is disabled and the
  1101. value is set statically to the input value.
  1102. This parameter can also be set for the process at startup by setting the
  1103. environment variable @env{MALLOC_MMAP_THRESHOLD_} to the desired value.
  1104. @comment TODO: @item M_MXFAST
  1105. @item M_PERTURB
  1106. If non-zero, memory blocks are filled with values depending on some
  1107. low order bits of this parameter when they are allocated (except when
  1108. allocated by @code{calloc}) and freed. This can be used to debug the
  1109. use of uninitialized or freed heap memory. Note that this option does not
  1110. guarantee that the freed block will have any specific values. It only
  1111. guarantees that the content the block had before it was freed will be
  1112. overwritten.
  1113. The default value of this parameter is @code{0}.
  1114. This parameter can also be set for the process at startup by setting the
  1115. environment variable @env{MALLOC_PERTURB_} to the desired value.
  1116. @item M_TOP_PAD
  1117. This parameter determines the amount of extra memory to obtain from the system
  1118. when an arena needs to be extended. It also specifies the number of bytes to
  1119. retain when shrinking an arena. This provides the necessary hysteresis in heap
  1120. size such that excessive amounts of system calls can be avoided.
  1121. The default value of this parameter is @code{0}.
  1122. This parameter can also be set for the process at startup by setting the
  1123. environment variable @env{MALLOC_TOP_PAD_} to the desired value.
  1124. @item M_TRIM_THRESHOLD
  1125. This is the minimum size (in bytes) of the top-most, releasable chunk
  1126. that will trigger a system call in order to return memory to the system.
  1127. If this parameter is not set, the default value is set as 128 KiB and the
  1128. threshold is adjusted dynamically to suit the allocation patterns of the
  1129. program. If the parameter is set, the dynamic adjustment is disabled and the
  1130. value is set statically to the provided input.
  1131. This parameter can also be set for the process at startup by setting the
  1132. environment variable @env{MALLOC_TRIM_THRESHOLD_} to the desired value.
  1133. @item M_ARENA_TEST
  1134. This parameter specifies the number of arenas that can be created before the
  1135. test on the limit to the number of arenas is conducted. The value is ignored if
  1136. @code{M_ARENA_MAX} is set.
  1137. The default value of this parameter is 2 on 32-bit systems and 8 on 64-bit
  1138. systems.
  1139. This parameter can also be set for the process at startup by setting the
  1140. environment variable @env{MALLOC_ARENA_TEST} to the desired value.
  1141. @item M_ARENA_MAX
  1142. This parameter sets the number of arenas to use regardless of the number of
  1143. cores in the system.
  1144. The default value of this tunable is @code{0}, meaning that the limit on the
  1145. number of arenas is determined by the number of CPU cores online. For 32-bit
  1146. systems the limit is twice the number of cores online and on 64-bit systems, it
  1147. is eight times the number of cores online. Note that the default value is not
  1148. derived from the default value of M_ARENA_TEST and is computed independently.
  1149. This parameter can also be set for the process at startup by setting the
  1150. environment variable @env{MALLOC_ARENA_MAX} to the desired value.
  1151. @end vtable
  1152. @end deftypefun
  1153. @node Heap Consistency Checking
  1154. @subsubsection Heap Consistency Checking
  1155. @cindex heap consistency checking
  1156. @cindex consistency checking, of heap
  1157. You can ask @code{malloc} to check the consistency of dynamic memory by
  1158. using the @code{mcheck} function and preloading the malloc debug library
  1159. @file{libc_malloc_debug} using the @var{LD_PRELOAD} environment variable.
  1160. This function is a GNU extension, declared in @file{mcheck.h}.
  1161. @pindex mcheck.h
  1162. @deftypefun int mcheck (void (*@var{abortfn}) (enum mcheck_status @var{status}))
  1163. @standards{GNU, mcheck.h}
  1164. @safety{@prelim{}@mtunsafe{@mtasurace{:mcheck} @mtasuconst{:malloc_hooks}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  1165. @c The hooks must be set up before malloc is first used, which sort of
  1166. @c implies @mtuinit/@asuinit but since the function is a no-op if malloc
  1167. @c was already used, that doesn't pose any safety issues. The actual
  1168. @c problem is with the hooks, designed for single-threaded
  1169. @c fully-synchronous operation: they manage an unguarded linked list of
  1170. @c allocated blocks, and get temporarily overwritten before calling the
  1171. @c allocation functions recursively while holding the old hooks. There
  1172. @c are no guards for thread safety, and inconsistent hooks may be found
  1173. @c within signal handlers or left behind in case of cancellation.
  1174. Calling @code{mcheck} tells @code{malloc} to perform occasional
  1175. consistency checks. These will catch things such as writing
  1176. past the end of a block that was allocated with @code{malloc}.
  1177. The @var{abortfn} argument is the function to call when an inconsistency
  1178. is found. If you supply a null pointer, then @code{mcheck} uses a
  1179. default function which prints a message and calls @code{abort}
  1180. (@pxref{Aborting a Program}). The function you supply is called with
  1181. one argument, which says what sort of inconsistency was detected; its
  1182. type is described below.
  1183. It is too late to begin allocation checking once you have allocated
  1184. anything with @code{malloc}. So @code{mcheck} does nothing in that
  1185. case. The function returns @code{-1} if you call it too late, and
  1186. @code{0} otherwise (when it is successful).
  1187. The easiest way to arrange to call @code{mcheck} early enough is to use
  1188. the option @samp{-lmcheck} when you link your program; then you don't
  1189. need to modify your program source at all. Alternatively you might use
  1190. a debugger to insert a call to @code{mcheck} whenever the program is
  1191. started, for example these gdb commands will automatically call @code{mcheck}
  1192. whenever the program starts:
  1193. @smallexample
  1194. (gdb) break main
  1195. Breakpoint 1, main (argc=2, argv=0xbffff964) at whatever.c:10
  1196. (gdb) command 1
  1197. Type commands for when breakpoint 1 is hit, one per line.
  1198. End with a line saying just "end".
  1199. >call mcheck(0)
  1200. >continue
  1201. >end
  1202. (gdb) @dots{}
  1203. @end smallexample
  1204. This will however only work if no initialization function of any object
  1205. involved calls any of the @code{malloc} functions since @code{mcheck}
  1206. must be called before the first such function.
  1207. @end deftypefun
  1208. @deftypefun {enum mcheck_status} mprobe (void *@var{pointer})
  1209. @safety{@prelim{}@mtunsafe{@mtasurace{:mcheck} @mtasuconst{:malloc_hooks}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  1210. @c The linked list of headers may be modified concurrently by other
  1211. @c threads, and it may find a partial update if called from a signal
  1212. @c handler. It's mostly read only, so cancelling it might be safe, but
  1213. @c it will modify global state that, if cancellation hits at just the
  1214. @c right spot, may be left behind inconsistent. This path is only taken
  1215. @c if checkhdr finds an inconsistency. If the inconsistency could only
  1216. @c occur because of earlier undefined behavior, that wouldn't be an
  1217. @c additional safety issue problem, but because of the other concurrency
  1218. @c issues in the mcheck hooks, the apparent inconsistency could be the
  1219. @c result of mcheck's own internal data race. So, AC-Unsafe it is.
  1220. The @code{mprobe} function lets you explicitly check for inconsistencies
  1221. in a particular allocated block. You must have already called
  1222. @code{mcheck} at the beginning of the program, to do its occasional
  1223. checks; calling @code{mprobe} requests an additional consistency check
  1224. to be done at the time of the call.
  1225. The argument @var{pointer} must be a pointer returned by @code{malloc}
  1226. or @code{realloc}. @code{mprobe} returns a value that says what
  1227. inconsistency, if any, was found. The values are described below.
  1228. @end deftypefun
  1229. @deftp {Data Type} {enum mcheck_status}
  1230. This enumerated type describes what kind of inconsistency was detected
  1231. in an allocated block, if any. Here are the possible values:
  1232. @table @code
  1233. @item MCHECK_DISABLED
  1234. @code{mcheck} was not called before the first allocation.
  1235. No consistency checking can be done.
  1236. @item MCHECK_OK
  1237. No inconsistency detected.
  1238. @item MCHECK_HEAD
  1239. The data immediately before the block was modified.
  1240. This commonly happens when an array index or pointer
  1241. is decremented too far.
  1242. @item MCHECK_TAIL
  1243. The data immediately after the block was modified.
  1244. This commonly happens when an array index or pointer
  1245. is incremented too far.
  1246. @item MCHECK_FREE
  1247. The block was already freed.
  1248. @end table
  1249. @end deftp
  1250. Another possibility to check for and guard against bugs in the use of
  1251. @code{malloc}, @code{realloc} and @code{free} is to set the environment
  1252. variable @code{MALLOC_CHECK_}. When @code{MALLOC_CHECK_} is set to a
  1253. non-zero value less than 4, a special (less efficient) implementation is
  1254. used which is designed to be tolerant against simple errors, such as
  1255. double calls of @code{free} with the same argument, or overruns of a
  1256. single byte (off-by-one bugs). Not all such errors can be protected
  1257. against, however, and memory leaks can result. Like in the case of
  1258. @code{mcheck}, one would need to preload the @file{libc_malloc_debug}
  1259. library to enable @code{MALLOC_CHECK_} functionality. Without this
  1260. preloaded library, setting @code{MALLOC_CHECK_} will have no effect.
  1261. Any detected heap corruption results in immediate termination of the
  1262. process.
  1263. There is one problem with @code{MALLOC_CHECK_}: in SUID or SGID binaries
  1264. it could possibly be exploited since diverging from the normal programs
  1265. behavior it now writes something to the standard error descriptor.
  1266. Therefore the use of @code{MALLOC_CHECK_} is disabled by default for
  1267. SUID and SGID binaries.
  1268. So, what's the difference between using @code{MALLOC_CHECK_} and linking
  1269. with @samp{-lmcheck}? @code{MALLOC_CHECK_} is orthogonal with respect to
  1270. @samp{-lmcheck}. @samp{-lmcheck} has been added for backward
  1271. compatibility. Both @code{MALLOC_CHECK_} and @samp{-lmcheck} should
  1272. uncover the same bugs - but using @code{MALLOC_CHECK_} you don't need to
  1273. recompile your application.
  1274. @c __morecore, __after_morecore_hook are undocumented
  1275. @c It's not clear whether to document them.
  1276. @node Statistics of Malloc
  1277. @subsubsection Statistics for Memory Allocation with @code{malloc}
  1278. @cindex allocation statistics
  1279. You can get information about dynamic memory allocation by calling the
  1280. @code{mallinfo2} function. This function and its associated data type
  1281. are declared in @file{malloc.h}; they are an extension of the standard
  1282. SVID/XPG version.
  1283. @pindex malloc.h
  1284. @deftp {Data Type} {struct mallinfo2}
  1285. @standards{GNU, malloc.h}
  1286. This structure type is used to return information about the dynamic
  1287. memory allocator. It contains the following members:
  1288. @table @code
  1289. @item size_t arena
  1290. This is the total size of memory allocated with @code{sbrk} by
  1291. @code{malloc}, in bytes.
  1292. @item size_t ordblks
  1293. This is the number of chunks not in use. (The memory allocator
  1294. internally gets chunks of memory from the operating system, and then
  1295. carves them up to satisfy individual @code{malloc} requests;
  1296. @pxref{The GNU Allocator}.)
  1297. @item size_t smblks
  1298. This field is unused.
  1299. @item size_t hblks
  1300. This is the total number of chunks allocated with @code{mmap}.
  1301. @item size_t hblkhd
  1302. This is the total size of memory allocated with @code{mmap}, in bytes.
  1303. @item size_t usmblks
  1304. This field is unused and always 0.
  1305. @item size_t fsmblks
  1306. This field is unused.
  1307. @item size_t uordblks
  1308. This is the total size of memory occupied by chunks handed out by
  1309. @code{malloc}.
  1310. @item size_t fordblks
  1311. This is the total size of memory occupied by free (not in use) chunks.
  1312. @item size_t keepcost
  1313. This is the size of the top-most releasable chunk that normally
  1314. borders the end of the heap (i.e., the high end of the virtual address
  1315. space's data segment).
  1316. @end table
  1317. @end deftp
  1318. @deftypefun {struct mallinfo2} mallinfo2 (void)
  1319. @standards{SVID, malloc.h}
  1320. @safety{@prelim{}@mtunsafe{@mtuinit{} @mtasuconst{:mallopt}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{}}}
  1321. @c Accessing mp_.n_mmaps and mp_.max_mmapped_mem, modified with atomics
  1322. @c but non-atomically elsewhere, may get us inconsistent results. We
  1323. @c mark the statistics as unsafe, rather than the fast-path functions
  1324. @c that collect the possibly inconsistent data.
  1325. @c __libc_mallinfo2 @mtuinit @mtasuconst:mallopt @asuinit @asulock @aculock
  1326. @c ptmalloc_init (once) dup @mtsenv @asulock @aculock @acsfd @acsmem
  1327. @c mutex_lock dup @asulock @aculock
  1328. @c int_mallinfo @mtasuconst:mallopt [mp_ access on main_arena]
  1329. @c malloc_consolidate dup ok
  1330. @c check_malloc_state dup ok/disabled
  1331. @c chunksize dup ok
  1332. @c fastbin dupo ok
  1333. @c bin_at dup ok
  1334. @c last dup ok
  1335. @c mutex_unlock @aculock
  1336. This function returns information about the current dynamic memory usage
  1337. in a structure of type @code{struct mallinfo2}.
  1338. @end deftypefun
  1339. @node Summary of Malloc
  1340. @subsubsection Summary of @code{malloc}-Related Functions
  1341. Here is a summary of the functions that work with @code{malloc}:
  1342. @table @code
  1343. @item void *malloc (size_t @var{size})
  1344. Allocate a block of @var{size} bytes. @xref{Basic Allocation}.
  1345. @item void free (void *@var{addr})
  1346. Free a block previously allocated by @code{malloc}. @xref{Freeing after
  1347. Malloc}.
  1348. @item void *realloc (void *@var{addr}, size_t @var{size})
  1349. Make a block previously allocated by @code{malloc} larger or smaller,
  1350. possibly by copying it to a new location. @xref{Changing Block Size}.
  1351. @item void *reallocarray (void *@var{ptr}, size_t @var{nmemb}, size_t @var{size})
  1352. Change the size of a block previously allocated by @code{malloc} to
  1353. @code{@var{nmemb} * @var{size}} bytes as with @code{realloc}. @xref{Changing
  1354. Block Size}.
  1355. @item void *calloc (size_t @var{count}, size_t @var{eltsize})
  1356. Allocate a block of @var{count} * @var{eltsize} bytes using
  1357. @code{malloc}, and set its contents to zero. @xref{Allocating Cleared
  1358. Space}.
  1359. @item void *valloc (size_t @var{size})
  1360. Allocate a block of @var{size} bytes, starting on a page boundary.
  1361. @xref{Aligned Memory Blocks}.
  1362. @item void *aligned_alloc (size_t @var{alignment}, size_t @var{size})
  1363. Allocate a block of @var{size} bytes, starting on an address that is a
  1364. multiple of @var{alignment}. @xref{Aligned Memory Blocks}.
  1365. @item int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
  1366. Allocate a block of @var{size} bytes, starting on an address that is a
  1367. multiple of @var{alignment}. @xref{Aligned Memory Blocks}.
  1368. @item void *memalign (size_t @var{boundary}, size_t @var{size})
  1369. Allocate a block of @var{size} bytes, starting on an address that is a
  1370. multiple of @var{boundary}. @xref{Aligned Memory Blocks}.
  1371. @item int mallopt (int @var{param}, int @var{value})
  1372. Adjust a tunable parameter. @xref{Malloc Tunable Parameters}.
  1373. @item int mcheck (void (*@var{abortfn}) (void))
  1374. Tell @code{malloc} to perform occasional consistency checks on
  1375. dynamically allocated memory, and to call @var{abortfn} when an
  1376. inconsistency is found. @xref{Heap Consistency Checking}.
  1377. @item struct mallinfo2 mallinfo2 (void)
  1378. Return information about the current dynamic memory usage.
  1379. @xref{Statistics of Malloc}.
  1380. @end table
  1381. @node Allocation Debugging
  1382. @subsection Allocation Debugging
  1383. @cindex allocation debugging
  1384. @cindex malloc debugger
  1385. A complicated task when programming with languages which do not use
  1386. garbage collected dynamic memory allocation is to find memory leaks.
  1387. Long running programs must ensure that dynamically allocated objects are
  1388. freed at the end of their lifetime. If this does not happen the system
  1389. runs out of memory, sooner or later.
  1390. The @code{malloc} implementation in @theglibc{} provides some
  1391. simple means to detect such leaks and obtain some information to find
  1392. the location. To do this the application must be started in a special
  1393. mode which is enabled by an environment variable. There are no speed
  1394. penalties for the program if the debugging mode is not enabled.
  1395. @menu
  1396. * Tracing malloc:: How to install the tracing functionality.
  1397. * Using the Memory Debugger:: Example programs excerpts.
  1398. * Tips for the Memory Debugger:: Some more or less clever ideas.
  1399. * Interpreting the traces:: What do all these lines mean?
  1400. @end menu
  1401. @node Tracing malloc
  1402. @subsubsection How to install the tracing functionality
  1403. @deftypefun void mtrace (void)
  1404. @standards{GNU, mcheck.h}
  1405. @safety{@prelim{}@mtunsafe{@mtsenv{} @mtasurace{:mtrace} @mtuinit{}}@asunsafe{@asuinit{} @ascuheap{} @asucorrupt{} @asulock{}}@acunsafe{@acuinit{} @acucorrupt{} @aculock{} @acsfd{} @acsmem{}}}
  1406. @c Like the mcheck hooks, these are not designed with thread safety in
  1407. @c mind, because the hook pointers are temporarily modified without
  1408. @c regard to other threads, signals or cancellation.
  1409. @c mtrace @mtuinit @mtasurace:mtrace @mtsenv @asuinit @ascuheap @asucorrupt @acuinit @acucorrupt @aculock @acsfd @acsmem
  1410. @c __libc_secure_getenv dup @mtsenv
  1411. @c malloc dup @ascuheap @acsmem
  1412. @c fopen dup @ascuheap @asulock @aculock @acsmem @acsfd
  1413. @c fcntl dup ok
  1414. @c setvbuf dup @aculock
  1415. @c fprintf dup (on newly-created stream) @aculock
  1416. @c __cxa_atexit (once) dup @asulock @aculock @acsmem
  1417. @c free dup @ascuheap @acsmem
  1418. The @code{mtrace} function provides a way to trace memory allocation
  1419. events in the program that calls it. It is disabled by default in the
  1420. library and can be enabled by preloading the debugging library
  1421. @file{libc_malloc_debug} using the @code{LD_PRELOAD} environment
  1422. variable.
  1423. When the @code{mtrace} function is called it looks for an environment
  1424. variable named @code{MALLOC_TRACE}. This variable is supposed to
  1425. contain a valid file name. The user must have write access. If the
  1426. file already exists it is truncated. If the environment variable is not
  1427. set or it does not name a valid file which can be opened for writing
  1428. nothing is done. The behavior of @code{malloc} etc. is not changed.
  1429. For obvious reasons this also happens if the application is installed
  1430. with the SUID or SGID bit set.
  1431. If the named file is successfully opened, @code{mtrace} installs special
  1432. handlers for the functions @code{malloc}, @code{realloc}, and
  1433. @code{free}. From then on, all uses of these functions are traced and
  1434. protocolled into the file. There is now of course a speed penalty for all
  1435. calls to the traced functions so tracing should not be enabled during normal
  1436. use.
  1437. This function is a GNU extension and generally not available on other
  1438. systems. The prototype can be found in @file{mcheck.h}.
  1439. @end deftypefun
  1440. @deftypefun void muntrace (void)
  1441. @standards{GNU, mcheck.h}
  1442. @safety{@prelim{}@mtunsafe{@mtasurace{:mtrace} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{} @aculock{} @acsfd{}}}
  1443. @c muntrace @mtasurace:mtrace @mtslocale @asucorrupt @ascuheap @acucorrupt @acsmem @aculock @acsfd
  1444. @c fprintf (fputs) dup @mtslocale @asucorrupt @ascuheap @acsmem @aculock @acucorrupt
  1445. @c fclose dup @ascuheap @asulock @aculock @acsmem @acsfd
  1446. The @code{muntrace} function can be called after @code{mtrace} was used
  1447. to enable tracing the @code{malloc} calls. If no (successful) call of
  1448. @code{mtrace} was made @code{muntrace} does nothing.
  1449. Otherwise it deinstalls the handlers for @code{malloc}, @code{realloc},
  1450. and @code{free} and then closes the protocol file. No calls are
  1451. protocolled anymore and the program runs again at full speed.
  1452. This function is a GNU extension and generally not available on other
  1453. systems. The prototype can be found in @file{mcheck.h}.
  1454. @end deftypefun
  1455. @node Using the Memory Debugger
  1456. @subsubsection Example program excerpts
  1457. Even though the tracing functionality does not influence the runtime
  1458. behavior of the program it is not a good idea to call @code{mtrace} in
  1459. all programs. Just imagine that you debug a program using @code{mtrace}
  1460. and all other programs used in the debugging session also trace their
  1461. @code{malloc} calls. The output file would be the same for all programs
  1462. and thus is unusable. Therefore one should call @code{mtrace} only if
  1463. compiled for debugging. A program could therefore start like this:
  1464. @example
  1465. #include <mcheck.h>
  1466. int
  1467. main (int argc, char *argv[])
  1468. @{
  1469. #ifdef DEBUGGING
  1470. mtrace ();
  1471. #endif
  1472. @dots{}
  1473. @}
  1474. @end example
  1475. This is all that is needed if you want to trace the calls during the
  1476. whole runtime of the program. Alternatively you can stop the tracing at
  1477. any time with a call to @code{muntrace}. It is even possible to restart
  1478. the tracing again with a new call to @code{mtrace}. But this can cause
  1479. unreliable results since there may be calls of the functions which are
  1480. not called. Please note that not only the application uses the traced
  1481. functions, also libraries (including the C library itself) use these
  1482. functions.
  1483. This last point is also why it is not a good idea to call @code{muntrace}
  1484. before the program terminates. The libraries are informed about the
  1485. termination of the program only after the program returns from
  1486. @code{main} or calls @code{exit} and so cannot free the memory they use
  1487. before this time.
  1488. So the best thing one can do is to call @code{mtrace} as the very first
  1489. function in the program and never call @code{muntrace}. So the program
  1490. traces almost all uses of the @code{malloc} functions (except those
  1491. calls which are executed by constructors of the program or used
  1492. libraries).
  1493. @node Tips for the Memory Debugger
  1494. @subsubsection Some more or less clever ideas
  1495. You know the situation. The program is prepared for debugging and in
  1496. all debugging sessions it runs well. But once it is started without
  1497. debugging the error shows up. A typical example is a memory leak that
  1498. becomes visible only when we turn off the debugging. If you foresee
  1499. such situations you can still win. Simply use something equivalent to
  1500. the following little program:
  1501. @example
  1502. #include <mcheck.h>
  1503. #include <signal.h>
  1504. static void
  1505. enable (int sig)
  1506. @{
  1507. mtrace ();
  1508. signal (SIGUSR1, enable);
  1509. @}
  1510. static void
  1511. disable (int sig)
  1512. @{
  1513. muntrace ();
  1514. signal (SIGUSR2, disable);
  1515. @}
  1516. int
  1517. main (int argc, char *argv[])
  1518. @{
  1519. @dots{}
  1520. signal (SIGUSR1, enable);
  1521. signal (SIGUSR2, disable);
  1522. @dots{}
  1523. @}
  1524. @end example
  1525. I.e., the user can start the memory debugger any time s/he wants if the
  1526. program was started with @code{MALLOC_TRACE} set in the environment.
  1527. The output will of course not show the allocations which happened before
  1528. the first signal but if there is a memory leak this will show up
  1529. nevertheless.
  1530. @node Interpreting the traces
  1531. @subsubsection Interpreting the traces
  1532. If you take a look at the output it will look similar to this:
  1533. @example
  1534. = Start
  1535. @ [0x8048209] - 0x8064cc8
  1536. @ [0x8048209] - 0x8064ce0
  1537. @ [0x8048209] - 0x8064cf8
  1538. @ [0x80481eb] + 0x8064c48 0x14
  1539. @ [0x80481eb] + 0x8064c60 0x14
  1540. @ [0x80481eb] + 0x8064c78 0x14
  1541. @ [0x80481eb] + 0x8064c90 0x14
  1542. = End
  1543. @end example
  1544. What this all means is not really important since the trace file is not
  1545. meant to be read by a human. Therefore no attention is given to
  1546. readability. Instead there is a program which comes with @theglibc{}
  1547. which interprets the traces and outputs a summary in an
  1548. user-friendly way. The program is called @code{mtrace} (it is in fact a
  1549. Perl script) and it takes one or two arguments. In any case the name of
  1550. the file with the trace output must be specified. If an optional
  1551. argument precedes the name of the trace file this must be the name of
  1552. the program which generated the trace.
  1553. @example
  1554. drepper$ mtrace tst-mtrace log
  1555. No memory leaks.
  1556. @end example
  1557. In this case the program @code{tst-mtrace} was run and it produced a
  1558. trace file @file{log}. The message printed by @code{mtrace} shows there
  1559. are no problems with the code, all allocated memory was freed
  1560. afterwards.
  1561. If we call @code{mtrace} on the example trace given above we would get a
  1562. different output:
  1563. @example
  1564. drepper$ mtrace errlog
  1565. - 0x08064cc8 Free 2 was never alloc'd 0x8048209
  1566. - 0x08064ce0 Free 3 was never alloc'd 0x8048209
  1567. - 0x08064cf8 Free 4 was never alloc'd 0x8048209
  1568. Memory not freed:
  1569. -----------------
  1570. Address Size Caller
  1571. 0x08064c48 0x14 at 0x80481eb
  1572. 0x08064c60 0x14 at 0x80481eb
  1573. 0x08064c78 0x14 at 0x80481eb
  1574. 0x08064c90 0x14 at 0x80481eb
  1575. @end example
  1576. We have called @code{mtrace} with only one argument and so the script
  1577. has no chance to find out what is meant with the addresses given in the
  1578. trace. We can do better:
  1579. @example
  1580. drepper$ mtrace tst errlog
  1581. - 0x08064cc8 Free 2 was never alloc'd /home/drepper/tst.c:39
  1582. - 0x08064ce0 Free 3 was never alloc'd /home/drepper/tst.c:39
  1583. - 0x08064cf8 Free 4 was never alloc'd /home/drepper/tst.c:39
  1584. Memory not freed:
  1585. -----------------
  1586. Address Size Caller
  1587. 0x08064c48 0x14 at /home/drepper/tst.c:33
  1588. 0x08064c60 0x14 at /home/drepper/tst.c:33
  1589. 0x08064c78 0x14 at /home/drepper/tst.c:33
  1590. 0x08064c90 0x14 at /home/drepper/tst.c:33
  1591. @end example
  1592. Suddenly the output makes much more sense and the user can see
  1593. immediately where the function calls causing the trouble can be found.
  1594. Interpreting this output is not complicated. There are at most two
  1595. different situations being detected. First, @code{free} was called for
  1596. pointers which were never returned by one of the allocation functions.
  1597. This is usually a very bad problem and what this looks like is shown in
  1598. the first three lines of the output. Situations like this are quite
  1599. rare and if they appear they show up very drastically: the program
  1600. normally crashes.
  1601. The other situation which is much harder to detect are memory leaks. As
  1602. you can see in the output the @code{mtrace} function collects all this
  1603. information and so can say that the program calls an allocation function
  1604. from line 33 in the source file @file{/home/drepper/tst-mtrace.c} four
  1605. times without freeing this memory before the program terminates.
  1606. Whether this is a real problem remains to be investigated.
  1607. @node Replacing malloc
  1608. @subsection Replacing @code{malloc}
  1609. @cindex @code{malloc} replacement
  1610. @cindex @code{LD_PRELOAD} and @code{malloc}
  1611. @cindex alternative @code{malloc} implementations
  1612. @cindex customizing @code{malloc}
  1613. @cindex interposing @code{malloc}
  1614. @cindex preempting @code{malloc}
  1615. @cindex replacing @code{malloc}
  1616. @Theglibc{} supports replacing the built-in @code{malloc} implementation
  1617. with a different allocator with the same interface. For dynamically
  1618. linked programs, this happens through ELF symbol interposition, either
  1619. using shared object dependencies or @code{LD_PRELOAD}. For static
  1620. linking, the @code{malloc} replacement library must be linked in before
  1621. linking against @code{libc.a} (explicitly or implicitly).
  1622. Care must be taken not to use functionality from @theglibc{} that uses
  1623. @code{malloc} internally. For example, the @code{fopen},
  1624. @code{opendir}, @code{dlopen}, and @code{pthread_setspecific} functions
  1625. currently use the @code{malloc} subsystem internally. If the
  1626. replacement @code{malloc} or its dependencies use thread-local storage
  1627. (TLS), it must use the initial-exec TLS model, and not one of the
  1628. dynamic TLS variants.
  1629. @strong{Note:} Failure to provide a complete set of replacement
  1630. functions (that is, all the functions used by the application,
  1631. @theglibc{}, and other linked-in libraries) can lead to static linking
  1632. failures, and, at run time, to heap corruption and application crashes.
  1633. Replacement functions should implement the behavior documented for
  1634. their counterparts in @theglibc{}; for example, the replacement
  1635. @code{free} should also preserve @code{errno}.
  1636. The minimum set of functions which has to be provided by a custom
  1637. @code{malloc} is given in the table below.
  1638. @table @code
  1639. @item malloc
  1640. @item free
  1641. @item calloc
  1642. @item realloc
  1643. @end table
  1644. These @code{malloc}-related functions are required for @theglibc{} to
  1645. work.@footnote{Versions of @theglibc{} before 2.25 required that a
  1646. custom @code{malloc} defines @code{__libc_memalign} (with the same
  1647. interface as the @code{memalign} function).}
  1648. The @code{malloc} implementation in @theglibc{} provides additional
  1649. functionality not used by the library itself, but which is often used by
  1650. other system libraries and applications. A general-purpose replacement
  1651. @code{malloc} implementation should provide definitions of these
  1652. functions, too. Their names are listed in the following table.
  1653. @table @code
  1654. @item aligned_alloc
  1655. @item free_aligned_sized
  1656. @item free_sized
  1657. @item malloc_usable_size
  1658. @item memalign
  1659. @item posix_memalign
  1660. @item pvalloc
  1661. @item valloc
  1662. @end table
  1663. In addition, very old applications may use the obsolete @code{cfree}
  1664. function.
  1665. Further @code{malloc}-related functions such as @code{mallopt} or
  1666. @code{mallinfo2} will not have any effect or return incorrect statistics
  1667. when a replacement @code{malloc} is in use. However, failure to replace
  1668. these functions typically does not result in crashes or other incorrect
  1669. application behavior, but may result in static linking failures.
  1670. There are other functions (@code{reallocarray}, @code{strdup}, etc.) in
  1671. @theglibc{} that are not listed above but return newly allocated memory to
  1672. callers. Replacement of these functions is not supported and may produce
  1673. incorrect results. @Theglibc{} implementations of these functions call
  1674. the replacement allocator functions whenever available, so they will work
  1675. correctly with @code{malloc} replacement.
  1676. @node Obstacks
  1677. @subsection Obstacks
  1678. @cindex obstacks
  1679. An @dfn{obstack} is a pool of memory containing a stack of objects. You
  1680. can create any number of separate obstacks, and then allocate objects in
  1681. specified obstacks. Within each obstack, the last object allocated must
  1682. always be the first one freed, but distinct obstacks are independent of
  1683. each other.
  1684. Aside from this one constraint of order of freeing, obstacks are totally
  1685. general: an obstack can contain any number of objects of any size. They
  1686. are implemented with macros, so allocation is usually very fast as long as
  1687. the objects are usually small. And the only space overhead per object is
  1688. the padding needed to start each object on a suitable boundary.
  1689. @menu
  1690. * Creating Obstacks:: How to declare an obstack in your program.
  1691. * Preparing for Obstacks:: Preparations needed before you can
  1692. use obstacks.
  1693. * Allocation in an Obstack:: Allocating objects in an obstack.
  1694. * Freeing Obstack Objects:: Freeing objects in an obstack.
  1695. * Obstack Functions:: The obstack functions are both
  1696. functions and macros.
  1697. * Growing Objects:: Making an object bigger by stages.
  1698. * Extra Fast Growing:: Extra-high-efficiency (though more
  1699. complicated) growing objects.
  1700. * Status of an Obstack:: Inquiries about the status of an obstack.
  1701. * Obstacks Data Alignment:: Controlling alignment of objects in obstacks.
  1702. * Obstack Chunks:: How obstacks obtain and release chunks;
  1703. efficiency considerations.
  1704. * Summary of Obstacks::
  1705. @end menu
  1706. @node Creating Obstacks
  1707. @subsubsection Creating Obstacks
  1708. The utilities for manipulating obstacks are declared in the header
  1709. file @file{obstack.h}.
  1710. @pindex obstack.h
  1711. @deftp {Data Type} {struct obstack}
  1712. @standards{GNU, obstack.h}
  1713. An obstack is represented by a data structure of type @code{struct
  1714. obstack}. This structure has a small fixed size; it records the status
  1715. of the obstack and how to find the space in which objects are allocated.
  1716. It does not contain any of the objects themselves. You should not try
  1717. to access the contents of the structure directly; use only the functions
  1718. described in this chapter.
  1719. @end deftp
  1720. You can declare variables of type @code{struct obstack} and use them as
  1721. obstacks, or you can allocate obstacks dynamically like any other kind
  1722. of object. Dynamic allocation of obstacks allows your program to have a
  1723. variable number of different stacks. (You can even allocate an
  1724. obstack structure in another obstack, but this is rarely useful.)
  1725. All the functions that work with obstacks require you to specify which
  1726. obstack to use. You do this with a pointer of type @code{struct obstack
  1727. *}. In the following, we often say ``an obstack'' when strictly
  1728. speaking the object at hand is such a pointer.
  1729. The objects in the obstack are packed into large blocks called
  1730. @dfn{chunks}. The @code{struct obstack} structure points to a chain of
  1731. the chunks currently in use.
  1732. The obstack library obtains a new chunk whenever you allocate an object
  1733. that won't fit in the previous chunk. Since the obstack library manages
  1734. chunks automatically, you don't need to pay much attention to them, but
  1735. you do need to supply a function which the obstack library should use to
  1736. get a chunk. Usually you supply a function which uses @code{malloc}
  1737. directly or indirectly. You must also supply a function to free a chunk.
  1738. These matters are described in the following section.
  1739. @node Preparing for Obstacks
  1740. @subsubsection Preparing for Using Obstacks
  1741. Each source file in which you plan to use the obstack functions
  1742. must include the header file @file{obstack.h}, like this:
  1743. @smallexample
  1744. #include <obstack.h>
  1745. @end smallexample
  1746. @findex obstack_chunk_alloc
  1747. @findex obstack_chunk_free
  1748. Also, if the source file uses the macro @code{obstack_init}, it must
  1749. declare or define two functions or macros that will be called by the
  1750. obstack library. One, @code{obstack_chunk_alloc}, is used to allocate
  1751. the chunks of memory into which objects are packed. The other,
  1752. @code{obstack_chunk_free}, is used to return chunks when the objects in
  1753. them are freed. These macros should appear before any use of obstacks
  1754. in the source file.
  1755. Usually these are defined to use @code{malloc} via the intermediary
  1756. @code{xmalloc} (@pxref{Unconstrained Allocation}). This is done with
  1757. the following pair of macro definitions:
  1758. @smallexample
  1759. #define obstack_chunk_alloc xmalloc
  1760. #define obstack_chunk_free free
  1761. @end smallexample
  1762. @noindent
  1763. Though the memory you get using obstacks really comes from @code{malloc},
  1764. using obstacks is faster because @code{malloc} is called less often, for
  1765. larger blocks of memory. @xref{Obstack Chunks}, for full details.
  1766. At run time, before the program can use a @code{struct obstack} object
  1767. as an obstack, it must initialize the obstack by calling
  1768. @code{obstack_init}.
  1769. @deftypefun int obstack_init (struct obstack *@var{obstack-ptr})
  1770. @standards{GNU, obstack.h}
  1771. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{@acsmem{}}}
  1772. @c obstack_init @mtsrace:obstack-ptr @acsmem
  1773. @c _obstack_begin @acsmem
  1774. @c chunkfun = obstack_chunk_alloc (suggested malloc)
  1775. @c freefun = obstack_chunk_free (suggested free)
  1776. @c *chunkfun @acsmem
  1777. @c obstack_chunk_alloc user-supplied
  1778. @c *obstack_alloc_failed_handler user-supplied
  1779. @c -> print_and_abort (default)
  1780. @c
  1781. @c print_and_abort
  1782. @c _ dup @ascuintl
  1783. @c fxprintf dup @asucorrupt @aculock @acucorrupt
  1784. @c exit @acucorrupt?
  1785. Initialize obstack @var{obstack-ptr} for allocation of objects. This
  1786. function calls the obstack's @code{obstack_chunk_alloc} function. If
  1787. allocation of memory fails, the function pointed to by
  1788. @code{obstack_alloc_failed_handler} is called. The @code{obstack_init}
  1789. function always returns 1 (Compatibility notice: Former versions of
  1790. obstack returned 0 if allocation failed).
  1791. @end deftypefun
  1792. Here are two examples of how to allocate the space for an obstack and
  1793. initialize it. First, an obstack that is a static variable:
  1794. @smallexample
  1795. static struct obstack myobstack;
  1796. @dots{}
  1797. obstack_init (&myobstack);
  1798. @end smallexample
  1799. @noindent
  1800. Second, an obstack that is itself dynamically allocated:
  1801. @smallexample
  1802. struct obstack *myobstack_ptr
  1803. = (struct obstack *) xmalloc (sizeof (struct obstack));
  1804. obstack_init (myobstack_ptr);
  1805. @end smallexample
  1806. @defvar obstack_alloc_failed_handler
  1807. @standards{GNU, obstack.h}
  1808. The value of this variable is a pointer to a function that
  1809. @code{obstack} uses when @code{obstack_chunk_alloc} fails to allocate
  1810. memory. The default action is to print a message and abort.
  1811. You should supply a function that either calls @code{exit}
  1812. (@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
  1813. Exits}) and doesn't return.
  1814. @smallexample
  1815. void my_obstack_alloc_failed (void)
  1816. @dots{}
  1817. obstack_alloc_failed_handler = &my_obstack_alloc_failed;
  1818. @end smallexample
  1819. @end defvar
  1820. @node Allocation in an Obstack
  1821. @subsubsection Allocation in an Obstack
  1822. @cindex allocation (obstacks)
  1823. The most direct way to allocate an object in an obstack is with
  1824. @code{obstack_alloc}, which is invoked almost like @code{malloc}.
  1825. @deftypefun {void *} obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
  1826. @standards{GNU, obstack.h}
  1827. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
  1828. @c obstack_alloc @mtsrace:obstack-ptr @acucorrupt @acsmem
  1829. @c obstack_blank dup @mtsrace:obstack-ptr @acucorrupt @acsmem
  1830. @c obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
  1831. This allocates an uninitialized block of @var{size} bytes in an obstack
  1832. and returns its address. Here @var{obstack-ptr} specifies which obstack
  1833. to allocate the block in; it is the address of the @code{struct obstack}
  1834. object which represents the obstack. Each obstack function or macro
  1835. requires you to specify an @var{obstack-ptr} as the first argument.
  1836. This function calls the obstack's @code{obstack_chunk_alloc} function if
  1837. it needs to allocate a new chunk of memory; it calls
  1838. @code{obstack_alloc_failed_handler} if allocation of memory by
  1839. @code{obstack_chunk_alloc} failed.
  1840. @end deftypefun
  1841. For example, here is a function that allocates a copy of a string @var{str}
  1842. in a specific obstack, which is in the variable @code{string_obstack}:
  1843. @smallexample
  1844. struct obstack string_obstack;
  1845. char *
  1846. copystring (char *string)
  1847. @{
  1848. size_t len = strlen (string) + 1;
  1849. char *s = (char *) obstack_alloc (&string_obstack, len);
  1850. memcpy (s, string, len);
  1851. return s;
  1852. @}
  1853. @end smallexample
  1854. To allocate a block with specified contents, use the function
  1855. @code{obstack_copy}, declared like this:
  1856. @deftypefun {void *} obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
  1857. @standards{GNU, obstack.h}
  1858. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
  1859. @c obstack_copy @mtsrace:obstack-ptr @acucorrupt @acsmem
  1860. @c obstack_grow dup @mtsrace:obstack-ptr @acucorrupt @acsmem
  1861. @c obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
  1862. This allocates a block and initializes it by copying @var{size}
  1863. bytes of data starting at @var{address}. It calls
  1864. @code{obstack_alloc_failed_handler} if allocation of memory by
  1865. @code{obstack_chunk_alloc} failed.
  1866. @end deftypefun
  1867. @deftypefun {void *} obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
  1868. @standards{GNU, obstack.h}
  1869. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
  1870. @c obstack_copy0 @mtsrace:obstack-ptr @acucorrupt @acsmem
  1871. @c obstack_grow0 dup @mtsrace:obstack-ptr @acucorrupt @acsmem
  1872. @c obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
  1873. Like @code{obstack_copy}, but appends an extra byte containing a null
  1874. character. This extra byte is not counted in the argument @var{size}.
  1875. @end deftypefun
  1876. The @code{obstack_copy0} function is convenient for copying a sequence
  1877. of characters into an obstack as a null-terminated string. Here is an
  1878. example of its use:
  1879. @smallexample
  1880. char *
  1881. obstack_savestring (char *addr, int size)
  1882. @{
  1883. return obstack_copy0 (&myobstack, addr, size);
  1884. @}
  1885. @end smallexample
  1886. @noindent
  1887. Contrast this with the previous example of @code{savestring} using
  1888. @code{malloc} (@pxref{Basic Allocation}).
  1889. @node Freeing Obstack Objects
  1890. @subsubsection Freeing Objects in an Obstack
  1891. @cindex freeing (obstacks)
  1892. To free an object allocated in an obstack, use the function
  1893. @code{obstack_free}. Since the obstack is a stack of objects, freeing
  1894. one object automatically frees all other objects allocated more recently
  1895. in the same obstack.
  1896. @deftypefun void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
  1897. @standards{GNU, obstack.h}
  1898. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{}}}
  1899. @c obstack_free @mtsrace:obstack-ptr @acucorrupt
  1900. @c (obstack_free) @mtsrace:obstack-ptr @acucorrupt
  1901. @c *freefun dup user-supplied
  1902. If @var{object} is a null pointer, everything allocated in the obstack
  1903. is freed. Otherwise, @var{object} must be the address of an object
  1904. allocated in the obstack. Then @var{object} is freed, along with
  1905. everything allocated in @var{obstack-ptr} since @var{object}.
  1906. @end deftypefun
  1907. Note that if @var{object} is a null pointer, the result is an
  1908. uninitialized obstack. To free all memory in an obstack but leave it
  1909. valid for further allocation, call @code{obstack_free} with the address
  1910. of the first object allocated on the obstack:
  1911. @smallexample
  1912. obstack_free (obstack_ptr, first_object_allocated_ptr);
  1913. @end smallexample
  1914. Recall that the objects in an obstack are grouped into chunks. When all
  1915. the objects in a chunk become free, the obstack library automatically
  1916. frees the chunk (@pxref{Preparing for Obstacks}). Then other
  1917. obstacks, or non-obstack allocation, can reuse the space of the chunk.
  1918. @node Obstack Functions
  1919. @subsubsection Obstack Functions and Macros
  1920. @cindex macros
  1921. The interfaces for using obstacks may be defined either as functions or
  1922. as macros, depending on the compiler. The obstack facility works with
  1923. all C compilers, including both @w{ISO C} and traditional C, but there are
  1924. precautions you must take if you plan to use compilers other than GNU C.
  1925. If you are using an old-fashioned @w{non-ISO C} compiler, all the obstack
  1926. ``functions'' are actually defined only as macros. You can call these
  1927. macros like functions, but you cannot use them in any other way (for
  1928. example, you cannot take their address).
  1929. Calling the macros requires a special precaution: namely, the first
  1930. operand (the obstack pointer) may not contain any side effects, because
  1931. it may be computed more than once. For example, if you write this:
  1932. @smallexample
  1933. obstack_alloc (get_obstack (), 4);
  1934. @end smallexample
  1935. @noindent
  1936. you will find that @code{get_obstack} may be called several times.
  1937. If you use @code{*obstack_list_ptr++} as the obstack pointer argument,
  1938. you will get very strange results since the incrementation may occur
  1939. several times.
  1940. In @w{ISO C}, each function has both a macro definition and a function
  1941. definition. The function definition is used if you take the address of the
  1942. function without calling it. An ordinary call uses the macro definition by
  1943. default, but you can request the function definition instead by writing the
  1944. function name in parentheses, as shown here:
  1945. @smallexample
  1946. char *x;
  1947. void *(*funcp) ();
  1948. /* @r{Use the macro}. */
  1949. x = (char *) obstack_alloc (obptr, size);
  1950. /* @r{Call the function}. */
  1951. x = (char *) (obstack_alloc) (obptr, size);
  1952. /* @r{Take the address of the function}. */
  1953. funcp = obstack_alloc;
  1954. @end smallexample
  1955. @noindent
  1956. This is the same situation that exists in @w{ISO C} for the standard library
  1957. functions. @xref{Macro Definitions}.
  1958. @strong{Warning:} When you do use the macros, you must observe the
  1959. precaution of avoiding side effects in the first operand, even in @w{ISO C}.
  1960. If you use the GNU C compiler, this precaution is not necessary, because
  1961. various language extensions in GNU C permit defining the macros so as to
  1962. compute each argument only once.
  1963. @node Growing Objects
  1964. @subsubsection Growing Objects
  1965. @cindex growing objects (in obstacks)
  1966. @cindex changing the size of a block (obstacks)
  1967. Because memory in obstack chunks is used sequentially, it is possible to
  1968. build up an object step by step, adding one or more bytes at a time to the
  1969. end of the object. With this technique, you do not need to know how much
  1970. data you will put in the object until you come to the end of it. We call
  1971. this the technique of @dfn{growing objects}. The special functions
  1972. for adding data to the growing object are described in this section.
  1973. You don't need to do anything special when you start to grow an object.
  1974. Using one of the functions to add data to the object automatically
  1975. starts it. However, it is necessary to say explicitly when the object is
  1976. finished. This is done with the function @code{obstack_finish}.
  1977. The actual address of the object thus built up is not known until the
  1978. object is finished. Until then, it always remains possible that you will
  1979. add so much data that the object must be copied into a new chunk.
  1980. While the obstack is in use for a growing object, you cannot use it for
  1981. ordinary allocation of another object. If you try to do so, the space
  1982. already added to the growing object will become part of the other object.
  1983. @deftypefun void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
  1984. @standards{GNU, obstack.h}
  1985. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
  1986. @c obstack_blank @mtsrace:obstack-ptr @acucorrupt @acsmem
  1987. @c _obstack_newchunk @mtsrace:obstack-ptr @acucorrupt @acsmem
  1988. @c *chunkfun dup @acsmem
  1989. @c *obstack_alloc_failed_handler dup user-supplied
  1990. @c *freefun
  1991. @c obstack_blank_fast dup @mtsrace:obstack-ptr
  1992. The most basic function for adding to a growing object is
  1993. @code{obstack_blank}, which adds space without initializing it.
  1994. @end deftypefun
  1995. @deftypefun void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
  1996. @standards{GNU, obstack.h}
  1997. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
  1998. @c obstack_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
  1999. @c _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
  2000. @c memcpy ok
  2001. To add a block of initialized space, use @code{obstack_grow}, which is
  2002. the growing-object analogue of @code{obstack_copy}. It adds @var{size}
  2003. bytes of data to the growing object, copying the contents from
  2004. @var{data}.
  2005. @end deftypefun
  2006. @deftypefun void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
  2007. @standards{GNU, obstack.h}
  2008. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
  2009. @c obstack_grow0 @mtsrace:obstack-ptr @acucorrupt @acsmem
  2010. @c (no sequence point between storing NUL and incrementing next_free)
  2011. @c (multiple changes to next_free => @acucorrupt)
  2012. @c _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
  2013. @c memcpy ok
  2014. This is the growing-object analogue of @code{obstack_copy0}. It adds
  2015. @var{size} bytes copied from @var{data}, followed by an additional null
  2016. character.
  2017. @end deftypefun
  2018. @deftypefun void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{c})
  2019. @standards{GNU, obstack.h}
  2020. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
  2021. @c obstack_1grow @mtsrace:obstack-ptr @acucorrupt @acsmem
  2022. @c _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
  2023. @c obstack_1grow_fast dup @mtsrace:obstack-ptr @acucorrupt @acsmem
  2024. To add one character at a time, use the function @code{obstack_1grow}.
  2025. It adds a single byte containing @var{c} to the growing object.
  2026. @end deftypefun
  2027. @deftypefun void obstack_ptr_grow (struct obstack *@var{obstack-ptr}, void *@var{data})
  2028. @standards{GNU, obstack.h}
  2029. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
  2030. @c obstack_ptr_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
  2031. @c _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
  2032. @c obstack_ptr_grow_fast dup @mtsrace:obstack-ptr
  2033. Adding the value of a pointer one can use the function
  2034. @code{obstack_ptr_grow}. It adds @code{sizeof (void *)} bytes
  2035. containing the value of @var{data}.
  2036. @end deftypefun
  2037. @deftypefun void obstack_int_grow (struct obstack *@var{obstack-ptr}, int @var{data})
  2038. @standards{GNU, obstack.h}
  2039. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
  2040. @c obstack_int_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
  2041. @c _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
  2042. @c obstack_int_grow_fast dup @mtsrace:obstack-ptr
  2043. A single value of type @code{int} can be added by using the
  2044. @code{obstack_int_grow} function. It adds @code{sizeof (int)} bytes to
  2045. the growing object and initializes them with the value of @var{data}.
  2046. @end deftypefun
  2047. @deftypefun {void *} obstack_finish (struct obstack *@var{obstack-ptr})
  2048. @standards{GNU, obstack.h}
  2049. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{}}}
  2050. @c obstack_finish @mtsrace:obstack-ptr @acucorrupt
  2051. When you are finished growing the object, use the function
  2052. @code{obstack_finish} to close it off and return its final address.
  2053. Once you have finished the object, the obstack is available for ordinary
  2054. allocation or for growing another object.
  2055. This function can return a null pointer under the same conditions as
  2056. @code{obstack_alloc} (@pxref{Allocation in an Obstack}).
  2057. @end deftypefun
  2058. When you build an object by growing it, you will probably need to know
  2059. afterward how long it became. You need not keep track of this as you grow
  2060. the object, because you can find out the length from the obstack just
  2061. before finishing the object with the function @code{obstack_object_size},
  2062. declared as follows:
  2063. @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
  2064. @standards{GNU, obstack.h}
  2065. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
  2066. This function returns the current size of the growing object, in bytes.
  2067. Remember to call this function @emph{before} finishing the object.
  2068. After it is finished, @code{obstack_object_size} will return zero.
  2069. @end deftypefun
  2070. If you have started growing an object and wish to cancel it, you should
  2071. finish it and then free it, like this:
  2072. @smallexample
  2073. obstack_free (obstack_ptr, obstack_finish (obstack_ptr));
  2074. @end smallexample
  2075. @noindent
  2076. This has no effect if no object was growing.
  2077. @cindex shrinking objects
  2078. You can use @code{obstack_blank} with a negative size argument to make
  2079. the current object smaller. Just don't try to shrink it beyond zero
  2080. length---there's no telling what will happen if you do that.
  2081. @node Extra Fast Growing
  2082. @subsubsection Extra Fast Growing Objects
  2083. @cindex efficiency and obstacks
  2084. The usual functions for growing objects incur overhead for checking
  2085. whether there is room for the new growth in the current chunk. If you
  2086. are frequently constructing objects in small steps of growth, this
  2087. overhead can be significant.
  2088. You can reduce the overhead by using special ``fast growth''
  2089. functions that grow the object without checking. In order to have a
  2090. robust program, you must do the checking yourself. If you do this checking
  2091. in the simplest way each time you are about to add data to the object, you
  2092. have not saved anything, because that is what the ordinary growth
  2093. functions do. But if you can arrange to check less often, or check
  2094. more efficiently, then you make the program faster.
  2095. The function @code{obstack_room} returns the amount of room available
  2096. in the current chunk. It is declared as follows:
  2097. @deftypefun int obstack_room (struct obstack *@var{obstack-ptr})
  2098. @standards{GNU, obstack.h}
  2099. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
  2100. This returns the number of bytes that can be added safely to the current
  2101. growing object (or to an object about to be started) in obstack
  2102. @var{obstack-ptr} using the fast growth functions.
  2103. @end deftypefun
  2104. While you know there is room, you can use these fast growth functions
  2105. for adding data to a growing object:
  2106. @deftypefun void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{c})
  2107. @standards{GNU, obstack.h}
  2108. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
  2109. @c obstack_1grow_fast @mtsrace:obstack-ptr @acucorrupt @acsmem
  2110. @c (no sequence point between copying c and incrementing next_free)
  2111. The function @code{obstack_1grow_fast} adds one byte containing the
  2112. character @var{c} to the growing object in obstack @var{obstack-ptr}.
  2113. @end deftypefun
  2114. @deftypefun void obstack_ptr_grow_fast (struct obstack *@var{obstack-ptr}, void *@var{data})
  2115. @standards{GNU, obstack.h}
  2116. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
  2117. @c obstack_ptr_grow_fast @mtsrace:obstack-ptr
  2118. The function @code{obstack_ptr_grow_fast} adds @code{sizeof (void *)}
  2119. bytes containing the value of @var{data} to the growing object in
  2120. obstack @var{obstack-ptr}.
  2121. @end deftypefun
  2122. @deftypefun void obstack_int_grow_fast (struct obstack *@var{obstack-ptr}, int @var{data})
  2123. @standards{GNU, obstack.h}
  2124. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
  2125. @c obstack_int_grow_fast @mtsrace:obstack-ptr
  2126. The function @code{obstack_int_grow_fast} adds @code{sizeof (int)} bytes
  2127. containing the value of @var{data} to the growing object in obstack
  2128. @var{obstack-ptr}.
  2129. @end deftypefun
  2130. @deftypefun void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
  2131. @standards{GNU, obstack.h}
  2132. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
  2133. @c obstack_blank_fast @mtsrace:obstack-ptr
  2134. The function @code{obstack_blank_fast} adds @var{size} bytes to the
  2135. growing object in obstack @var{obstack-ptr} without initializing them.
  2136. @end deftypefun
  2137. When you check for space using @code{obstack_room} and there is not
  2138. enough room for what you want to add, the fast growth functions
  2139. are not safe. In this case, simply use the corresponding ordinary
  2140. growth function instead. Very soon this will copy the object to a
  2141. new chunk; then there will be lots of room available again.
  2142. So, each time you use an ordinary growth function, check afterward for
  2143. sufficient space using @code{obstack_room}. Once the object is copied
  2144. to a new chunk, there will be plenty of space again, so the program will
  2145. start using the fast growth functions again.
  2146. Here is an example:
  2147. @smallexample
  2148. @group
  2149. void
  2150. add_string (struct obstack *obstack, const char *ptr, int len)
  2151. @{
  2152. while (len > 0)
  2153. @{
  2154. int room = obstack_room (obstack);
  2155. if (room == 0)
  2156. @{
  2157. /* @r{Not enough room. Add one character slowly,}
  2158. @r{which may copy to a new chunk and make room.} */
  2159. obstack_1grow (obstack, *ptr++);
  2160. len--;
  2161. @}
  2162. else
  2163. @{
  2164. if (room > len)
  2165. room = len;
  2166. /* @r{Add fast as much as we have room for.} */
  2167. len -= room;
  2168. while (room-- > 0)
  2169. obstack_1grow_fast (obstack, *ptr++);
  2170. @}
  2171. @}
  2172. @}
  2173. @end group
  2174. @end smallexample
  2175. @node Status of an Obstack
  2176. @subsubsection Status of an Obstack
  2177. @cindex obstack status
  2178. @cindex status of obstack
  2179. Here are functions that provide information on the current status of
  2180. allocation in an obstack. You can use them to learn about an object while
  2181. still growing it.
  2182. @deftypefun {void *} obstack_base (struct obstack *@var{obstack-ptr})
  2183. @standards{GNU, obstack.h}
  2184. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acsafe{}}
  2185. This function returns the tentative address of the beginning of the
  2186. currently growing object in @var{obstack-ptr}. If you finish the object
  2187. immediately, it will have that address. If you make it larger first, it
  2188. may outgrow the current chunk---then its address will change!
  2189. If no object is growing, this value says where the next object you
  2190. allocate will start (once again assuming it fits in the current
  2191. chunk).
  2192. @end deftypefun
  2193. @deftypefun {void *} obstack_next_free (struct obstack *@var{obstack-ptr})
  2194. @standards{GNU, obstack.h}
  2195. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acsafe{}}
  2196. This function returns the address of the first free byte in the current
  2197. chunk of obstack @var{obstack-ptr}. This is the end of the currently
  2198. growing object. If no object is growing, @code{obstack_next_free}
  2199. returns the same value as @code{obstack_base}.
  2200. @end deftypefun
  2201. @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
  2202. @standards{GNU, obstack.h}
  2203. @c dup
  2204. @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
  2205. This function returns the size in bytes of the currently growing object.
  2206. This is equivalent to
  2207. @smallexample
  2208. obstack_next_free (@var{obstack-ptr}) - obstack_base (@var{obstack-ptr})
  2209. @end smallexample
  2210. @end deftypefun
  2211. @node Obstacks Data Alignment
  2212. @subsubsection Alignment of Data in Obstacks
  2213. @cindex alignment (in obstacks)
  2214. Each obstack has an @dfn{alignment boundary}; each object allocated in
  2215. the obstack automatically starts on an address that is a multiple of the
  2216. specified boundary. By default, this boundary is aligned so that
  2217. the object can hold any type of data.
  2218. To access an obstack's alignment boundary, use the macro
  2219. @code{obstack_alignment_mask}, whose function prototype looks like
  2220. this:
  2221. @deftypefn Macro int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
  2222. @standards{GNU, obstack.h}
  2223. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2224. The value is a bit mask; a bit that is 1 indicates that the corresponding
  2225. bit in the address of an object should be 0. The mask value should be one
  2226. less than a power of 2; the effect is that all object addresses are
  2227. multiples of that power of 2. The default value of the mask is a value
  2228. that allows aligned objects to hold any type of data: for example, if
  2229. its value is 3, any type of data can be stored at locations whose
  2230. addresses are multiples of 4. A mask value of 0 means an object can start
  2231. on any multiple of 1 (that is, no alignment is required).
  2232. The expansion of the macro @code{obstack_alignment_mask} is an lvalue,
  2233. so you can alter the mask by assignment. For example, this statement:
  2234. @smallexample
  2235. obstack_alignment_mask (obstack_ptr) = 0;
  2236. @end smallexample
  2237. @noindent
  2238. has the effect of turning off alignment processing in the specified obstack.
  2239. @end deftypefn
  2240. Note that a change in alignment mask does not take effect until
  2241. @emph{after} the next time an object is allocated or finished in the
  2242. obstack. If you are not growing an object, you can make the new
  2243. alignment mask take effect immediately by calling @code{obstack_finish}.
  2244. This will finish a zero-length object and then do proper alignment for
  2245. the next object.
  2246. @node Obstack Chunks
  2247. @subsubsection Obstack Chunks
  2248. @cindex efficiency of chunks
  2249. @cindex chunks
  2250. Obstacks work by allocating space for themselves in large chunks, and
  2251. then parceling out space in the chunks to satisfy your requests. Chunks
  2252. are normally 4096 bytes long unless you specify a different chunk size.
  2253. The chunk size includes 8 bytes of overhead that are not actually used
  2254. for storing objects. Regardless of the specified size, longer chunks
  2255. will be allocated when necessary for long objects.
  2256. The obstack library allocates chunks by calling the function
  2257. @code{obstack_chunk_alloc}, which you must define. When a chunk is no
  2258. longer needed because you have freed all the objects in it, the obstack
  2259. library frees the chunk by calling @code{obstack_chunk_free}, which you
  2260. must also define.
  2261. These two must be defined (as macros) or declared (as functions) in each
  2262. source file that uses @code{obstack_init} (@pxref{Creating Obstacks}).
  2263. Most often they are defined as macros like this:
  2264. @smallexample
  2265. #define obstack_chunk_alloc malloc
  2266. #define obstack_chunk_free free
  2267. @end smallexample
  2268. Note that these are simple macros (no arguments). Macro definitions with
  2269. arguments will not work! It is necessary that @code{obstack_chunk_alloc}
  2270. or @code{obstack_chunk_free}, alone, expand into a function name if it is
  2271. not itself a function name.
  2272. If you allocate chunks with @code{malloc}, the chunk size should be a
  2273. power of 2. The default chunk size, 4096, was chosen because it is long
  2274. enough to satisfy many typical requests on the obstack yet short enough
  2275. not to waste too much memory in the portion of the last chunk not yet used.
  2276. @deftypefn Macro int obstack_chunk_size (struct obstack *@var{obstack-ptr})
  2277. @standards{GNU, obstack.h}
  2278. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2279. This returns the chunk size of the given obstack.
  2280. @end deftypefn
  2281. Since this macro expands to an lvalue, you can specify a new chunk size by
  2282. assigning it a new value. Doing so does not affect the chunks already
  2283. allocated, but will change the size of chunks allocated for that particular
  2284. obstack in the future. It is unlikely to be useful to make the chunk size
  2285. smaller, but making it larger might improve efficiency if you are
  2286. allocating many objects whose size is comparable to the chunk size. Here
  2287. is how to do so cleanly:
  2288. @smallexample
  2289. if (obstack_chunk_size (obstack_ptr) < @var{new-chunk-size})
  2290. obstack_chunk_size (obstack_ptr) = @var{new-chunk-size};
  2291. @end smallexample
  2292. @node Summary of Obstacks
  2293. @subsubsection Summary of Obstack Functions
  2294. Here is a summary of all the functions associated with obstacks. Each
  2295. takes the address of an obstack (@code{struct obstack *}) as its first
  2296. argument.
  2297. @table @code
  2298. @item void obstack_init (struct obstack *@var{obstack-ptr})
  2299. Initialize use of an obstack. @xref{Creating Obstacks}.
  2300. @item void *obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
  2301. Allocate an object of @var{size} uninitialized bytes.
  2302. @xref{Allocation in an Obstack}.
  2303. @item void *obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
  2304. Allocate an object of @var{size} bytes, with contents copied from
  2305. @var{address}. @xref{Allocation in an Obstack}.
  2306. @item void *obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
  2307. Allocate an object of @var{size}+1 bytes, with @var{size} of them copied
  2308. from @var{address}, followed by a null character at the end.
  2309. @xref{Allocation in an Obstack}.
  2310. @item void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
  2311. Free @var{object} (and everything allocated in the specified obstack
  2312. more recently than @var{object}). @xref{Freeing Obstack Objects}.
  2313. @item void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
  2314. Add @var{size} uninitialized bytes to a growing object.
  2315. @xref{Growing Objects}.
  2316. @item void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
  2317. Add @var{size} bytes, copied from @var{address}, to a growing object.
  2318. @xref{Growing Objects}.
  2319. @item void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
  2320. Add @var{size} bytes, copied from @var{address}, to a growing object,
  2321. and then add another byte containing a null character. @xref{Growing
  2322. Objects}.
  2323. @item void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{data-char})
  2324. Add one byte containing @var{data-char} to a growing object.
  2325. @xref{Growing Objects}.
  2326. @item void *obstack_finish (struct obstack *@var{obstack-ptr})
  2327. Finalize the object that is growing and return its permanent address.
  2328. @xref{Growing Objects}.
  2329. @item int obstack_object_size (struct obstack *@var{obstack-ptr})
  2330. Get the current size of the currently growing object. @xref{Growing
  2331. Objects}.
  2332. @item void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
  2333. Add @var{size} uninitialized bytes to a growing object without checking
  2334. that there is enough room. @xref{Extra Fast Growing}.
  2335. @item void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{data-char})
  2336. Add one byte containing @var{data-char} to a growing object without
  2337. checking that there is enough room. @xref{Extra Fast Growing}.
  2338. @item int obstack_room (struct obstack *@var{obstack-ptr})
  2339. Get the amount of room now available for growing the current object.
  2340. @xref{Extra Fast Growing}.
  2341. @item int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
  2342. The mask used for aligning the beginning of an object. This is an
  2343. lvalue. @xref{Obstacks Data Alignment}.
  2344. @item int obstack_chunk_size (struct obstack *@var{obstack-ptr})
  2345. The size for allocating chunks. This is an lvalue. @xref{Obstack Chunks}.
  2346. @item void *obstack_base (struct obstack *@var{obstack-ptr})
  2347. Tentative starting address of the currently growing object.
  2348. @xref{Status of an Obstack}.
  2349. @item void *obstack_next_free (struct obstack *@var{obstack-ptr})
  2350. Address just after the end of the currently growing object.
  2351. @xref{Status of an Obstack}.
  2352. @end table
  2353. @node Variable Size Automatic
  2354. @subsection Automatic Storage with Variable Size
  2355. @cindex automatic freeing
  2356. @cindex @code{alloca} function
  2357. @cindex automatic storage with variable size
  2358. The function @code{alloca} supports a kind of half-dynamic allocation in
  2359. which blocks are allocated dynamically but freed automatically.
  2360. Allocating a block with @code{alloca} is an explicit action; you can
  2361. allocate as many blocks as you wish, and compute the size at run time. But
  2362. all the blocks are freed when you exit the function that @code{alloca} was
  2363. called from, just as if they were automatic variables declared in that
  2364. function. There is no way to free the space explicitly.
  2365. The prototype for @code{alloca} is in @file{stdlib.h}. This function is
  2366. a BSD extension.
  2367. @pindex stdlib.h
  2368. @deftypefun {void *} alloca (size_t @var{size})
  2369. @standards{GNU, stdlib.h}
  2370. @standards{BSD, stdlib.h}
  2371. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2372. The return value of @code{alloca} is the address of a block of @var{size}
  2373. bytes of memory, allocated in the stack frame of the calling function.
  2374. @end deftypefun
  2375. Do not use @code{alloca} inside the arguments of a function call---you
  2376. will get unpredictable results, because the stack space for the
  2377. @code{alloca} would appear on the stack in the middle of the space for
  2378. the function arguments. An example of what to avoid is @code{foo (x,
  2379. alloca (4), y)}.
  2380. @c This might get fixed in future versions of GCC, but that won't make
  2381. @c it safe with compilers generally.
  2382. @menu
  2383. * Alloca Example:: Example of using @code{alloca}.
  2384. * Advantages of Alloca:: Reasons to use @code{alloca}.
  2385. * Disadvantages of Alloca:: Reasons to avoid @code{alloca}.
  2386. * GNU C Variable-Size Arrays:: Only in GNU C, here is an alternative
  2387. method of allocating dynamically and
  2388. freeing automatically.
  2389. @end menu
  2390. @node Alloca Example
  2391. @subsubsection @code{alloca} Example
  2392. As an example of the use of @code{alloca}, here is a function that opens
  2393. a file name made from concatenating two argument strings, and returns a
  2394. file descriptor or minus one signifying failure:
  2395. @smallexample
  2396. int
  2397. open2 (char *str1, char *str2, int flags, int mode)
  2398. @{
  2399. char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
  2400. stpcpy (stpcpy (name, str1), str2);
  2401. return open (name, flags, mode);
  2402. @}
  2403. @end smallexample
  2404. @noindent
  2405. Here is how you would get the same results with @code{malloc} and
  2406. @code{free}:
  2407. @smallexample
  2408. int
  2409. open2 (char *str1, char *str2, int flags, int mode)
  2410. @{
  2411. char *name = malloc (strlen (str1) + strlen (str2) + 1);
  2412. int desc;
  2413. if (name == 0)
  2414. fatal ("virtual memory exceeded");
  2415. stpcpy (stpcpy (name, str1), str2);
  2416. desc = open (name, flags, mode);
  2417. free (name);
  2418. return desc;
  2419. @}
  2420. @end smallexample
  2421. As you can see, it is simpler with @code{alloca}. But @code{alloca} has
  2422. other, more important advantages, and some disadvantages.
  2423. @node Advantages of Alloca
  2424. @subsubsection Advantages of @code{alloca}
  2425. Here are the reasons why @code{alloca} may be preferable to @code{malloc}:
  2426. @itemize @bullet
  2427. @item
  2428. Using @code{alloca} wastes very little space and is very fast. (It is
  2429. open-coded by the GNU C compiler.)
  2430. @item
  2431. Since @code{alloca} does not have separate pools for different sizes of
  2432. blocks, space used for any size block can be reused for any other size.
  2433. @code{alloca} does not cause memory fragmentation.
  2434. @item
  2435. @cindex longjmp
  2436. Nonlocal exits done with @code{longjmp} (@pxref{Non-Local Exits})
  2437. automatically free the space allocated with @code{alloca} when they exit
  2438. through the function that called @code{alloca}. This is the most
  2439. important reason to use @code{alloca}.
  2440. To illustrate this, suppose you have a function
  2441. @code{open_or_report_error} which returns a descriptor, like
  2442. @code{open}, if it succeeds, but does not return to its caller if it
  2443. fails. If the file cannot be opened, it prints an error message and
  2444. jumps out to the command level of your program using @code{longjmp}.
  2445. Let's change @code{open2} (@pxref{Alloca Example}) to use this
  2446. subroutine:
  2447. @smallexample
  2448. int
  2449. open2 (char *str1, char *str2, int flags, int mode)
  2450. @{
  2451. char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
  2452. stpcpy (stpcpy (name, str1), str2);
  2453. return open_or_report_error (name, flags, mode);
  2454. @}
  2455. @end smallexample
  2456. @noindent
  2457. Because of the way @code{alloca} works, the memory it allocates is
  2458. freed even when an error occurs, with no special effort required.
  2459. By contrast, the previous definition of @code{open2} (which uses
  2460. @code{malloc} and @code{free}) would develop a memory leak if it were
  2461. changed in this way. Even if you are willing to make more changes to
  2462. fix it, there is no easy way to do so.
  2463. @end itemize
  2464. @node Disadvantages of Alloca
  2465. @subsubsection Disadvantages of @code{alloca}
  2466. @cindex @code{alloca} disadvantages
  2467. @cindex disadvantages of @code{alloca}
  2468. These are the disadvantages of @code{alloca} in comparison with
  2469. @code{malloc}:
  2470. @itemize @bullet
  2471. @item
  2472. If you try to allocate more memory than the machine can provide, you
  2473. don't get a clean error message. Instead you get a fatal signal like
  2474. the one you would get from an infinite recursion; probably a
  2475. segmentation violation (@pxref{Program Error Signals}).
  2476. @item
  2477. Some @nongnusystems{} fail to support @code{alloca}, so it is less
  2478. portable. However, a slower emulation of @code{alloca} written in C
  2479. is available for use on systems with this deficiency.
  2480. @end itemize
  2481. @node GNU C Variable-Size Arrays
  2482. @subsubsection GNU C Variable-Size Arrays
  2483. @cindex variable-sized arrays
  2484. In GNU C, you can replace most uses of @code{alloca} with an array of
  2485. variable size. Here is how @code{open2} would look then:
  2486. @smallexample
  2487. int open2 (char *str1, char *str2, int flags, int mode)
  2488. @{
  2489. char name[strlen (str1) + strlen (str2) + 1];
  2490. stpcpy (stpcpy (name, str1), str2);
  2491. return open (name, flags, mode);
  2492. @}
  2493. @end smallexample
  2494. But @code{alloca} is not always equivalent to a variable-sized array, for
  2495. several reasons:
  2496. @itemize @bullet
  2497. @item
  2498. A variable size array's space is freed at the end of the scope of the
  2499. name of the array. The space allocated with @code{alloca}
  2500. remains until the end of the function.
  2501. @item
  2502. It is possible to use @code{alloca} within a loop, allocating an
  2503. additional block on each iteration. This is impossible with
  2504. variable-sized arrays.
  2505. @end itemize
  2506. @strong{NB:} If you mix use of @code{alloca} and variable-sized arrays
  2507. within one function, exiting a scope in which a variable-sized array was
  2508. declared frees all blocks allocated with @code{alloca} during the
  2509. execution of that scope.
  2510. @node Resizing the Data Segment
  2511. @section Resizing the Data Segment
  2512. The symbols in this section are declared in @file{unistd.h}.
  2513. You will not normally use the functions in this section, because the
  2514. functions described in @ref{Memory Allocation} are easier to use. Those
  2515. are interfaces to a @glibcadj{} memory allocator that uses the
  2516. functions below itself. The functions below are simple interfaces to
  2517. system calls.
  2518. @deftypefun int brk (void *@var{addr})
  2519. @standards{BSD, unistd.h}
  2520. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2521. @code{brk} sets the high end of the calling process' data segment to
  2522. @var{addr}.
  2523. The address of the end of a segment is defined to be the address of the
  2524. last byte in the segment plus 1.
  2525. The function has no effect if @var{addr} is lower than the low end of
  2526. the data segment. (This is considered success, by the way.)
  2527. The function fails if it would cause the data segment to overlap another
  2528. segment or exceed the process' data storage limit (@pxref{Limits on
  2529. Resources}).
  2530. The function is named for a common historical case where data storage
  2531. and the stack are in the same segment. Data storage allocation grows
  2532. upward from the bottom of the segment while the stack grows downward
  2533. toward it from the top of the segment and the curtain between them is
  2534. called the @dfn{break}.
  2535. The return value is zero on success. On failure, the return value is
  2536. @code{-1} and @code{errno} is set accordingly. The following @code{errno}
  2537. values are specific to this function:
  2538. @table @code
  2539. @item ENOMEM
  2540. The request would cause the data segment to overlap another segment or
  2541. exceed the process' data storage limit.
  2542. @end table
  2543. @c The Brk system call in Linux (as opposed to the GNU C Library function)
  2544. @c is considerably different. It always returns the new end of the data
  2545. @c segment, whether it succeeds or fails. The GNU C library Brk determines
  2546. @c it's a failure if and only if the system call returns an address less
  2547. @c than the address requested.
  2548. @end deftypefun
  2549. @deftypefun {void *} sbrk (ptrdiff_t @var{delta})
  2550. @standards{BSD, unistd.h}
  2551. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2552. This function is the same as @code{brk} except that you specify the new
  2553. end of the data segment as an offset @var{delta} from the current end
  2554. and on success the return value is the address of the resulting end of
  2555. the data segment instead of zero.
  2556. This means you can use @samp{sbrk(0)} to find out what the current end
  2557. of the data segment is.
  2558. @end deftypefun
  2559. @node Memory Protection
  2560. @section Memory Protection
  2561. @cindex memory protection
  2562. @cindex page protection
  2563. @cindex protection flags
  2564. When a page is mapped using @code{mmap}, page protection flags can be
  2565. specified using the protection flags argument. @xref{Memory-mapped
  2566. I/O}.
  2567. The following flags are available:
  2568. @vtable @code
  2569. @item PROT_WRITE
  2570. @standards{POSIX, sys/mman.h}
  2571. The memory can be written to.
  2572. @item PROT_READ
  2573. @standards{POSIX, sys/mman.h}
  2574. The memory can be read. On some architectures, this flag implies that
  2575. the memory can be executed as well (as if @code{PROT_EXEC} had been
  2576. specified at the same time).
  2577. @item PROT_EXEC
  2578. @standards{POSIX, sys/mman.h}
  2579. The memory can be used to store instructions which can then be executed.
  2580. On most architectures, this flag implies that the memory can be read (as
  2581. if @code{PROT_READ} had been specified).
  2582. @item PROT_NONE
  2583. @standards{POSIX, sys/mman.h}
  2584. This flag must be specified on its own.
  2585. The memory is reserved, but cannot be read, written, or executed. If
  2586. this flag is specified in a call to @code{mmap}, a virtual memory area
  2587. will be set aside for future use in the process, and @code{mmap} calls
  2588. without the @code{MAP_FIXED} flag will not use it for subsequent
  2589. allocations. For anonymous mappings, the kernel will not reserve any
  2590. physical memory for the allocation at the time the mapping is created.
  2591. @end vtable
  2592. The operating system may keep track of these flags separately even if
  2593. the underlying hardware treats them the same for the purposes of access
  2594. checking (as happens with @code{PROT_READ} and @code{PROT_EXEC} on some
  2595. platforms). On GNU systems, @code{PROT_EXEC} always implies
  2596. @code{PROT_READ}, so that users can view the machine code which is
  2597. executing on their system.
  2598. Inappropriate access will cause a segfault (@pxref{Program Error
  2599. Signals}).
  2600. After allocation, protection flags can be changed using the
  2601. @code{mprotect} function.
  2602. @deftypefun int mprotect (void *@var{address}, size_t @var{length}, int @var{protection})
  2603. @standards{POSIX, sys/mman.h}
  2604. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2605. A successful call to the @code{mprotect} function changes the protection
  2606. flags of at least @var{length} bytes of memory, starting at
  2607. @var{address}.
  2608. @var{address} must be aligned to the page size for the mapping. The
  2609. system page size can be obtained by calling @code{sysconf} with the
  2610. @code{_SC_PAGESIZE} parameter (@pxref{Sysconf Definition}). The system
  2611. page size is the granularity in which the page protection of anonymous
  2612. memory mappings and most file mappings can be changed. Memory which is
  2613. mapped from special files or devices may have larger page granularity
  2614. than the system page size and may require larger alignment.
  2615. @var{length} is the number of bytes whose protection flags must be
  2616. changed. It is automatically rounded up to the next multiple of the
  2617. system page size.
  2618. @var{protection} is a combination of the @code{PROT_*} flags described
  2619. above.
  2620. The @code{mprotect} function returns @math{0} on success and @math{-1}
  2621. on failure.
  2622. The following @code{errno} error conditions are defined for this
  2623. function:
  2624. @table @code
  2625. @item ENOMEM
  2626. The system was not able to allocate resources to fulfill the request.
  2627. This can happen if there is not enough physical memory in the system for
  2628. the allocation of backing storage. The error can also occur if the new
  2629. protection flags would cause the memory region to be split from its
  2630. neighbors, and the process limit for the number of such distinct memory
  2631. regions would be exceeded.
  2632. @item EINVAL
  2633. @var{address} is not properly aligned to a page boundary for the
  2634. mapping, or @var{length} (after rounding up to the system page size) is
  2635. not a multiple of the applicable page size for the mapping, or the
  2636. combination of flags in @var{protection} is not valid.
  2637. @item EACCES
  2638. The file for a file-based mapping was not opened with open flags which
  2639. are compatible with @var{protection}.
  2640. @item EPERM
  2641. The system security policy does not allow a mapping with the specified
  2642. flags. For example, mappings which are both @code{PROT_EXEC} and
  2643. @code{PROT_WRITE} at the same time might not be allowed.
  2644. @end table
  2645. @end deftypefun
  2646. If the @code{mprotect} function is used to make a region of memory
  2647. inaccessible by specifying the @code{PROT_NONE} protection flag and
  2648. access is later restored, the memory retains its previous contents.
  2649. On some systems, it may not be possible to specify additional flags
  2650. which were not present when the mapping was first created. For example,
  2651. an attempt to make a region of memory executable could fail if the
  2652. initial protection flags were @samp{PROT_READ | PROT_WRITE}.
  2653. In general, the @code{mprotect} function can be used to change any
  2654. process memory, no matter how it was allocated. However, portable use
  2655. of the function requires that it is only used with memory regions
  2656. returned by @code{mmap} or @code{mmap64}.
  2657. @deftypefun int mseal (void *@var{address}, size_t @var{length}, unsigned long @var{flags})
  2658. @standards{Linux, sys/mman.h}
  2659. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2660. A successful call to the @code {mseal} function protects the memory
  2661. range @var{address} of @var{length} bytes, previously allocated with
  2662. @code{mmap} or @code{mremap}, against further metadata changes, such
  2663. as:
  2664. @itemize @bullet
  2665. @item
  2666. Unmapping, moving to another location, extending or shrinking the size,
  2667. via @code{munmap} and @code{mremap}.
  2668. @item
  2669. Moving or expanding a different VMA into the current location, via
  2670. @code{mremap}.
  2671. @item
  2672. Modifying the memory range with @code{mmap} along with the flag @code{MAP_FIXED}.
  2673. @item
  2674. Change the protection flags with @code{mprotect} or @code{pkey_mprotect}. Also
  2675. for certain destructive @code{madvise} behaviours (@code{MADV_DONTNEED},
  2676. @code{MADV_FREE}, @code{MADV_DONTNEED_LOCKED}, and @code{MADV_WIPEONFORK}),
  2677. @code{mseal} only blocks the operation if the protection key associated with
  2678. the memory denies write.
  2679. @item
  2680. Destructive behaviors on anonymous memory, such as @code{madvise} with
  2681. @code{MADV_DONTNEED}.
  2682. @end itemize
  2683. The @var{address} must be an allocated virtual memory done by @code{mmap}
  2684. or @code{mremap}, and it must be page-aligned. The end address (@var{address}
  2685. plus @var{length}) must be within an allocated virtual memory range. There
  2686. should be no unallocated memory between the start and end of the address range.
  2687. The @var{flags} is currently unused.
  2688. The @code{mseal} function returns @math{0} on success and @math{-1} on
  2689. failure.
  2690. The following @code{errno} error conditions are defined for this
  2691. function:
  2692. @table @code
  2693. @item EPERM
  2694. The system blocked the operation, and the given address range is unmodified
  2695. without a partial update. This error is also returned when @code{mseal} is
  2696. issued on a 32-bit CPU (sealing is currently supported only on 64-bit CPUs,
  2697. although 32-bit binaries running on a 64-bit kernel are supported).
  2698. @item ENOMEM
  2699. Either the @var{address} is not allocated, or the end address is not within the
  2700. allocation, or there is unallocated memory between the start and end address.
  2701. @item ENOSYS
  2702. The kernel does not support the @code{mseal} syscall.
  2703. @end table
  2704. @end deftypefun
  2705. @strong{NB:} The memory sealing changes the lifetime of a mapping, where the
  2706. sealing memory could not be unmapped until the process terminates or replaces
  2707. the process image through @code{execve} function. The sealed mappings are
  2708. inherited through @code{fork}.
  2709. @subsection Memory Protection Keys
  2710. @cindex memory protection key
  2711. @cindex protection key
  2712. @cindex MPK
  2713. On some systems, further access restrictions can be added to specific pages
  2714. using @dfn{memory protection keys}. These restrictions work as follows:
  2715. @itemize @bullet
  2716. @item
  2717. All memory pages are associated with a protection key. The default
  2718. protection key does not cause any additional protections to be applied
  2719. during memory accesses. New keys can be allocated with the
  2720. @code{pkey_alloc} function, and applied to pages using
  2721. @code{pkey_mprotect}.
  2722. @item
  2723. Each thread has a set of separate access restrictions for each
  2724. protection key. These access restrictions can be manipulated using the
  2725. @code{pkey_set} and @code{pkey_get} functions.
  2726. @item
  2727. During a memory access, the system obtains the protection key for the
  2728. accessed page and uses that to determine the applicable access restrictions,
  2729. as configured for the current thread. If the access is restricted, a
  2730. segmentation fault is the result ((@pxref{Program Error Signals}).
  2731. These checks happen in addition to the @code{PROT_}* protection flags
  2732. set by @code{mprotect} or @code{pkey_mprotect}.
  2733. @end itemize
  2734. New threads and subprocesses inherit the access restrictions of the current
  2735. thread. If a protection key is allocated subsequently, existing threads
  2736. (except the current) will use an unspecified system default for the
  2737. access restrictions associated with newly allocated keys.
  2738. Upon entering a signal handler, the system resets the access restrictions of
  2739. the current thread so that pages with the default key can be accessed,
  2740. but the access restrictions for other protection keys are unspecified.
  2741. Applications are expected to allocate a key once using
  2742. @code{pkey_alloc}, and apply the key to memory regions which need
  2743. special protection with @code{pkey_mprotect}:
  2744. @smallexample
  2745. int key = pkey_alloc (0, PKEY_DISABLE_ACCESS);
  2746. if (key < 0)
  2747. /* Perform error checking, including fallback for lack of support. */
  2748. ...;
  2749. /* Apply the key to a special memory region used to store critical
  2750. data. */
  2751. if (pkey_mprotect (region, region_length,
  2752. PROT_READ | PROT_WRITE, key) < 0)
  2753. ...; /* Perform error checking (generally fatal). */
  2754. @end smallexample
  2755. If the key allocation fails due to lack of support for memory protection
  2756. keys, the @code{pkey_mprotect} call can usually be skipped. In this
  2757. case, the region will not be protected by default. It is also possible
  2758. to call @code{pkey_mprotect} with a key value of @math{-1}, in which
  2759. case it will behave in the same way as @code{mprotect}.
  2760. After key allocation assignment to memory pages, @code{pkey_set} can be
  2761. used to temporarily acquire access to the memory region and relinquish
  2762. it again:
  2763. @smallexample
  2764. if (key >= 0 && pkey_set (key, PKEY_UNRESTRICTED) < 0)
  2765. ...; /* Perform error checking (generally fatal). */
  2766. /* At this point, the current thread has read-write access to the
  2767. memory region. */
  2768. ...
  2769. /* Revoke access again. */
  2770. if (key >= 0 && pkey_set (key, PKEY_DISABLE_ACCESS) < 0)
  2771. ...; /* Perform error checking (generally fatal). */
  2772. @end smallexample
  2773. In this example, a negative key value indicates that no key had been
  2774. allocated, which means that the system lacks support for memory
  2775. protection keys and it is not necessary to change the the access restrictions
  2776. of the current thread (because it always has access).
  2777. Compared to using @code{mprotect} to change the page protection flags,
  2778. this approach has two advantages: It is thread-safe in the sense that
  2779. the access restrictions are only changed for the current thread, so another
  2780. thread which changes its own access restrictions concurrently to gain access
  2781. to the mapping will not suddenly see its access restrictions updated. And
  2782. @code{pkey_set} typically does not involve a call into the kernel and a
  2783. context switch, so it is more efficient.
  2784. @deftypefun int pkey_alloc (unsigned int @var{flags}, unsigned int @var{access_restrictions})
  2785. @standards{Linux, sys/mman.h}
  2786. @safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@acucorrupt{}}}
  2787. Allocate a new protection key. The @var{flags} argument is reserved and
  2788. must be zero. The @var{access_restrictions} argument specifies access restrictions
  2789. which are applied to the current thread (as if with @code{pkey_set}
  2790. below). Access restrictions of other threads are not changed.
  2791. The function returns the new protection key, a non-negative number, or
  2792. @math{-1} on error.
  2793. The following @code{errno} error conditions are defined for this
  2794. function:
  2795. @table @code
  2796. @item ENOSYS
  2797. The system does not implement memory protection keys.
  2798. @item EINVAL
  2799. The @var{flags} argument is not zero.
  2800. The @var{access_restrictions} argument is invalid.
  2801. The system does not implement memory protection keys or runs in a mode
  2802. in which memory protection keys are disabled.
  2803. @item ENOSPC
  2804. All available protection keys already have been allocated.
  2805. The system does not implement memory protection keys or runs in a mode
  2806. in which memory protection keys are disabled.
  2807. @end table
  2808. @end deftypefun
  2809. @deftypefun int pkey_free (int @var{key})
  2810. @standards{Linux, sys/mman.h}
  2811. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2812. Deallocate the protection key, so that it can be reused by
  2813. @code{pkey_alloc}.
  2814. Calling this function does not change the access restrictions of the freed
  2815. protection key. The calling thread and other threads may retain access
  2816. to it, even if it is subsequently allocated again. For this reason, it
  2817. is not recommended to call the @code{pkey_free} function.
  2818. @table @code
  2819. @item ENOSYS
  2820. The system does not implement memory protection keys.
  2821. @item EINVAL
  2822. The @var{key} argument is not a valid protection key.
  2823. @end table
  2824. @end deftypefun
  2825. @deftypefun int pkey_mprotect (void *@var{address}, size_t @var{length}, int @var{protection}, int @var{key})
  2826. @standards{Linux, sys/mman.h}
  2827. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2828. Similar to @code{mprotect}, but also set the memory protection key for
  2829. the memory region to @code{key}.
  2830. Some systems use memory protection keys to emulate certain combinations
  2831. of @var{protection} flags. Under such circumstances, specifying an
  2832. explicit protection key may behave as if additional flags have been
  2833. specified in @var{protection}, even though this does not happen with the
  2834. default protection key. For example, some systems can support
  2835. @code{PROT_EXEC}-only mappings only with a default protection key, and
  2836. memory with a key which was allocated using @code{pkey_alloc} will still
  2837. be readable if @code{PROT_EXEC} is specified without @code{PROT_READ}.
  2838. If @var{key} is @math{-1}, the default protection key is applied to the
  2839. mapping, just as if @code{mprotect} had been called.
  2840. The @code{pkey_mprotect} function returns @math{0} on success and
  2841. @math{-1} on failure. The same @code{errno} error conditions as for
  2842. @code{mprotect} are defined for this function, with the following
  2843. addition:
  2844. @table @code
  2845. @item EINVAL
  2846. The @var{key} argument is not @math{-1} or a valid memory protection
  2847. key allocated using @code{pkey_alloc}.
  2848. @item ENOSYS
  2849. The system does not implement memory protection keys, and @var{key} is
  2850. not @math{-1}.
  2851. @end table
  2852. @end deftypefun
  2853. @deftypefun int pkey_set (int @var{key}, unsigned int @var{access_restrictions})
  2854. @standards{Linux, sys/mman.h}
  2855. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2856. Change the access restrictions of the current thread for memory pages with
  2857. the protection key @var{key} to @var{access_restrictions}. If
  2858. @var{access_restrictions} is @code{PKEY_UNRESTRICTED} (zero), no additional
  2859. access restrictions on top of the page protection flags are applied. Otherwise,
  2860. @var{access_restrictions} is a combination of the following flags:
  2861. @vtable @code
  2862. @item PKEY_DISABLE_READ
  2863. @standards{Linux, sys/mman.h}
  2864. Subsequent attempts to read from memory with the specified protection
  2865. key will fault. At present only AArch64 platforms with enabled Stage 1
  2866. permission overlays feature support this type of restriction.
  2867. @item PKEY_DISABLE_WRITE
  2868. @standards{Linux, sys/mman.h}
  2869. Subsequent attempts to write to memory with the specified protection
  2870. key will fault.
  2871. @item PKEY_DISABLE_ACCESS
  2872. @standards{Linux, sys/mman.h}
  2873. Subsequent attempts to write to or read from memory with the specified
  2874. protection key will fault. On AArch64 platforms with enabled Stage 1
  2875. permission overlays feature this restriction value has the same effect
  2876. as combination of @code{PKEY_DISABLE_READ} and @code{PKEY_DISABLE_WRITE}.
  2877. @item PKEY_DISABLE_EXECUTE
  2878. @standards{Linux, sys/mman.h}
  2879. Subsequent attempts to execute from memory with the specified protection
  2880. key will fault. At present only AArch64 platforms with enabled Stage 1
  2881. permission overlays feature support this type of restriction.
  2882. @end vtable
  2883. Operations not specified as flags are not restricted. In particular,
  2884. this means that the memory region will remain executable if it was
  2885. mapped with the @code{PROT_EXEC} protection flag and
  2886. @code{PKEY_DISABLE_ACCESS} has been specified.
  2887. Calling the @code{pkey_set} function with a protection key which was not
  2888. allocated by @code{pkey_alloc} results in undefined behavior. This
  2889. means that calling this function on systems which do not support memory
  2890. protection keys is undefined.
  2891. The @code{pkey_set} function returns @math{0} on success and @math{-1}
  2892. on failure.
  2893. The following @code{errno} error conditions are defined for this
  2894. function:
  2895. @table @code
  2896. @item EINVAL
  2897. The system does not support the access restrictions expressed in
  2898. the @var{access_restrictions} argument.
  2899. @end table
  2900. @end deftypefun
  2901. @deftypefun int pkey_get (int @var{key})
  2902. @standards{Linux, sys/mman.h}
  2903. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2904. Return the access restrictions of the current thread for memory pages
  2905. with protection key @var{key}. The return value is zero or a combination of
  2906. the @code{PKEY_DISABLE_}* flags; see the @code{pkey_set} function.
  2907. The returned value should be checked for presence or absence of specific flags
  2908. using bitwise operations. Comparing the returned value with any of the flags
  2909. or their combination using equals will almost certainly fail.
  2910. Calling the @code{pkey_get} function with a protection key which was not
  2911. allocated by @code{pkey_alloc} results in undefined behavior. This
  2912. means that calling this function on systems which do not support memory
  2913. protection keys is undefined.
  2914. @end deftypefun
  2915. @node Locking Pages
  2916. @section Locking Pages
  2917. @cindex locking pages
  2918. @cindex memory lock
  2919. @cindex paging
  2920. You can tell the system to associate a particular virtual memory page
  2921. with a real page frame and keep it that way --- i.e., cause the page to
  2922. be paged in if it isn't already and mark it so it will never be paged
  2923. out and consequently will never cause a page fault. This is called
  2924. @dfn{locking} a page.
  2925. The functions in this chapter lock and unlock the calling process'
  2926. pages.
  2927. @menu
  2928. * Why Lock Pages:: Reasons to read this section.
  2929. * Locked Memory Details:: Everything you need to know locked
  2930. memory
  2931. * Page Lock Functions:: Here's how to do it.
  2932. @end menu
  2933. @node Why Lock Pages
  2934. @subsection Why Lock Pages
  2935. Because page faults cause paged out pages to be paged in transparently,
  2936. a process rarely needs to be concerned about locking pages. However,
  2937. there are two reasons people sometimes are:
  2938. @itemize @bullet
  2939. @item
  2940. Speed. A page fault is transparent only insofar as the process is not
  2941. sensitive to how long it takes to do a simple memory access. Time-critical
  2942. processes, especially realtime processes, may not be able to wait or
  2943. may not be able to tolerate variance in execution speed.
  2944. @cindex realtime processing
  2945. @cindex speed of execution
  2946. A process that needs to lock pages for this reason probably also needs
  2947. priority among other processes for use of the CPU. @xref{Priority}.
  2948. In some cases, the programmer knows better than the system's demand
  2949. paging allocator which pages should remain in real memory to optimize
  2950. system performance. In this case, locking pages can help.
  2951. @item
  2952. Privacy. If you keep secrets in virtual memory and that virtual memory
  2953. gets paged out, that increases the chance that the secrets will get out.
  2954. If a passphrase gets written out to disk swap space, for example, it might
  2955. still be there long after virtual and real memory have been wiped clean.
  2956. @end itemize
  2957. Be aware that when you lock a page, that's one fewer page frame that can
  2958. be used to back other virtual memory (by the same or other processes),
  2959. which can mean more page faults, which means the system runs more
  2960. slowly. In fact, if you lock enough memory, some programs may not be
  2961. able to run at all for lack of real memory.
  2962. @node Locked Memory Details
  2963. @subsection Locked Memory Details
  2964. A memory lock is associated with a virtual page, not a real frame. The
  2965. paging rule is: If a frame backs at least one locked page, don't page it
  2966. out.
  2967. Memory locks do not stack. I.e., you can't lock a particular page twice
  2968. so that it has to be unlocked twice before it is truly unlocked. It is
  2969. either locked or it isn't.
  2970. A memory lock persists until the process that owns the memory explicitly
  2971. unlocks it. (But process termination and exec cause the virtual memory
  2972. to cease to exist, which you might say means it isn't locked any more).
  2973. Memory locks are not inherited by child processes. (But note that on a
  2974. modern Unix system, immediately after a fork, the parent's and the
  2975. child's virtual address space are backed by the same real page frames,
  2976. so the child enjoys the parent's locks). @xref{Creating a Process}.
  2977. Because of its ability to impact other processes, only the superuser can
  2978. lock a page. Any process can unlock its own page.
  2979. The system sets limits on the amount of memory a process can have locked
  2980. and the amount of real memory it can have dedicated to it. @xref{Limits
  2981. on Resources}.
  2982. In Linux, locked pages aren't as locked as you might think.
  2983. Two virtual pages that are not shared memory can nonetheless be backed
  2984. by the same real frame. The kernel does this in the name of efficiency
  2985. when it knows both virtual pages contain identical data, and does it
  2986. even if one or both of the virtual pages are locked.
  2987. But when a process modifies one of those pages, the kernel must get it a
  2988. separate frame and fill it with the page's data. This is known as a
  2989. @dfn{copy-on-write page fault}. It takes a small amount of time and in
  2990. a pathological case, getting that frame may require I/O.
  2991. @cindex copy-on-write page fault
  2992. @cindex page fault, copy-on-write
  2993. To make sure this doesn't happen to your program, don't just lock the
  2994. pages. Write to them as well, unless you know you won't write to them
  2995. ever. And to make sure you have pre-allocated frames for your stack,
  2996. enter a scope that declares a C automatic variable larger than the
  2997. maximum stack size you will need, set it to something, then return from
  2998. its scope.
  2999. @node Page Lock Functions
  3000. @subsection Functions To Lock And Unlock Pages
  3001. The symbols in this section are declared in @file{sys/mman.h}. These
  3002. functions are defined by POSIX.1b, but their availability depends on
  3003. your kernel. If your kernel doesn't allow these functions, they exist
  3004. but always fail. They @emph{are} available with a Linux kernel.
  3005. @strong{Portability Note:} POSIX.1b requires that when the @code{mlock}
  3006. and @code{munlock} functions are available, the file @file{unistd.h}
  3007. define the macro @code{_POSIX_MEMLOCK_RANGE} and the file
  3008. @code{limits.h} define the macro @code{PAGESIZE} to be the size of a
  3009. memory page in bytes. It requires that when the @code{mlockall} and
  3010. @code{munlockall} functions are available, the @file{unistd.h} file
  3011. define the macro @code{_POSIX_MEMLOCK}. @Theglibc{} conforms to
  3012. this requirement.
  3013. @deftypefun int mlock (const void *@var{addr}, size_t @var{len})
  3014. @standards{POSIX.1b, sys/mman.h}
  3015. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  3016. @code{mlock} locks a range of the calling process' virtual pages.
  3017. The range of memory starts at address @var{addr} and is @var{len} bytes
  3018. long. Actually, since you must lock whole pages, it is the range of
  3019. pages that include any part of the specified range.
  3020. When the function returns successfully, each of those pages is backed by
  3021. (connected to) a real frame (is resident) and is marked to stay that
  3022. way. This means the function may cause page-ins and have to wait for
  3023. them.
  3024. When the function fails, it does not affect the lock status of any
  3025. pages.
  3026. The return value is zero if the function succeeds. Otherwise, it is
  3027. @code{-1} and @code{errno} is set accordingly. @code{errno} values
  3028. specific to this function are:
  3029. @table @code
  3030. @item ENOMEM
  3031. @itemize @bullet
  3032. @item
  3033. At least some of the specified address range does not exist in the
  3034. calling process' virtual address space.
  3035. @item
  3036. The locking would cause the process to exceed its locked page limit.
  3037. @end itemize
  3038. @item EPERM
  3039. The calling process is not superuser.
  3040. @item EINVAL
  3041. @var{len} is not positive.
  3042. @item ENOSYS
  3043. The kernel does not provide @code{mlock} capability.
  3044. @end table
  3045. @end deftypefun
  3046. @deftypefun int mlock2 (const void *@var{addr}, size_t @var{len}, unsigned int @var{flags})
  3047. @standards{Linux, sys/mman.h}
  3048. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  3049. This function is similar to @code{mlock}. If @var{flags} is zero, a
  3050. call to @code{mlock2} behaves exactly as the equivalent call to @code{mlock}.
  3051. The @var{flags} argument must be a combination of zero or more of the
  3052. following flags:
  3053. @vtable @code
  3054. @item MLOCK_ONFAULT
  3055. @standards{Linux, sys/mman.h}
  3056. Only those pages in the specified address range which are already in
  3057. memory are locked immediately. Additional pages in the range are
  3058. automatically locked in case of a page fault and allocation of memory.
  3059. @end vtable
  3060. Like @code{mlock}, @code{mlock2} returns zero on success and @code{-1}
  3061. on failure, setting @code{errno} accordingly. Additional @code{errno}
  3062. values defined for @code{mlock2} are:
  3063. @table @code
  3064. @item EINVAL
  3065. The specified (non-zero) @var{flags} argument is not supported by this
  3066. system.
  3067. @end table
  3068. @end deftypefun
  3069. You can lock @emph{all} a process' memory with @code{mlockall}. You
  3070. unlock memory with @code{munlock} or @code{munlockall}.
  3071. To avoid all page faults in a C program, you have to use
  3072. @code{mlockall}, because some of the memory a program uses is hidden
  3073. from the C code, e.g. the stack and automatic variables, and you
  3074. wouldn't know what address to tell @code{mlock}.
  3075. @deftypefun int munlock (const void *@var{addr}, size_t @var{len})
  3076. @standards{POSIX.1b, sys/mman.h}
  3077. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  3078. @code{munlock} unlocks a range of the calling process' virtual pages.
  3079. @code{munlock} is the inverse of @code{mlock} and functions completely
  3080. analogously to @code{mlock}, except that there is no @code{EPERM}
  3081. failure.
  3082. @end deftypefun
  3083. @deftypefun int mlockall (int @var{flags})
  3084. @standards{POSIX.1b, sys/mman.h}
  3085. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  3086. @code{mlockall} locks all the pages in a process' virtual memory address
  3087. space, and/or any that are added to it in the future. This includes the
  3088. pages of the code, data and stack segment, as well as shared libraries,
  3089. user space kernel data, shared memory, and memory mapped files.
  3090. @var{flags} is a string of single bit flags represented by the following
  3091. macros. They tell @code{mlockall} which of its functions you want. All
  3092. other bits must be zero.
  3093. @vtable @code
  3094. @item MCL_CURRENT
  3095. Lock all pages which currently exist in the calling process' virtual
  3096. address space.
  3097. @item MCL_FUTURE
  3098. Set a mode such that any pages added to the process' virtual address
  3099. space in the future will be locked from birth. This mode does not
  3100. affect future address spaces owned by the same process so exec, which
  3101. replaces a process' address space, wipes out @code{MCL_FUTURE}.
  3102. @xref{Executing a File}.
  3103. @end vtable
  3104. When the function returns successfully, and you specified
  3105. @code{MCL_CURRENT}, all of the process' pages are backed by (connected
  3106. to) real frames (they are resident) and are marked to stay that way.
  3107. This means the function may cause page-ins and have to wait for them.
  3108. When the process is in @code{MCL_FUTURE} mode because it successfully
  3109. executed this function and specified @code{MCL_CURRENT}, any system call
  3110. by the process that requires space be added to its virtual address space
  3111. fails with @code{errno} = @code{ENOMEM} if locking the additional space
  3112. would cause the process to exceed its locked page limit. In the case
  3113. that the address space addition that can't be accommodated is stack
  3114. expansion, the stack expansion fails and the kernel sends a
  3115. @code{SIGSEGV} signal to the process.
  3116. When the function fails, it does not affect the lock status of any pages
  3117. or the future locking mode.
  3118. The return value is zero if the function succeeds. Otherwise, it is
  3119. @code{-1} and @code{errno} is set accordingly. @code{errno} values
  3120. specific to this function are:
  3121. @table @code
  3122. @item ENOMEM
  3123. @itemize @bullet
  3124. @item
  3125. At least some of the specified address range does not exist in the
  3126. calling process' virtual address space.
  3127. @item
  3128. The locking would cause the process to exceed its locked page limit.
  3129. @end itemize
  3130. @item EPERM
  3131. The calling process is not superuser.
  3132. @item EINVAL
  3133. Undefined bits in @var{flags} are not zero.
  3134. @item ENOSYS
  3135. The kernel does not provide @code{mlockall} capability.
  3136. @end table
  3137. You can lock just specific pages with @code{mlock}. You unlock pages
  3138. with @code{munlockall} and @code{munlock}.
  3139. @end deftypefun
  3140. @deftypefun int munlockall (void)
  3141. @standards{POSIX.1b, sys/mman.h}
  3142. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  3143. @code{munlockall} unlocks every page in the calling process' virtual
  3144. address space and turns off @code{MCL_FUTURE} future locking mode.
  3145. The return value is zero if the function succeeds. Otherwise, it is
  3146. @code{-1} and @code{errno} is set accordingly. The only way this
  3147. function can fail is for generic reasons that all functions and system
  3148. calls can fail, so there are no specific @code{errno} values.
  3149. @end deftypefun
  3150. @ignore
  3151. @c This was never actually implemented. -zw
  3152. @node Relocating Allocator
  3153. @section Relocating Allocator
  3154. @cindex relocating memory allocator
  3155. Any system of dynamic memory allocation has overhead: the amount of
  3156. space it uses is more than the amount the program asks for. The
  3157. @dfn{relocating memory allocator} achieves very low overhead by moving
  3158. blocks in memory as necessary, on its own initiative.
  3159. @c @menu
  3160. @c * Relocator Concepts:: How to understand relocating allocation.
  3161. @c * Using Relocator:: Functions for relocating allocation.
  3162. @c @end menu
  3163. @node Relocator Concepts
  3164. @subsection Concepts of Relocating Allocation
  3165. @ifinfo
  3166. The @dfn{relocating memory allocator} achieves very low overhead by
  3167. moving blocks in memory as necessary, on its own initiative.
  3168. @end ifinfo
  3169. When you allocate a block with @code{malloc}, the address of the block
  3170. never changes unless you use @code{realloc} to change its size. Thus,
  3171. you can safely store the address in various places, temporarily or
  3172. permanently, as you like. This is not safe when you use the relocating
  3173. memory allocator, because any and all relocatable blocks can move
  3174. whenever you allocate memory in any fashion. Even calling @code{malloc}
  3175. or @code{realloc} can move the relocatable blocks.
  3176. @cindex handle
  3177. For each relocatable block, you must make a @dfn{handle}---a pointer
  3178. object in memory, designated to store the address of that block. The
  3179. relocating allocator knows where each block's handle is, and updates the
  3180. address stored there whenever it moves the block, so that the handle
  3181. always points to the block. Each time you access the contents of the
  3182. block, you should fetch its address anew from the handle.
  3183. To call any of the relocating allocator functions from a signal handler
  3184. is almost certainly incorrect, because the signal could happen at any
  3185. time and relocate all the blocks. The only way to make this safe is to
  3186. block the signal around any access to the contents of any relocatable
  3187. block---not a convenient mode of operation. @xref{Nonreentrancy}.
  3188. @node Using Relocator
  3189. @subsection Allocating and Freeing Relocatable Blocks
  3190. @pindex malloc.h
  3191. In the descriptions below, @var{handleptr} designates the address of the
  3192. handle. All the functions are declared in @file{malloc.h}; all are GNU
  3193. extensions.
  3194. @comment malloc.h
  3195. @comment GNU
  3196. @c @deftypefun {void *} r_alloc (void **@var{handleptr}, size_t @var{size})
  3197. This function allocates a relocatable block of size @var{size}. It
  3198. stores the block's address in @code{*@var{handleptr}} and returns
  3199. a non-null pointer to indicate success.
  3200. If @code{r_alloc} can't get the space needed, it stores a null pointer
  3201. in @code{*@var{handleptr}}, and returns a null pointer.
  3202. @end deftypefun
  3203. @comment malloc.h
  3204. @comment GNU
  3205. @c @deftypefun void r_alloc_free (void **@var{handleptr})
  3206. This function is the way to free a relocatable block. It frees the
  3207. block that @code{*@var{handleptr}} points to, and stores a null pointer
  3208. in @code{*@var{handleptr}} to show it doesn't point to an allocated
  3209. block any more.
  3210. @end deftypefun
  3211. @comment malloc.h
  3212. @comment GNU
  3213. @c @deftypefun {void *} r_re_alloc (void **@var{handleptr}, size_t @var{size})
  3214. The function @code{r_re_alloc} adjusts the size of the block that
  3215. @code{*@var{handleptr}} points to, making it @var{size} bytes long. It
  3216. stores the address of the resized block in @code{*@var{handleptr}} and
  3217. returns a non-null pointer to indicate success.
  3218. If enough memory is not available, this function returns a null pointer
  3219. and does not modify @code{*@var{handleptr}}.
  3220. @end deftypefun
  3221. @end ignore
  3222. @ignore
  3223. @comment No longer available...
  3224. @comment @node Memory Warnings
  3225. @comment @section Memory Usage Warnings
  3226. @comment @cindex memory usage warnings
  3227. @comment @cindex warnings of memory almost full
  3228. @pindex malloc.c
  3229. You can ask for warnings as the program approaches running out of memory
  3230. space, by calling @code{memory_warnings}. This tells @code{malloc} to
  3231. check memory usage every time it asks for more memory from the operating
  3232. system. This is a GNU extension declared in @file{malloc.h}.
  3233. @comment malloc.h
  3234. @comment GNU
  3235. @comment @deftypefun void memory_warnings (void *@var{start}, void (*@var{warn-func}) (const char *))
  3236. Call this function to request warnings for nearing exhaustion of virtual
  3237. memory.
  3238. The argument @var{start} says where data space begins, in memory. The
  3239. allocator compares this against the last address used and against the
  3240. limit of data space, to determine the fraction of available memory in
  3241. use. If you supply zero for @var{start}, then a default value is used
  3242. which is right in most circumstances.
  3243. For @var{warn-func}, supply a function that @code{malloc} can call to
  3244. warn you. It is called with a string (a warning message) as argument.
  3245. Normally it ought to display the string for the user to read.
  3246. @end deftypefun
  3247. The warnings come when memory becomes 75% full, when it becomes 85%
  3248. full, and when it becomes 95% full. Above 95% you get another warning
  3249. each time memory usage increases.
  3250. @end ignore