intro.texi 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505
  1. @node Introduction, Error Reporting, Top, Top
  2. @chapter Introduction
  3. @c %MENU% Purpose of the GNU C Library
  4. The C language provides no built-in facilities for performing such
  5. common operations as input/output, memory management, string
  6. manipulation, and the like. Instead, these facilities are defined
  7. in a standard @dfn{library}, which you compile and link with your
  8. programs.
  9. @cindex library
  10. @Theglibc{}, described in this document, defines all of the
  11. library functions that are specified by the @w{ISO C} standard, as well as
  12. additional features specific to POSIX and other derivatives of the Unix
  13. operating system, and extensions specific to @gnusystems{}.
  14. The purpose of this manual is to tell you how to use the facilities
  15. of @theglibc{}. We have mentioned which features belong to which
  16. standards to help you identify things that are potentially non-portable
  17. to other systems. But the emphasis in this manual is not on strict
  18. portability.
  19. @menu
  20. * Getting Started:: What this manual is for and how to use it.
  21. * Standards and Portability:: Standards and sources upon which the GNU
  22. C library is based.
  23. * Using the Library:: Some practical uses for the library.
  24. * Roadmap to the Manual:: Overview of the remaining chapters in
  25. this manual.
  26. @end menu
  27. @node Getting Started, Standards and Portability, , Introduction
  28. @section Getting Started
  29. This manual is written with the assumption that you are at least
  30. somewhat familiar with the C programming language and basic programming
  31. concepts. Specifically, familiarity with ISO standard C
  32. (@pxref{ISO C}), rather than ``traditional'' pre-ISO C dialects, is
  33. assumed.
  34. @Theglibc{} includes several @dfn{header files}, each of which
  35. provides definitions and declarations for a group of related facilities;
  36. this information is used by the C compiler when processing your program.
  37. For example, the header file @file{stdio.h} declares facilities for
  38. performing input and output, and the header file @file{string.h}
  39. declares string processing utilities. The organization of this manual
  40. generally follows the same division as the header files.
  41. If you are reading this manual for the first time, you should read all
  42. of the introductory material and skim the remaining chapters. There are
  43. a @emph{lot} of functions in @theglibc{} and it's not realistic to
  44. expect that you will be able to remember exactly @emph{how} to use each
  45. and every one of them. It's more important to become generally familiar
  46. with the kinds of facilities that the library provides, so that when you
  47. are writing your programs you can recognize @emph{when} to make use of
  48. library functions, and @emph{where} in this manual you can find more
  49. specific information about them.
  50. @node Standards and Portability, Using the Library, Getting Started, Introduction
  51. @section Standards and Portability
  52. @cindex standards
  53. This section discusses the various standards and other sources that @theglibc{}
  54. is based upon. These sources include the @w{ISO C} and
  55. POSIX standards, and the System V and Berkeley Unix implementations.
  56. The primary focus of this manual is to tell you how to make effective
  57. use of the @glibcadj{} facilities. But if you are concerned about
  58. making your programs compatible with these standards, or portable to
  59. operating systems other than GNU, this can affect how you use the
  60. library. This section gives you an overview of these standards, so that
  61. you will know what they are when they are mentioned in other parts of
  62. the manual.
  63. @xref{Library Summary}, for an alphabetical list of the functions and
  64. other symbols provided by the library. This list also states which
  65. standards each function or symbol comes from.
  66. @menu
  67. * ISO C:: The international standard for the C
  68. programming language.
  69. * POSIX:: The ISO/IEC 9945 (aka IEEE 1003) standards
  70. for operating systems.
  71. * Berkeley Unix:: BSD and SunOS.
  72. * SVID:: The System V Interface Description.
  73. * XPG:: The X/Open Portability Guide.
  74. @end menu
  75. @node ISO C, POSIX, , Standards and Portability
  76. @subsection ISO C
  77. @cindex ISO C
  78. @Theglibc{} is compatible with the C standard adopted by the
  79. American National Standards Institute (ANSI):
  80. @cite{American National Standard X3.159-1989---``ANSI C''} and later
  81. by the International Standardization Organization (ISO):
  82. @cite{ISO/IEC 9899:1990, ``Programming languages---C''}.
  83. We here refer to the standard as @w{ISO C} since this is the more
  84. general standard in respect of ratification.
  85. The header files and library facilities that make up @theglibc{} are
  86. a superset of those specified by the @w{ISO C} standard.@refill
  87. @pindex gcc
  88. If you are concerned about strict adherence to the @w{ISO C} standard, you
  89. should use the @samp{-ansi} option when you compile your programs with
  90. the GNU C compiler. This tells the compiler to define @emph{only} ISO
  91. standard features from the library header files, unless you explicitly
  92. ask for additional features. @xref{Feature Test Macros}, for
  93. information on how to do this.
  94. Being able to restrict the library to include only @w{ISO C} features is
  95. important because @w{ISO C} puts limitations on what names can be defined
  96. by the library implementation, and the GNU extensions don't fit these
  97. limitations. @xref{Reserved Names}, for more information about these
  98. restrictions.
  99. This manual does not attempt to give you complete details on the
  100. differences between @w{ISO C} and older dialects. It gives advice on how
  101. to write programs to work portably under multiple C dialects, but does
  102. not aim for completeness.
  103. @node POSIX, Berkeley Unix, ISO C, Standards and Portability
  104. @subsection POSIX (The Portable Operating System Interface)
  105. @cindex POSIX
  106. @cindex POSIX.1
  107. @cindex IEEE Std 1003.1
  108. @cindex ISO/IEC 9945-1
  109. @cindex POSIX.2
  110. @cindex IEEE Std 1003.2
  111. @cindex ISO/IEC 9945-2
  112. @Theglibc{} is also compatible with the ISO @dfn{POSIX} family of
  113. standards, known more formally as the @dfn{Portable Operating System
  114. Interface for Computer Environments} (ISO/IEC 9945). They were also
  115. published as ANSI/IEEE Std 1003. POSIX is derived mostly from various
  116. versions of the Unix operating system.
  117. The library facilities specified by the POSIX standards are a superset
  118. of those required by @w{ISO C}; POSIX specifies additional features for
  119. @w{ISO C} functions, as well as specifying new additional functions. In
  120. general, the additional requirements and functionality defined by the
  121. POSIX standards are aimed at providing lower-level support for a
  122. particular kind of operating system environment, rather than general
  123. programming language support which can run in many diverse operating
  124. system environments.@refill
  125. @Theglibc{} implements all of the functions specified in
  126. @cite{ISO/IEC 9945-1:1996, the POSIX System Application Program
  127. Interface}, commonly referred to as POSIX.1. The primary extensions to
  128. the @w{ISO C} facilities specified by this standard include file system
  129. interface primitives (@pxref{File System Interface}), device-specific
  130. terminal control functions (@pxref{Low-Level Terminal Interface}), and
  131. process control functions (@pxref{Processes}).
  132. Some facilities from @cite{ISO/IEC 9945-2:1993, the POSIX Shell and
  133. Utilities standard} (POSIX.2) are also implemented in @theglibc{}.
  134. These include utilities for dealing with regular expressions and other
  135. pattern matching facilities (@pxref{Pattern Matching}).
  136. @menu
  137. * POSIX Safety Concepts:: Safety concepts from POSIX.
  138. * Unsafe Features:: Features that make functions unsafe.
  139. * Conditionally Safe Features:: Features that make functions unsafe
  140. in the absence of workarounds.
  141. * Other Safety Remarks:: Additional safety features and remarks.
  142. @end menu
  143. @comment Roland sez:
  144. @comment The GNU C library as it stands conforms to 1003.2 draft 11, which
  145. @comment specifies:
  146. @comment
  147. @comment Several new macros in <limits.h>.
  148. @comment popen, pclose
  149. @comment <regex.h> (which is not yet fully implemented--wait on this)
  150. @comment fnmatch
  151. @comment getopt
  152. @comment <glob.h>
  153. @comment <wordexp.h> (not yet implemented)
  154. @comment confstr
  155. @node POSIX Safety Concepts, Unsafe Features, , POSIX
  156. @subsubsection POSIX Safety Concepts
  157. @cindex POSIX Safety Concepts
  158. This manual documents various safety properties of @glibcadj{}
  159. functions, in lines that follow their prototypes and look like:
  160. @sampsafety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  161. The properties are assessed according to the criteria set forth in the
  162. POSIX standard for such safety contexts as Thread-, Async-Signal- and
  163. Async-Cancel- -Safety. Intuitive definitions of these properties,
  164. attempting to capture the meaning of the standard definitions, follow.
  165. @itemize @bullet
  166. @item
  167. @cindex MT-Safe
  168. @cindex Thread-Safe
  169. @code{MT-Safe} or Thread-Safe functions are safe to call in the presence
  170. of other threads. MT, in MT-Safe, stands for Multi Thread.
  171. Being MT-Safe does not imply a function is atomic, nor that it uses any
  172. of the memory synchronization mechanisms POSIX exposes to users. It is
  173. even possible that calling MT-Safe functions in sequence does not yield
  174. an MT-Safe combination. For example, having a thread call two MT-Safe
  175. functions one right after the other does not guarantee behavior
  176. equivalent to atomic execution of a combination of both functions, since
  177. concurrent calls in other threads may interfere in a destructive way.
  178. Whole-program optimizations that could inline functions across library
  179. interfaces may expose unsafe reordering, and so performing inlining
  180. across the @glibcadj{} interface is not recommended. The documented
  181. MT-Safety status is not guaranteed under whole-program optimization.
  182. However, functions defined in user-visible headers are designed to be
  183. safe for inlining.
  184. @item
  185. @cindex AS-Safe
  186. @cindex Async-Signal-Safe
  187. @code{AS-Safe} or Async-Signal-Safe functions are safe to call from
  188. asynchronous signal handlers. AS, in AS-Safe, stands for Asynchronous
  189. Signal.
  190. Many functions that are AS-Safe may set @code{errno}, or modify the
  191. floating-point environment, because their doing so does not make them
  192. unsuitable for use in signal handlers. However, programs could
  193. misbehave should asynchronous signal handlers modify this thread-local
  194. state, and the signal handling machinery cannot be counted on to
  195. preserve it. Therefore, signal handlers that call functions that may
  196. set @code{errno} or modify the floating-point environment @emph{must}
  197. save their original values, and restore them before returning.
  198. @item
  199. @cindex AC-Safe
  200. @cindex Async-Cancel-Safe
  201. @code{AC-Safe} or Async-Cancel-Safe functions are safe to call when
  202. asynchronous cancellation is enabled. AC in AC-Safe stands for
  203. Asynchronous Cancellation.
  204. The POSIX standard defines only three functions to be AC-Safe, namely
  205. @code{pthread_cancel}, @code{pthread_setcancelstate}, and
  206. @code{pthread_setcanceltype}. At present @theglibc{} provides no
  207. guarantees beyond these three functions, but does document which
  208. functions are presently AC-Safe. This documentation is provided for use
  209. by @theglibc{} developers.
  210. Just like signal handlers, cancellation cleanup routines must configure
  211. the floating point environment they require. The routines cannot assume
  212. a floating point environment, particularly when asynchronous
  213. cancellation is enabled. If the configuration of the floating point
  214. environment cannot be performed atomically then it is also possible that
  215. the environment encountered is internally inconsistent.
  216. @item
  217. @cindex MT-Unsafe
  218. @cindex Thread-Unsafe
  219. @cindex AS-Unsafe
  220. @cindex Async-Signal-Unsafe
  221. @cindex AC-Unsafe
  222. @cindex Async-Cancel-Unsafe
  223. @code{MT-Unsafe}, @code{AS-Unsafe}, @code{AC-Unsafe} functions are not
  224. safe to call within the safety contexts described above. Calling them
  225. within such contexts invokes undefined behavior.
  226. Functions not explicitly documented as safe in a safety context should
  227. be regarded as Unsafe.
  228. @item
  229. @cindex Preliminary
  230. @code{Preliminary} safety properties are documented, indicating these
  231. properties may @emph{not} be counted on in future releases of
  232. @theglibc{}.
  233. Such preliminary properties are the result of an assessment of the
  234. properties of our current implementation, rather than of what is
  235. mandated and permitted by current and future standards.
  236. Although we strive to abide by the standards, in some cases our
  237. implementation is safe even when the standard does not demand safety,
  238. and in other cases our implementation does not meet the standard safety
  239. requirements. The latter are most likely bugs; the former, when marked
  240. as @code{Preliminary}, should not be counted on: future standards may
  241. require changes that are not compatible with the additional safety
  242. properties afforded by the current implementation.
  243. Furthermore, the POSIX standard does not offer a detailed definition of
  244. safety. We assume that, by ``safe to call'', POSIX means that, as long
  245. as the program does not invoke undefined behavior, the ``safe to call''
  246. function behaves as specified, and does not cause other functions to
  247. deviate from their specified behavior. We have chosen to use its loose
  248. definitions of safety, not because they are the best definitions to use,
  249. but because choosing them harmonizes this manual with POSIX.
  250. Please keep in mind that these are preliminary definitions and
  251. annotations, and certain aspects of the definitions are still under
  252. discussion and might be subject to clarification or change.
  253. Over time, we envision evolving the preliminary safety notes into stable
  254. commitments, as stable as those of our interfaces. As we do, we will
  255. remove the @code{Preliminary} keyword from safety notes. As long as the
  256. keyword remains, however, they are not to be regarded as a promise of
  257. future behavior.
  258. @end itemize
  259. Other keywords that appear in safety notes are defined in subsequent
  260. sections.
  261. @node Unsafe Features, Conditionally Safe Features, POSIX Safety Concepts, POSIX
  262. @subsubsection Unsafe Features
  263. @cindex Unsafe Features
  264. Functions that are unsafe to call in certain contexts are annotated with
  265. keywords that document their features that make them unsafe to call.
  266. AS-Unsafe features in this section indicate the functions are never safe
  267. to call when asynchronous signals are enabled. AC-Unsafe features
  268. indicate they are never safe to call when asynchronous cancellation is
  269. enabled. There are no MT-Unsafe marks in this section.
  270. @itemize @bullet
  271. @item @code{lock}
  272. @cindex lock
  273. Functions marked with @code{lock} as an AS-Unsafe feature may be
  274. interrupted by a signal while holding a non-recursive lock. If the
  275. signal handler calls another such function that takes the same lock, the
  276. result is a deadlock.
  277. Functions annotated with @code{lock} as an AC-Unsafe feature may, if
  278. cancelled asynchronously, fail to release a lock that would have been
  279. released if their execution had not been interrupted by asynchronous
  280. thread cancellation. Once a lock is left taken, attempts to take that
  281. lock will block indefinitely.
  282. @item @code{corrupt}
  283. @cindex corrupt
  284. Functions marked with @code{corrupt} as an AS-Unsafe feature may corrupt
  285. data structures and misbehave when they interrupt, or are interrupted
  286. by, another such function. Unlike functions marked with @code{lock},
  287. these take recursive locks to avoid MT-Safety problems, but this is not
  288. enough to stop a signal handler from observing a partially-updated data
  289. structure. Further corruption may arise from the interrupted function's
  290. failure to notice updates made by signal handlers.
  291. Functions marked with @code{corrupt} as an AC-Unsafe feature may leave
  292. data structures in a corrupt, partially updated state. Subsequent uses
  293. of the data structure may misbehave.
  294. @c A special case, probably not worth documenting separately, involves
  295. @c reallocing, or even freeing pointers. Any case involving free could
  296. @c be easily turned into an ac-safe leak by resetting the pointer before
  297. @c releasing it; I don't think we have any case that calls for this sort
  298. @c of fixing. Fixing the realloc cases would require a new interface:
  299. @c instead of @code{ptr=realloc(ptr,size)} we'd have to introduce
  300. @c @code{acsafe_realloc(&ptr,size)} that would modify ptr before
  301. @c releasing the old memory. The ac-unsafe realloc could be implemented
  302. @c in terms of an internal interface with this semantics (say
  303. @c __acsafe_realloc), but since realloc can be overridden, the function
  304. @c we call to implement realloc should not be this internal interface,
  305. @c but another internal interface that calls __acsafe_realloc if realloc
  306. @c was not overridden, and calls the overridden realloc with async
  307. @c cancel disabled. --lxoliva
  308. @item @code{heap}
  309. @cindex heap
  310. Functions marked with @code{heap} may call heap memory management
  311. functions from the @code{malloc}/@code{free} family of functions and are
  312. only as safe as those functions. This note is thus equivalent to:
  313. @sampsafety{@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
  314. @c Check for cases that should have used plugin instead of or in
  315. @c addition to this. Then, after rechecking gettext, adjust i18n if
  316. @c needed.
  317. @item @code{dlopen}
  318. @cindex dlopen
  319. Functions marked with @code{dlopen} use the dynamic loader to load
  320. shared libraries into the current execution image. This involves
  321. opening files, mapping them into memory, allocating additional memory,
  322. resolving symbols, applying relocations and more, all of this while
  323. holding internal dynamic loader locks.
  324. The locks are enough for these functions to be AS- and AC-Unsafe, but
  325. other issues may arise. At present this is a placeholder for all
  326. potential safety issues raised by @code{dlopen}.
  327. @c dlopen runs init and fini sections of the module; does this mean
  328. @c dlopen always implies plugin?
  329. @item @code{plugin}
  330. @cindex plugin
  331. Functions annotated with @code{plugin} may run code from plugins that
  332. may be external to @theglibc{}. Such plugin functions are assumed to be
  333. MT-Safe, AS-Unsafe and AC-Unsafe. Examples of such plugins are stack
  334. @cindex NSS
  335. unwinding libraries, name service switch (NSS) and character set
  336. @cindex iconv
  337. conversion (iconv) back-ends.
  338. Although the plugins mentioned as examples are all brought in by means
  339. of dlopen, the @code{plugin} keyword does not imply any direct
  340. involvement of the dynamic loader or the @code{libdl} interfaces, those
  341. are covered by @code{dlopen}. For example, if one function loads a
  342. module and finds the addresses of some of its functions, while another
  343. just calls those already-resolved functions, the former will be marked
  344. with @code{dlopen}, whereas the latter will get the @code{plugin}. When
  345. a single function takes all of these actions, then it gets both marks.
  346. @item @code{i18n}
  347. @cindex i18n
  348. Functions marked with @code{i18n} may call internationalization
  349. functions of the @code{gettext} family and will be only as safe as those
  350. functions. This note is thus equivalent to:
  351. @sampsafety{@mtsafe{@mtsenv{}}@asunsafe{@asucorrupt{} @ascuheap{} @ascudlopen{}}@acunsafe{@acucorrupt{}}}
  352. @item @code{timer}
  353. @cindex timer
  354. Functions marked with @code{timer} use the @code{alarm} function or
  355. similar to set a time-out for a system call or a long-running operation.
  356. In a multi-threaded program, there is a risk that the time-out signal
  357. will be delivered to a different thread, thus failing to interrupt the
  358. intended thread. Besides being MT-Unsafe, such functions are always
  359. AS-Unsafe, because calling them in signal handlers may interfere with
  360. timers set in the interrupted code, and AC-Unsafe, because there is no
  361. safe way to guarantee an earlier timer will be reset in case of
  362. asynchronous cancellation.
  363. @end itemize
  364. @node Conditionally Safe Features, Other Safety Remarks, Unsafe Features, POSIX
  365. @subsubsection Conditionally Safe Features
  366. @cindex Conditionally Safe Features
  367. For some features that make functions unsafe to call in certain
  368. contexts, there are known ways to avoid the safety problem other than
  369. refraining from calling the function altogether. The keywords that
  370. follow refer to such features, and each of their definitions indicate
  371. how the whole program needs to be constrained in order to remove the
  372. safety problem indicated by the keyword. Only when all the reasons that
  373. make a function unsafe are observed and addressed, by applying the
  374. documented constraints, does the function become safe to call in a
  375. context.
  376. @itemize @bullet
  377. @item @code{init}
  378. @cindex init
  379. Functions marked with @code{init} as an MT-Unsafe feature perform
  380. MT-Unsafe initialization when they are first called.
  381. Calling such a function at least once in single-threaded mode removes
  382. this specific cause for the function to be regarded as MT-Unsafe. If no
  383. other cause for that remains, the function can then be safely called
  384. after other threads are started.
  385. Functions marked with @code{init} as an AS- or AC-Unsafe feature use the
  386. internal @code{libc_once} machinery or similar to initialize internal
  387. data structures.
  388. If a signal handler interrupts such an initializer, and calls any
  389. function that also performs @code{libc_once} initialization, it will
  390. deadlock if the thread library has been loaded.
  391. Furthermore, if an initializer is partially complete before it is
  392. canceled or interrupted by a signal whose handler requires the same
  393. initialization, some or all of the initialization may be performed more
  394. than once, leaking resources or even resulting in corrupt internal data.
  395. Applications that need to call functions marked with @code{init} as an
  396. AS- or AC-Unsafe feature should ensure the initialization is performed
  397. before configuring signal handlers or enabling cancellation, so that the
  398. AS- and AC-Safety issues related with @code{libc_once} do not arise.
  399. @c We may have to extend the annotations to cover conditions in which
  400. @c initialization may or may not occur, since an initial call in a safe
  401. @c context is no use if the initialization doesn't take place at that
  402. @c time: it doesn't remove the risk for later calls.
  403. @item @code{race}
  404. @cindex race
  405. Functions annotated with @code{race} as an MT-Safety issue operate on
  406. objects in ways that may cause data races or similar forms of
  407. destructive interference out of concurrent execution. In some cases,
  408. the objects are passed to the functions by users; in others, they are
  409. used by the functions to return values to users; in others, they are not
  410. even exposed to users.
  411. We consider access to objects passed as (indirect) arguments to
  412. functions to be data race free. The assurance of data race free objects
  413. is the caller's responsibility. We will not mark a function as
  414. MT-Unsafe or AS-Unsafe if it misbehaves when users fail to take the
  415. measures required by POSIX to avoid data races when dealing with such
  416. objects. As a general rule, if a function is documented as reading from
  417. an object passed (by reference) to it, or modifying it, users ought to
  418. use memory synchronization primitives to avoid data races just as they
  419. would should they perform the accesses themselves rather than by calling
  420. the library function. @code{FILE} streams are the exception to the
  421. general rule, in that POSIX mandates the library to guard against data
  422. races in many functions that manipulate objects of this specific opaque
  423. type. We regard this as a convenience provided to users, rather than as
  424. a general requirement whose expectations should extend to other types.
  425. In order to remind users that guarding certain arguments is their
  426. responsibility, we will annotate functions that take objects of certain
  427. types as arguments. We draw the line for objects passed by users as
  428. follows: objects whose types are exposed to users, and that users are
  429. expected to access directly, such as memory buffers, strings, and
  430. various user-visible @code{struct} types, do @emph{not} give reason for
  431. functions to be annotated with @code{race}. It would be noisy and
  432. redundant with the general requirement, and not many would be surprised
  433. by the library's lack of internal guards when accessing objects that can
  434. be accessed directly by users.
  435. As for objects that are opaque or opaque-like, in that they are to be
  436. manipulated only by passing them to library functions (e.g.,
  437. @code{FILE}, @code{DIR}, @code{obstack}, @code{iconv_t}), there might be
  438. additional expectations as to internal coordination of access by the
  439. library. We will annotate, with @code{race} followed by a colon and the
  440. argument name, functions that take such objects but that do not take
  441. care of synchronizing access to them by default. For example,
  442. @code{FILE} stream @code{unlocked} functions will be annotated, but
  443. those that perform implicit locking on @code{FILE} streams by default
  444. will not, even though the implicit locking may be disabled on a
  445. per-stream basis.
  446. In either case, we will not regard as MT-Unsafe functions that may
  447. access user-supplied objects in unsafe ways should users fail to ensure
  448. the accesses are well defined. The notion prevails that users are
  449. expected to safeguard against data races any user-supplied objects that
  450. the library accesses on their behalf.
  451. @c The above describes @mtsrace; @mtasurace is described below.
  452. This user responsibility does not apply, however, to objects controlled
  453. by the library itself, such as internal objects and static buffers used
  454. to return values from certain calls. When the library doesn't guard
  455. them against concurrent uses, these cases are regarded as MT-Unsafe and
  456. AS-Unsafe (although the @code{race} mark under AS-Unsafe will be omitted
  457. as redundant with the one under MT-Unsafe). As in the case of
  458. user-exposed objects, the mark may be followed by a colon and an
  459. identifier. The identifier groups all functions that operate on a
  460. certain unguarded object; users may avoid the MT-Safety issues related
  461. with unguarded concurrent access to such internal objects by creating a
  462. non-recursive mutex related with the identifier, and always holding the
  463. mutex when calling any function marked as racy on that identifier, as
  464. they would have to should the identifier be an object under user
  465. control. The non-recursive mutex avoids the MT-Safety issue, but it
  466. trades one AS-Safety issue for another, so use in asynchronous signals
  467. remains undefined.
  468. When the identifier relates to a static buffer used to hold return
  469. values, the mutex must be held for as long as the buffer remains in use
  470. by the caller. Many functions that return pointers to static buffers
  471. offer reentrant variants that store return values in caller-supplied
  472. buffers instead. In some cases, such as @code{tmpname}, the variant is
  473. chosen not by calling an alternate entry point, but by passing a
  474. non-@code{NULL} pointer to the buffer in which the returned values are
  475. to be stored. These variants are generally preferable in multi-threaded
  476. programs, although some of them are not MT-Safe because of other
  477. internal buffers, also documented with @code{race} notes.
  478. @item @code{const}
  479. @cindex const
  480. Functions marked with @code{const} as an MT-Safety issue non-atomically
  481. modify internal objects that are better regarded as constant, because a
  482. substantial portion of @theglibc{} accesses them without
  483. synchronization. Unlike @code{race}, that causes both readers and
  484. writers of internal objects to be regarded as MT-Unsafe and AS-Unsafe,
  485. this mark is applied to writers only. Writers remain equally MT- and
  486. AS-Unsafe to call, but the then-mandatory constness of objects they
  487. modify enables readers to be regarded as MT-Safe and AS-Safe (as long as
  488. no other reasons for them to be unsafe remain), since the lack of
  489. synchronization is not a problem when the objects are effectively
  490. constant.
  491. The identifier that follows the @code{const} mark will appear by itself
  492. as a safety note in readers. Programs that wish to work around this
  493. safety issue, so as to call writers, may use a non-recursve
  494. @code{rwlock} associated with the identifier, and guard @emph{all} calls
  495. to functions marked with @code{const} followed by the identifier with a
  496. write lock, and @emph{all} calls to functions marked with the identifier
  497. by itself with a read lock. The non-recursive locking removes the
  498. MT-Safety problem, but it trades one AS-Safety problem for another, so
  499. use in asynchronous signals remains undefined.
  500. @c But what if, instead of marking modifiers with const:id and readers
  501. @c with just id, we marked writers with race:id and readers with ro:id?
  502. @c Instead of having to define each instance of “id”, we'd have a
  503. @c general pattern governing all such “id”s, wherein race:id would
  504. @c suggest the need for an exclusive/write lock to make the function
  505. @c safe, whereas ro:id would indicate “id” is expected to be read-only,
  506. @c but if any modifiers are called (while holding an exclusive lock),
  507. @c then ro:id-marked functions ought to be guarded with a read lock for
  508. @c safe operation. ro:env or ro:locale, for example, seems to convey
  509. @c more clearly the expectations and the meaning, than just env or
  510. @c locale.
  511. @item @code{sig}
  512. @cindex sig
  513. Functions marked with @code{sig} as a MT-Safety issue (that implies an
  514. identical AS-Safety issue, omitted for brevity) may temporarily install
  515. a signal handler for internal purposes, which may interfere with other
  516. uses of the signal, identified after a colon.
  517. This safety problem can be worked around by ensuring that no other uses
  518. of the signal will take place for the duration of the call. Holding a
  519. non-recursive mutex while calling all functions that use the same
  520. temporary signal; blocking that signal before the call and resetting its
  521. handler afterwards is recommended.
  522. There is no safe way to guarantee the original signal handler is
  523. restored in case of asynchronous cancellation, therefore so-marked
  524. functions are also AC-Unsafe.
  525. @c fixme: at least deferred cancellation should get it right, and would
  526. @c obviate the restoring bit below, and the qualifier above.
  527. Besides the measures recommended to work around the MT- and AS-Safety
  528. problem, in order to avert the cancellation problem, disabling
  529. asynchronous cancellation @emph{and} installing a cleanup handler to
  530. restore the signal to the desired state and to release the mutex are
  531. recommended.
  532. @item @code{term}
  533. @cindex term
  534. Functions marked with @code{term} as an MT-Safety issue may change the
  535. terminal settings in the recommended way, namely: call @code{tcgetattr},
  536. modify some flags, and then call @code{tcsetattr}; this creates a window
  537. in which changes made by other threads are lost. Thus, functions marked
  538. with @code{term} are MT-Unsafe. The same window enables changes made by
  539. asynchronous signals to be lost. These functions are also AS-Unsafe,
  540. but the corresponding mark is omitted as redundant.
  541. It is thus advisable for applications using the terminal to avoid
  542. concurrent and reentrant interactions with it, by not using it in signal
  543. handlers or blocking signals that might use it, and holding a lock while
  544. calling these functions and interacting with the terminal. This lock
  545. should also be used for mutual exclusion with functions marked with
  546. @code{@mtasurace{:tcattr(fd)}}, where @var{fd} is a file descriptor for
  547. the controlling terminal. The caller may use a single mutex for
  548. simplicity, or use one mutex per terminal, even if referenced by
  549. different file descriptors.
  550. Functions marked with @code{term} as an AC-Safety issue are supposed to
  551. restore terminal settings to their original state, after temporarily
  552. changing them, but they may fail to do so if cancelled.
  553. @c fixme: at least deferred cancellation should get it right, and would
  554. @c obviate the restoring bit below, and the qualifier above.
  555. Besides the measures recommended to work around the MT- and AS-Safety
  556. problem, in order to avert the cancellation problem, disabling
  557. asynchronous cancellation @emph{and} installing a cleanup handler to
  558. restore the terminal settings to the original state and to release the
  559. mutex are recommended.
  560. @end itemize
  561. @node Other Safety Remarks, , Conditionally Safe Features, POSIX
  562. @subsubsection Other Safety Remarks
  563. @cindex Other Safety Remarks
  564. Additional keywords may be attached to functions, indicating features
  565. that do not make a function unsafe to call, but that may need to be
  566. taken into account in certain classes of programs:
  567. @itemize @bullet
  568. @item @code{locale}
  569. @cindex locale
  570. Functions annotated with @code{locale} as an MT-Safety issue read from
  571. the locale object without any form of synchronization. Functions
  572. annotated with @code{locale} called concurrently with locale changes may
  573. behave in ways that do not correspond to any of the locales active
  574. during their execution, but an unpredictable mix thereof.
  575. We do not mark these functions as MT- or AS-Unsafe, however, because
  576. functions that modify the locale object are marked with
  577. @code{const:locale} and regarded as unsafe. Being unsafe, the latter
  578. are not to be called when multiple threads are running or asynchronous
  579. signals are enabled, and so the locale can be considered effectively
  580. constant in these contexts, which makes the former safe.
  581. @c Should the locking strategy suggested under @code{const} be used,
  582. @c failure to guard locale uses is not as fatal as data races in
  583. @c general: unguarded uses will @emph{not} follow dangling pointers or
  584. @c access uninitialized, unmapped or recycled memory. Each access will
  585. @c read from a consistent locale object that is or was active at some
  586. @c point during its execution. Without synchronization, however, it
  587. @c cannot even be assumed that, after a change in locale, earlier
  588. @c locales will no longer be used, even after the newly-chosen one is
  589. @c used in the thread. Nevertheless, even though unguarded reads from
  590. @c the locale will not violate type safety, functions that access the
  591. @c locale multiple times may invoke all sorts of undefined behavior
  592. @c because of the unexpected locale changes.
  593. @item @code{env}
  594. @cindex env
  595. Functions marked with @code{env} as an MT-Safety issue access the
  596. environment with @code{getenv} or similar, without any guards to ensure
  597. safety in the presence of concurrent modifications.
  598. We do not mark these functions as MT- or AS-Unsafe, however, because
  599. functions that modify the environment are all marked with
  600. @code{const:env} and regarded as unsafe. Being unsafe, the latter are
  601. not to be called when multiple threads are running or asynchronous
  602. signals are enabled, and so the environment can be considered
  603. effectively constant in these contexts, which makes the former safe.
  604. @item @code{hostid}
  605. @cindex hostid
  606. The function marked with @code{hostid} as an MT-Safety issue reads from
  607. the system-wide data structures that hold the ``host ID'' of the
  608. machine. These data structures cannot generally be modified atomically.
  609. Since it is expected that the ``host ID'' will not normally change, the
  610. function that reads from it (@code{gethostid}) is regarded as safe,
  611. whereas the function that modifies it (@code{sethostid}) is marked with
  612. @code{@mtasuconst{:@mtshostid{}}}, indicating it may require special
  613. care if it is to be called. In this specific case, the special care
  614. amounts to system-wide (not merely intra-process) coordination.
  615. @item @code{sigintr}
  616. @cindex sigintr
  617. Functions marked with @code{sigintr} as an MT-Safety issue access the
  618. @code{_sigintr} internal data structure without any guards to ensure
  619. safety in the presence of concurrent modifications.
  620. We do not mark these functions as MT- or AS-Unsafe, however, because
  621. functions that modify the this data structure are all marked with
  622. @code{const:sigintr} and regarded as unsafe. Being unsafe, the latter
  623. are not to be called when multiple threads are running or asynchronous
  624. signals are enabled, and so the data structure can be considered
  625. effectively constant in these contexts, which makes the former safe.
  626. @item @code{fd}
  627. @cindex fd
  628. Functions annotated with @code{fd} as an AC-Safety issue may leak file
  629. descriptors if asynchronous thread cancellation interrupts their
  630. execution.
  631. Functions that allocate or deallocate file descriptors will generally be
  632. marked as such. Even if they attempted to protect the file descriptor
  633. allocation and deallocation with cleanup regions, allocating a new
  634. descriptor and storing its number where the cleanup region could release
  635. it cannot be performed as a single atomic operation. Similarly,
  636. releasing the descriptor and taking it out of the data structure
  637. normally responsible for releasing it cannot be performed atomically.
  638. There will always be a window in which the descriptor cannot be released
  639. because it was not stored in the cleanup handler argument yet, or it was
  640. already taken out before releasing it. It cannot be taken out after
  641. release: an open descriptor could mean either that the descriptor still
  642. has to be closed, or that it already did so but the descriptor was
  643. reallocated by another thread or signal handler.
  644. Such leaks could be internally avoided, with some performance penalty,
  645. by temporarily disabling asynchronous thread cancellation. However,
  646. since callers of allocation or deallocation functions would have to do
  647. this themselves, to avoid the same sort of leak in their own layer, it
  648. makes more sense for the library to assume they are taking care of it
  649. than to impose a performance penalty that is redundant when the problem
  650. is solved in upper layers, and insufficient when it is not.
  651. This remark by itself does not cause a function to be regarded as
  652. AC-Unsafe. However, cumulative effects of such leaks may pose a
  653. problem for some programs. If this is the case, suspending asynchronous
  654. cancellation for the duration of calls to such functions is recommended.
  655. @item @code{mem}
  656. @cindex mem
  657. Functions annotated with @code{mem} as an AC-Safety issue may leak
  658. memory if asynchronous thread cancellation interrupts their execution.
  659. The problem is similar to that of file descriptors: there is no atomic
  660. interface to allocate memory and store its address in the argument to a
  661. cleanup handler, or to release it and remove its address from that
  662. argument, without at least temporarily disabling asynchronous
  663. cancellation, which these functions do not do.
  664. This remark does not by itself cause a function to be regarded as
  665. generally AC-Unsafe. However, cumulative effects of such leaks may be
  666. severe enough for some programs that disabling asynchronous cancellation
  667. for the duration of calls to such functions may be required.
  668. @item @code{cwd}
  669. @cindex cwd
  670. Functions marked with @code{cwd} as an MT-Safety issue may temporarily
  671. change the current working directory during their execution, which may
  672. cause relative pathnames to be resolved in unexpected ways in other
  673. threads or within asynchronous signal or cancellation handlers.
  674. This is not enough of a reason to mark so-marked functions as MT- or
  675. AS-Unsafe, but when this behavior is optional (e.g., @code{nftw} with
  676. @code{FTW_CHDIR}), avoiding the option may be a good alternative to
  677. using full pathnames or file descriptor-relative (e.g. @code{openat})
  678. system calls.
  679. @item @code{!posix}
  680. @cindex !posix
  681. This remark, as an MT-, AS- or AC-Safety note to a function, indicates
  682. the safety status of the function is known to differ from the specified
  683. status in the POSIX standard. For example, POSIX does not require a
  684. function to be Safe, but our implementation is, or vice-versa.
  685. For the time being, the absence of this remark does not imply the safety
  686. properties we documented are identical to those mandated by POSIX for
  687. the corresponding functions.
  688. @item @code{:identifier}
  689. @cindex :identifier
  690. Annotations may sometimes be followed by identifiers, intended to group
  691. several functions that e.g. access the data structures in an unsafe way,
  692. as in @code{race} and @code{const}, or to provide more specific
  693. information, such as naming a signal in a function marked with
  694. @code{sig}. It is envisioned that it may be applied to @code{lock} and
  695. @code{corrupt} as well in the future.
  696. In most cases, the identifier will name a set of functions, but it may
  697. name global objects or function arguments, or identifiable properties or
  698. logical components associated with them, with a notation such as
  699. e.g. @code{:buf(arg)} to denote a buffer associated with the argument
  700. @var{arg}, or @code{:tcattr(fd)} to denote the terminal attributes of a
  701. file descriptor @var{fd}.
  702. The most common use for identifiers is to provide logical groups of
  703. functions and arguments that need to be protected by the same
  704. synchronization primitive in order to ensure safe operation in a given
  705. context.
  706. @item @code{/condition}
  707. @cindex /condition
  708. Some safety annotations may be conditional, in that they only apply if a
  709. boolean expression involving arguments, global variables or even the
  710. underlying kernel evaluates to true. Such conditions as
  711. @code{/hurd} or @code{/!linux!bsd} indicate the preceding marker only
  712. applies when the underlying kernel is the HURD, or when it is neither
  713. Linux nor a BSD kernel, respectively. @code{/!ps} and
  714. @code{/one_per_line} indicate the preceding marker only applies when
  715. argument @var{ps} is NULL, or global variable @var{one_per_line} is
  716. nonzero.
  717. When all marks that render a function unsafe are adorned with such
  718. conditions, and none of the named conditions hold, then the function can
  719. be regarded as safe.
  720. @end itemize
  721. @node Berkeley Unix, SVID, POSIX, Standards and Portability
  722. @subsection Berkeley Unix
  723. @cindex BSD Unix
  724. @cindex 4.@var{n} BSD Unix
  725. @cindex Berkeley Unix
  726. @cindex SunOS
  727. @cindex Unix, Berkeley
  728. @Theglibc{} defines facilities from some versions of Unix which
  729. are not formally standardized, specifically from the 4.2 BSD, 4.3 BSD,
  730. and 4.4 BSD Unix systems (also known as @dfn{Berkeley Unix}) and from
  731. @dfn{SunOS} (a popular 4.2 BSD derivative that includes some Unix System
  732. V functionality). These systems support most of the @w{ISO C} and POSIX
  733. facilities, and 4.4 BSD and newer releases of SunOS in fact support them all.
  734. The BSD facilities include symbolic links (@pxref{Symbolic Links}), the
  735. @code{select} function (@pxref{Waiting for I/O}), the BSD signal
  736. functions (@pxref{BSD Signal Handling}), and sockets (@pxref{Sockets}).
  737. @node SVID, XPG, Berkeley Unix, Standards and Portability
  738. @subsection SVID (The System V Interface Description)
  739. @cindex SVID
  740. @cindex System V Unix
  741. @cindex Unix, System V
  742. The @dfn{System V Interface Description} (SVID) is a document describing
  743. the AT&T Unix System V operating system. It is to some extent a
  744. superset of the POSIX standard (@pxref{POSIX}).
  745. @Theglibc{} defines most of the facilities required by the SVID
  746. that are not also required by the @w{ISO C} or POSIX standards, for
  747. compatibility with System V Unix and other Unix systems (such as
  748. SunOS) which include these facilities. However, many of the more
  749. obscure and less generally useful facilities required by the SVID are
  750. not included. (In fact, Unix System V itself does not provide them all.)
  751. The supported facilities from System V include the methods for
  752. inter-process communication and shared memory, the @code{hsearch} and
  753. @code{drand48} families of functions, @code{fmtmsg} and several of the
  754. mathematical functions.
  755. @node XPG, , SVID, Standards and Portability
  756. @subsection XPG (The X/Open Portability Guide)
  757. The X/Open Portability Guide, published by the X/Open Company, Ltd., is
  758. a more general standard than POSIX. X/Open owns the Unix copyright and
  759. the XPG specifies the requirements for systems which are intended to be
  760. a Unix system.
  761. @Theglibc{} complies to the X/Open Portability Guide, Issue 4.2,
  762. with all extensions common to XSI (X/Open System Interface)
  763. compliant systems and also all X/Open UNIX extensions.
  764. The additions on top of POSIX are mainly derived from functionality
  765. available in @w{System V} and BSD systems. Some of the really bad
  766. mistakes in @w{System V} systems were corrected, though. Since
  767. fulfilling the XPG standard with the Unix extensions is a
  768. precondition for getting the Unix brand chances are good that the
  769. functionality is available on commercial systems.
  770. @node Using the Library, Roadmap to the Manual, Standards and Portability, Introduction
  771. @section Using the Library
  772. This section describes some of the practical issues involved in using
  773. @theglibc{}.
  774. @menu
  775. * Header Files:: How to include the header files in your
  776. programs.
  777. * Macro Definitions:: Some functions in the library may really
  778. be implemented as macros.
  779. * Reserved Names:: The C standard reserves some names for
  780. the library, and some for users.
  781. * Feature Test Macros:: How to control what names are defined.
  782. @end menu
  783. @node Header Files, Macro Definitions, , Using the Library
  784. @subsection Header Files
  785. @cindex header files
  786. Libraries for use by C programs really consist of two parts: @dfn{header
  787. files} that define types and macros and declare variables and
  788. functions; and the actual library or @dfn{archive} that contains the
  789. definitions of the variables and functions.
  790. (Recall that in C, a @dfn{declaration} merely provides information that
  791. a function or variable exists and gives its type. For a function
  792. declaration, information about the types of its arguments might be
  793. provided as well. The purpose of declarations is to allow the compiler
  794. to correctly process references to the declared variables and functions.
  795. A @dfn{definition}, on the other hand, actually allocates storage for a
  796. variable or says what a function does.)
  797. @cindex definition (compared to declaration)
  798. @cindex declaration (compared to definition)
  799. In order to use the facilities in @theglibc{}, you should be sure
  800. that your program source files include the appropriate header files.
  801. This is so that the compiler has declarations of these facilities
  802. available and can correctly process references to them. Once your
  803. program has been compiled, the linker resolves these references to
  804. the actual definitions provided in the archive file.
  805. Header files are included into a program source file by the
  806. @samp{#include} preprocessor directive. The C language supports two
  807. forms of this directive; the first,
  808. @smallexample
  809. #include "@var{header}"
  810. @end smallexample
  811. @noindent
  812. is typically used to include a header file @var{header} that you write
  813. yourself; this would contain definitions and declarations describing the
  814. interfaces between the different parts of your particular application.
  815. By contrast,
  816. @smallexample
  817. #include <file.h>
  818. @end smallexample
  819. @noindent
  820. is typically used to include a header file @file{file.h} that contains
  821. definitions and declarations for a standard library. This file would
  822. normally be installed in a standard place by your system administrator.
  823. You should use this second form for the C library header files.
  824. Typically, @samp{#include} directives are placed at the top of the C
  825. source file, before any other code. If you begin your source files with
  826. some comments explaining what the code in the file does (a good idea),
  827. put the @samp{#include} directives immediately afterwards, following the
  828. feature test macro definition (@pxref{Feature Test Macros}).
  829. For more information about the use of header files and @samp{#include}
  830. directives, @pxref{Header Files,,, cpp.info, The GNU C Preprocessor
  831. Manual}.@refill
  832. @Theglibc{} provides several header files, each of which contains
  833. the type and macro definitions and variable and function declarations
  834. for a group of related facilities. This means that your programs may
  835. need to include several header files, depending on exactly which
  836. facilities you are using.
  837. Some library header files include other library header files
  838. automatically. However, as a matter of programming style, you should
  839. not rely on this; it is better to explicitly include all the header
  840. files required for the library facilities you are using. The @glibcadj{}
  841. header files have been written in such a way that it doesn't
  842. matter if a header file is accidentally included more than once;
  843. including a header file a second time has no effect. Likewise, if your
  844. program needs to include multiple header files, the order in which they
  845. are included doesn't matter.
  846. @strong{Compatibility Note:} Inclusion of standard header files in any
  847. order and any number of times works in any @w{ISO C} implementation.
  848. However, this has traditionally not been the case in many older C
  849. implementations.
  850. Strictly speaking, you don't @emph{have to} include a header file to use
  851. a function it declares; you could declare the function explicitly
  852. yourself, according to the specifications in this manual. But it is
  853. usually better to include the header file because it may define types
  854. and macros that are not otherwise available and because it may define
  855. more efficient macro replacements for some functions. It is also a sure
  856. way to have the correct declaration.
  857. @node Macro Definitions, Reserved Names, Header Files, Using the Library
  858. @subsection Macro Definitions of Functions
  859. @cindex shadowing functions with macros
  860. @cindex removing macros that shadow functions
  861. @cindex undefining macros that shadow functions
  862. If we describe something as a function in this manual, it may have a
  863. macro definition as well. This normally has no effect on how your
  864. program runs---the macro definition does the same thing as the function
  865. would. In particular, macro equivalents for library functions evaluate
  866. arguments exactly once, in the same way that a function call would. The
  867. main reason for these macro definitions is that sometimes they can
  868. produce an inline expansion that is considerably faster than an actual
  869. function call.
  870. Taking the address of a library function works even if it is also
  871. defined as a macro. This is because, in this context, the name of the
  872. function isn't followed by the left parenthesis that is syntactically
  873. necessary to recognize a macro call.
  874. You might occasionally want to avoid using the macro definition of a
  875. function---perhaps to make your program easier to debug. There are
  876. two ways you can do this:
  877. @itemize @bullet
  878. @item
  879. You can avoid a macro definition in a specific use by enclosing the name
  880. of the function in parentheses. This works because the name of the
  881. function doesn't appear in a syntactic context where it is recognizable
  882. as a macro call.
  883. @item
  884. You can suppress any macro definition for a whole source file by using
  885. the @samp{#undef} preprocessor directive, unless otherwise stated
  886. explicitly in the description of that facility.
  887. @end itemize
  888. For example, suppose the header file @file{stdlib.h} declares a function
  889. named @code{abs} with
  890. @smallexample
  891. extern int abs (int);
  892. @end smallexample
  893. @noindent
  894. and also provides a macro definition for @code{abs}. Then, in:
  895. @smallexample
  896. #include <stdlib.h>
  897. int f (int *i) @{ return abs (++*i); @}
  898. @end smallexample
  899. @noindent
  900. the reference to @code{abs} might refer to either a macro or a function.
  901. On the other hand, in each of the following examples the reference is
  902. to a function and not a macro.
  903. @smallexample
  904. #include <stdlib.h>
  905. int g (int *i) @{ return (abs) (++*i); @}
  906. #undef abs
  907. int h (int *i) @{ return abs (++*i); @}
  908. @end smallexample
  909. Since macro definitions that double for a function behave in
  910. exactly the same way as the actual function version, there is usually no
  911. need for any of these methods. In fact, removing macro definitions usually
  912. just makes your program slower.
  913. @node Reserved Names, Feature Test Macros, Macro Definitions, Using the Library
  914. @subsection Reserved Names
  915. @cindex reserved names
  916. @cindex name space
  917. The names of all library types, macros, variables and functions that
  918. come from the @w{ISO C} standard are reserved unconditionally; your program
  919. @strong{may not} redefine these names. All other library names are
  920. reserved if your program explicitly includes the header file that
  921. defines or declares them. There are several reasons for these
  922. restrictions:
  923. @itemize @bullet
  924. @item
  925. Other people reading your code could get very confused if you were using
  926. a function named @code{exit} to do something completely different from
  927. what the standard @code{exit} function does, for example. Preventing
  928. this situation helps to make your programs easier to understand and
  929. contributes to modularity and maintainability.
  930. @item
  931. It avoids the possibility of a user accidentally redefining a library
  932. function that is called by other library functions. If redefinition
  933. were allowed, those other functions would not work properly.
  934. @item
  935. It allows the compiler to do whatever special optimizations it pleases
  936. on calls to these functions, without the possibility that they may have
  937. been redefined by the user. Some library facilities, such as those for
  938. dealing with variadic arguments (@pxref{Variadic Functions})
  939. and non-local exits (@pxref{Non-Local Exits}), actually require a
  940. considerable amount of cooperation on the part of the C compiler, and
  941. with respect to the implementation, it might be easier for the compiler
  942. to treat these as built-in parts of the language.
  943. @end itemize
  944. In addition to the names documented in this manual, reserved names
  945. include all external identifiers (global functions and variables) that
  946. begin with an underscore (@samp{_}) and all identifiers regardless of
  947. use that begin with either two underscores or an underscore followed by
  948. a capital letter are reserved names. This is so that the library and
  949. header files can define functions, variables, and macros for internal
  950. purposes without risk of conflict with names in user programs.
  951. Some additional classes of identifier names are reserved for future
  952. extensions to the C language or the POSIX.1 environment. While using these
  953. names for your own purposes right now might not cause a problem, they do
  954. raise the possibility of conflict with future versions of the C
  955. or POSIX standards, so you should avoid these names.
  956. @itemize @bullet
  957. @item
  958. Names beginning with a capital @samp{E} followed a digit or uppercase
  959. letter may be used for additional error code names. @xref{Error
  960. Reporting}.
  961. @item
  962. Names that begin with either @samp{is} or @samp{to} followed by a
  963. lowercase letter may be used for additional character testing and
  964. conversion functions. @xref{Character Handling}.
  965. @item
  966. Names that begin with @samp{LC_} followed by an uppercase letter may be
  967. used for additional macros specifying locale attributes.
  968. @xref{Locales}.
  969. @item
  970. Names of all existing mathematics functions (@pxref{Mathematics})
  971. suffixed with @samp{f} or @samp{l} are reserved for corresponding
  972. functions that operate on @code{float} and @code{long double} arguments,
  973. respectively.
  974. @item
  975. Names that begin with @samp{SIG} followed by an uppercase letter are
  976. reserved for additional signal names. @xref{Standard Signals}.
  977. @item
  978. Names that begin with @samp{SIG_} followed by an uppercase letter are
  979. reserved for additional signal actions. @xref{Basic Signal Handling}.
  980. @item
  981. Names beginning with @samp{str}, @samp{mem}, or @samp{wcs} followed by a
  982. lowercase letter are reserved for additional string and array functions.
  983. @xref{String and Array Utilities}.
  984. @item
  985. Names that end with @samp{_t} are reserved for additional type names.
  986. @end itemize
  987. In addition, some individual header files reserve names beyond
  988. those that they actually define. You only need to worry about these
  989. restrictions if your program includes that particular header file.
  990. @itemize @bullet
  991. @item
  992. The header file @file{dirent.h} reserves names prefixed with
  993. @samp{d_}.
  994. @pindex dirent.h
  995. @item
  996. The header file @file{fcntl.h} reserves names prefixed with
  997. @samp{l_}, @samp{F_}, @samp{O_}, and @samp{S_}.
  998. @pindex fcntl.h
  999. @item
  1000. The header file @file{grp.h} reserves names prefixed with @samp{gr_}.
  1001. @pindex grp.h
  1002. @item
  1003. The header file @file{limits.h} reserves names suffixed with @samp{_MAX}.
  1004. @pindex limits.h
  1005. @item
  1006. The header file @file{pwd.h} reserves names prefixed with @samp{pw_}.
  1007. @pindex pwd.h
  1008. @item
  1009. The header file @file{signal.h} reserves names prefixed with @samp{sa_}
  1010. and @samp{SA_}.
  1011. @pindex signal.h
  1012. @item
  1013. The header file @file{sys/stat.h} reserves names prefixed with @samp{st_}
  1014. and @samp{S_}.
  1015. @pindex sys/stat.h
  1016. @item
  1017. The header file @file{sys/times.h} reserves names prefixed with @samp{tms_}.
  1018. @pindex sys/times.h
  1019. @item
  1020. The header file @file{termios.h} reserves names prefixed with @samp{c_},
  1021. @samp{V}, @samp{I}, @samp{O}, and @samp{TC}; and names prefixed with
  1022. @samp{B} followed by a digit.
  1023. @pindex termios.h
  1024. @end itemize
  1025. @comment Include the section on Creature Nest Macros.
  1026. @include creature.texi
  1027. @node Roadmap to the Manual, , Using the Library, Introduction
  1028. @section Roadmap to the Manual
  1029. Here is an overview of the contents of the remaining chapters of
  1030. this manual.
  1031. @c The chapter overview ordering is:
  1032. @c Error Reporting (2)
  1033. @c Virtual Memory Allocation and Paging (3)
  1034. @c Character Handling (4)
  1035. @c Strings and Array Utilities (5)
  1036. @c Character Set Handling (6)
  1037. @c Locales and Internationalization (7)
  1038. @c Searching and Sorting (9)
  1039. @c Pattern Matching (10)
  1040. @c Input/Output Overview (11)
  1041. @c Input/Output on Streams (12)
  1042. @c Low-level Input/Ooutput (13)
  1043. @c File System Interface (14)
  1044. @c Pipes and FIFOs (15)
  1045. @c Sockets (16)
  1046. @c Low-Level Terminal Interface (17)
  1047. @c Syslog (18)
  1048. @c Mathematics (19)
  1049. @c Aritmetic Functions (20)
  1050. @c Date and Time (21)
  1051. @c Non-Local Exist (23)
  1052. @c Signal Handling (24)
  1053. @c The Basic Program/System Interface (25)
  1054. @c Processes (26)
  1055. @c Job Control (28)
  1056. @c System Databases and Name Service Switch (29)
  1057. @c Users and Groups (30) -- References `User Database' and `Group Database'
  1058. @c System Management (31)
  1059. @c System Configuration Parameters (32)
  1060. @c C Language Facilities in the Library (AA)
  1061. @c Summary of Library Facilities (AB)
  1062. @c Installing (AC)
  1063. @c Library Maintenance (AD)
  1064. @c The following chapters need overview text to be added:
  1065. @c Message Translation (8)
  1066. @c Resource Usage And Limitations (22)
  1067. @c Inter-Process Communication (27)
  1068. @c Debugging support (34)
  1069. @c POSIX Threads (35)
  1070. @c Internal Probes (36)
  1071. @c Platform-specific facilities (AE)
  1072. @c Contributors to (AF)
  1073. @c Free Software Needs Free Documentation (AG)
  1074. @c GNU Lesser General Public License (AH)
  1075. @c GNU Free Documentation License (AI)
  1076. @itemize @bullet
  1077. @item
  1078. @ref{Error Reporting}, describes how errors detected by the library
  1079. are reported.
  1080. @item
  1081. @ref{Memory}, describes @theglibc{}'s facilities for managing and
  1082. using virtual and real memory, including dynamic allocation of virtual
  1083. memory. If you do not know in advance how much memory your program
  1084. needs, you can allocate it dynamically instead, and manipulate it via
  1085. pointers.
  1086. @item
  1087. @ref{Character Handling}, contains information about character
  1088. classification functions (such as @code{isspace}) and functions for
  1089. performing case conversion.
  1090. @item
  1091. @ref{String and Array Utilities}, has descriptions of functions for
  1092. manipulating strings (null-terminated character arrays) and general
  1093. byte arrays, including operations such as copying and comparison.
  1094. @item
  1095. @ref{Character Set Handling}, contains information about manipulating
  1096. characters and strings using character sets larger than will fit in
  1097. the usual @code{char} data type.
  1098. @item
  1099. @ref{Locales}, describes how selecting a particular country
  1100. or language affects the behavior of the library. For example, the locale
  1101. affects collation sequences for strings and how monetary values are
  1102. formatted.
  1103. @item
  1104. @ref{Searching and Sorting}, contains information about functions
  1105. for searching and sorting arrays. You can use these functions on any
  1106. kind of array by providing an appropriate comparison function.
  1107. @item
  1108. @ref{Pattern Matching}, presents functions for matching regular expressions
  1109. and shell file name patterns, and for expanding words as the shell does.
  1110. @item
  1111. @ref{I/O Overview}, gives an overall look at the input and output
  1112. facilities in the library, and contains information about basic concepts
  1113. such as file names.
  1114. @item
  1115. @ref{I/O on Streams}, describes I/O operations involving streams (or
  1116. @w{@code{FILE *}} objects). These are the normal C library functions
  1117. from @file{stdio.h}.
  1118. @item
  1119. @ref{Low-Level I/O}, contains information about I/O operations
  1120. on file descriptors. File descriptors are a lower-level mechanism
  1121. specific to the Unix family of operating systems.
  1122. @item
  1123. @ref{File System Interface}, has descriptions of operations on entire
  1124. files, such as functions for deleting and renaming them and for creating
  1125. new directories. This chapter also contains information about how you
  1126. can access the attributes of a file, such as its owner and file protection
  1127. modes.
  1128. @item
  1129. @ref{Pipes and FIFOs}, contains information about simple interprocess
  1130. communication mechanisms. Pipes allow communication between two related
  1131. processes (such as between a parent and child), while FIFOs allow
  1132. communication between processes sharing a common file system on the same
  1133. machine.
  1134. @item
  1135. @ref{Sockets}, describes a more complicated interprocess communication
  1136. mechanism that allows processes running on different machines to
  1137. communicate over a network. This chapter also contains information about
  1138. Internet host addressing and how to use the system network databases.
  1139. @item
  1140. @ref{Low-Level Terminal Interface}, describes how you can change the
  1141. attributes of a terminal device. If you want to disable echo of
  1142. characters typed by the user, for example, read this chapter.
  1143. @item
  1144. @ref{Mathematics}, contains information about the math library
  1145. functions. These include things like random-number generators and
  1146. remainder functions on integers as well as the usual trigonometric and
  1147. exponential functions on floating-point numbers.
  1148. @item
  1149. @ref{Arithmetic,, Low-Level Arithmetic Functions}, describes functions
  1150. for simple arithmetic, analysis of floating-point values, and reading
  1151. numbers from strings.
  1152. @item
  1153. @ref{Date and Time}, describes functions for measuring both calendar time
  1154. and CPU time, as well as functions for setting alarms and timers.
  1155. @item
  1156. @ref{Non-Local Exits}, contains descriptions of the @code{setjmp} and
  1157. @code{longjmp} functions. These functions provide a facility for
  1158. @code{goto}-like jumps which can jump from one function to another.
  1159. @item
  1160. @ref{Signal Handling}, tells you all about signals---what they are,
  1161. how to establish a handler that is called when a particular kind of
  1162. signal is delivered, and how to prevent signals from arriving during
  1163. critical sections of your program.
  1164. @item
  1165. @ref{Program Basics}, tells how your programs can access their
  1166. command-line arguments and environment variables.
  1167. @item
  1168. @ref{Processes}, contains information about how to start new processes
  1169. and run programs.
  1170. @item
  1171. @ref{Job Control}, describes functions for manipulating process groups
  1172. and the controlling terminal. This material is probably only of
  1173. interest if you are writing a shell or other program which handles job
  1174. control specially.
  1175. @item
  1176. @ref{Name Service Switch}, describes the services which are available
  1177. for looking up names in the system databases, how to determine which
  1178. service is used for which database, and how these services are
  1179. implemented so that contributors can design their own services.
  1180. @item
  1181. @ref{User Database}, and @ref{Group Database}, tell you how to access
  1182. the system user and group databases.
  1183. @item
  1184. @ref{System Management}, describes functions for controlling and getting
  1185. information about the hardware and software configuration your program
  1186. is executing under.
  1187. @item
  1188. @ref{System Configuration}, tells you how you can get information about
  1189. various operating system limits. Most of these parameters are provided for
  1190. compatibility with POSIX.
  1191. @item
  1192. @ref{Language Features}, contains information about library support for
  1193. standard parts of the C language, including things like the @code{sizeof}
  1194. operator and the symbolic constant @code{NULL}, how to write functions
  1195. accepting variable numbers of arguments, and constants describing the
  1196. ranges and other properties of the numerical types. There is also a simple
  1197. debugging mechanism which allows you to put assertions in your code, and
  1198. have diagnostic messages printed if the tests fail.
  1199. @item
  1200. @ref{Library Summary}, gives a summary of all the functions, variables, and
  1201. macros in the library, with complete data types and function prototypes,
  1202. and says what standard or system each is derived from.
  1203. @item
  1204. @ref{Installation}, explains how to build and install @theglibc{} on
  1205. your system, and how to report any bugs you might find.
  1206. @item
  1207. @ref{Maintenance}, explains how to add new functions or port the
  1208. library to a new system.
  1209. @end itemize
  1210. If you already know the name of the facility you are interested in, you
  1211. can look it up in @ref{Library Summary}. This gives you a summary of
  1212. its syntax and a pointer to where you can find a more detailed
  1213. description. This appendix is particularly useful if you just want to
  1214. verify the order and type of arguments to a function, for example. It
  1215. also tells you what standard or system each function, variable, or macro
  1216. is derived from.