memory.texi 148 KB

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