1 /** @file
2   The header <stdlib.h> declares five types and several functions of general
3   utility, and defines several macros.
4 
5   The files stddef.h and stdlib.h are "catch all" headers for definitions and declarations
6   that don't fit well in the other headers.  There are two separate header files because
7   the contents of <stddef.h> are valid in both freestanding and hosted environment, while the
8   header <stdlib.h> contains elements that are only valid in a hosted environment.
9 
10   The following macros are defined in this file:<BR>
11   @verbatim
12     EXIT_FAILURE    An expression indicating application failure, used as an argument to exit().
13     EXIT_SUCCESS    An expression indicating application success, used as an argument to exit().
14     RAND_MAX        The maximum value returned by the rand function.
15     MB_CUR_MAX      Maximum number of bytes in a multibyte character for the current locale.
16     ATEXIT_MAX      Maximum number of routines that may be registered by the atexit function.
17   @endverbatim
18 
19   The following types are defined in this file:<BR>
20   @verbatim
21     size_t      Unsigned integer type of the result of the sizeof operator.
22     wchar_t     The type of a wide character.
23     div_t       Type of the value returned by the div function.
24     ldiv_t      Type of the value returned by the ldiv function.
25     lldiv_t     Type of the value returned by the lldiv function.
26   @endverbatim
27 
28   The following functions are declared in this file:<BR>
29   @verbatim
30     ################  Communication with the environment
31     void        abort   (void) __noreturn;
32     int         atexit  (void (*)(void));
33     void        exit    (int status) __noreturn;
34     void        _Exit   (int status) __noreturn;
35     char       *getenv  (const char *name);
36     int         setenv  (register const char * name,
37                          register const char * value, int rewrite);
38     int         system  (const char *string);
39 
40     ################  Integer arithmetic functions
41     int         abs     (int j);
42     long        labs    (long j);
43     long long   llabs   (long long j);
44     div_t       div     (int numer, int denom);
45     ldiv_t      ldiv    (long numer, long denom);
46     lldiv_t     lldiv   (long long numer, long long denom);
47 
48     ################  Pseudo-random sequence generation functions
49     int         rand    (void);
50     void        srand   (unsigned seed);
51 
52     ################  Memory management functions
53     void       *calloc  (size_t Num, size_t Size);
54     void        free    (void *);
55     void       *malloc  (size_t);
56     void       *realloc (void *Ptr, size_t NewSize);
57 
58     ################  Searching and Sorting utilities
59     void       *bsearch (const void *key,  const void *base0,
60                          size_t nmemb,     size_t size,
61                          int (*compar)(const void *, const void *));
62     void        qsort   (void *base, size_t nmemb, size_t size,
63                          int (*compar)(const void *, const void *));
64 
65     ################  Multibyte/wide character conversion functions
66     int         mblen   (const char *, size_t);
67     int         mbtowc  (wchar_t * __restrict, const char * __restrict, size_t);
68     int         wctomb  (char *, wchar_t);
69 
70     ################  Multibyte/wide string conversion functions
71     size_t      mbstowcs  (wchar_t * __restrict dest,
72                            const char * __restrict src, size_t limit);
73     size_t      wcstombs  (char * __restrict dest,
74                            const wchar_t * __restrict src, size_t limit);
75 
76     ################  Miscelaneous functions for *nix compatibility
77     char       *realpath    (char *file_name, char *resolved_name);
78     const char *getprogname (void);
79     void        setprogname (const char *progname);
80 
81     ############  Integer Numeric conversion functions
82     int                   atoi      (const char *nptr);
83     long                  atol      (const char *nptr);
84     long long             atoll     (const char *nptr);
85     long                  strtol    (const char * __restrict nptr,
86                                      char ** __restrict endptr, int base);
87     unsigned long         strtoul   (const char * __restrict nptr,
88                                      char ** __restrict endptr, int base);
89     long long             strtoll   (const char * __restrict nptr,
90                                      char ** __restrict endptr, int base);
91     unsigned long long    strtoull  (const char * __restrict nptr,
92                                      char ** __restrict endptr, int base);
93 
94     #########  Floating-point Numeric conversion functions
95     double                atof      (const char *);
96     double                strtod    (const char * __restrict nptr,
97                                      char ** __restrict endptr);
98     float                 strtof    (const char * __restrict nptr,
99                                      char ** __restrict endptr);
100     long double           strtold   (const char * __restrict nptr,
101                                      char ** __restrict endptr);
102   @endverbatim
103 
104   Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
105   This program and the accompanying materials are licensed and made available under
106   the terms and conditions of the BSD License that accompanies this distribution.
107   The full text of the license may be found at
108   http://opensource.org/licenses/bsd-license.
109 
110   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
111   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
112 **/
113 #ifndef _STDLIB_H
114 #define _STDLIB_H
115 #include  <sys/EfiCdefs.h>
116 
117 #ifdef _EFI_SIZE_T_
118   /** Unsigned integer type of the result of the sizeof operator. **/
119   typedef _EFI_SIZE_T_  size_t;
120   #undef _EFI_SIZE_T_
121   #undef _BSD_SIZE_T_
122 #endif
123 
124 #ifndef __cplusplus
125   #ifdef _EFI_WCHAR_T
126     /** Type of a wide (Unicode) character. **/
127     typedef _EFI_WCHAR_T wchar_t;
128     #undef  _EFI_WCHAR_T
129     #undef _BSD_WCHAR_T_
130   #endif
131 #endif
132 
133 /// A structure type that is the type of the value returned by the div function.
134 typedef struct {
135   int quot;   /**< quotient */
136   int rem;    /**< remainder */
137 } div_t;
138 
139 /// A structure type that is the type of the value returned by the ldiv function.
140 typedef struct {
141   long  quot;
142   long  rem;
143 } ldiv_t;
144 
145 /// A structure type that is the type of the value returned by the lldiv function.
146 typedef struct {
147   long long quot;
148   long long rem;
149 } lldiv_t;
150 
151 /** @{
152     Expand to integer constant expressions that can be used as the argument to
153     the exit function to return unsuccessful or successful termination status,
154     respectively, to the host environment.
155 **/
156 #define EXIT_FAILURE  1
157 #define EXIT_SUCCESS  0
158 /*@}*/
159 
160 /** Expands to an integer constant expression that is the maximum value
161     returned by the rand function.
162 **/
163 #define RAND_MAX  0x7fffffff
164 
165 /** Expands to a positive integer expression with type size_t that is the
166     maximum number of bytes in a multibyte character for the extended character
167     set specified by the current locale (category LC_CTYPE), which is never
168     greater than MB_LEN_MAX.
169 
170     Since UEFI only supports the Unicode Base Multilingual Plane (BMP),
171     correctly formed characters will only produce 1, 2, or 3-byte UTF-8 characters.
172 **/
173 #define MB_CUR_MAX  3
174 
175 /** Maximum number of functions that can be registered by atexit.
176 
177     The C standard states that the implementation shall support the
178     registration of at least 32 functions.
179 **/
180 #define ATEXIT_MAX  32
181 
182 __BEGIN_DECLS
183 
184 /* ################  Communication with the environment  ################## */
185 
186 /** The abort function causes abnormal program termination to occur, unless
187     the signal SIGABRT is being caught and the signal handler does not return.
188 
189     Open streams with unwritten buffered data are not flushed, open
190     streams are not closed, and temporary files are not removed by abort.
191 
192     Unsuccessful termination is returned to the host environment by means of
193     the function call, raise(SIGABRT).
194 
195     @sa signal.h
196 **/
197 void    abort(void) __noreturn;
198 
199 /** The atexit function registers the function pointed to by func, to be
200     called without arguments at normal program termination.
201 
202     The implementation supports the registration of up to 32 functions.
203 
204     @param[in]  Handler   Pointer to the function to register as one of the
205                           routines to call at application exit time.
206 
207     @return   The atexit function returns zero if the registration succeeds,
208               nonzero if it fails.
209 **/
210 int     atexit(void (*Handler)(void));
211 
212 /** The exit function causes normal program termination to occur. If more than
213     one call to the exit function is executed by a program,
214     the behavior is undefined.
215 
216     First, all functions registered by the atexit function are called, in the
217     reverse order of their registration, except that a function is called
218     after any previously registered functions that had already been called at
219     the time it was registered. If, during the call to any such function, a
220     call to the longjmp function is made that would terminate the call to the
221     registered function, the behavior is undefined.
222 
223     Next, all open streams with unwritten buffered data are flushed, all open
224     streams are closed, and all files created by the tmpfile function
225     are removed.
226 
227     Finally, control is returned to the host environment.
228 
229     @param[in]  status    A value to be returned when the application exits.
230 
231     @return   If the value of status is zero, or EXIT_SUCCESS, status is
232               returned unchanged. If the value of status is EXIT_FAILURE,
233               RETURN_ABORTED is returned.  Otherwise, status is returned unchanged.
234 **/
235 void    exit(int status) __noreturn;
236 
237 /** The _Exit function causes normal program termination to occur and control
238     to be returned to the host environment.
239 
240     No functions registered by the atexit function or signal handlers
241     registered by the signal function are called.  Open streams with unwritten
242     buffered data are not flushed, open streams are not closed, and temporary
243     files are not removed by abort.
244 
245     The status returned to the host environment is determined in the same way
246     as for the exit function.
247 
248     @param[in]  status    A value to be returned when the application exits.
249 
250     @return   If the value of status is zero, or EXIT_SUCCESS, status is
251               returned unchanged. If the value of status is EXIT_FAILURE,
252               RETURN_ABORTED is returned.  Otherwise, status is returned unchanged.
253 **/
254 void    _Exit(int status) __noreturn;
255 
256 /** The getenv function searches an environment list, provided by the host
257     environment, for a string that matches the string pointed to by name.  The
258     set of environment names and the method for altering the environment list
259     are determined by the underlying UEFI Shell implementation.
260 
261     @param[in]  name    Pointer to a string naming the environment variable to retrieve.
262 
263     @return   The getenv function returns a pointer to a string associated with
264               the matched list member.  The string pointed to shall not be
265               modified by the program, but may be overwritten by a subsequent
266               call to the getenv function.  If the specified name cannot be
267               found, a null pointer is returned.
268 **/
269 char   *getenv(const char *name);
270 
271 /** Add or update a variable in the environment list.
272 
273     @param[in]  name     Address of a zero terminated name string.
274     @param[in]  value    Address of a zero terminated value string.
275     @param[in]  rewrite  TRUE allows overwriting existing values.
276 
277     @retval  0  Returns 0 upon success.
278     @retval -1  Returns -1 upon failure, sets errno with more information.
279 **/
280 int
281 setenv (
282   register const char * name,
283   register const char * value,
284   int rewrite
285   );
286 
287 /** If string is a null pointer, the system function determines whether the
288     host environment has a command processor. If string is not a null pointer,
289     the system function passes the string pointed to by string to that command
290     processor to be executed in a manner which the implementation shall
291     document; this might then cause the program calling system to behave in a
292     non-conforming manner or to terminate.
293 
294     @param[in]  string    Pointer to the command string to be executed.
295 
296     @return   If the argument is a null pointer, the system function returns
297               nonzero only if a command processor is available. If the argument
298               is not a null pointer, and the system function does return, it
299               returns an implementation-defined value.
300 **/
301 int     system(const char *string);
302 
303 
304 /* ################  Integer arithmetic functions  ######################## */
305 
306 /** Computes the absolute value of an integer j.
307 
308     @param[in]  j   The value to find the absolute value of.
309 
310     @return   The absolute value of j.
311 **/
312 int     abs(int j);
313 
314 /** Computes the absolute value of a long integer j.
315 
316     @param[in]  j   The value to find the absolute value of.
317 
318     @return   The absolute value of j.
319 **/
320 long    labs(long j);
321 
322 /** Computes the absolute value of a long long integer j.
323 
324     @param[in]  j   The value to find the absolute value of.
325 
326     @return   The absolute value of j.
327 **/
328 long long
329         llabs(long long j);
330 
331 /** Computes numer / denom and numer % denom in a single operation.
332 
333     @param[in]  numer   The numerator for the division.
334     @param[in]  denom   The denominator for the division.
335 
336     @return   Returns a structure of type div_t, comprising both the
337               quotient and the remainder.
338 **/
339 div_t   div(int numer, int denom);
340 
341 /** Computes numer / denom and numer % denom in a single operation.
342 
343     @param[in]  numer   The numerator for the division.
344     @param[in]  denom   The denominator for the division.
345 
346     @return   Returns a structure of type ldiv_t, comprising both the
347               quotient and the remainder.
348 **/
349 ldiv_t  ldiv(long numer, long denom);
350 
351 /** Computes numer / denom and numer % denom in a single operation.
352 
353     @param[in]  numer   The numerator for the division.
354     @param[in]  denom   The denominator for the division.
355 
356     @return   Returns a structure of type lldiv_t, comprising both the
357               quotient and the remainder.
358 **/
359 lldiv_t lldiv(long long numer, long long denom);
360 
361 /* ############  Integer Numeric conversion functions  #################### */
362 
363 /** The atoi function converts the initial portion of the string pointed to by
364     nptr to int representation.  Except for the behavior on error, it is
365     equivalent to:
366       - atoi: (int)strtol(nptr, (char **)NULL, 10)
367 
368     @param[in]  nptr  Pointer to the string to be converted.
369 
370     @return   The atoi function returns the converted value.
371 **/
372 int     atoi(const char *nptr);
373 
374 /** The atol function converts the initial portion of the string pointed to by
375     nptr to long int representation.  Except for the behavior on error, it is
376     equivalent to:
377       - atol: strtol(nptr, (char **)NULL, 10)
378 
379     @param[in]  nptr  Pointer to the string to be converted.
380 
381     @return   The atol function returns the converted value.
382 **/
383 long    atol(const char *nptr);
384 
385 /** The atoll function converts the initial portion of the string pointed to by
386     nptr to long long int representation.  Except for the behavior on error, it
387     is equivalent to:
388       - atoll: strtoll(nptr, (char **)NULL, 10)
389 
390     @param[in]  nptr  Pointer to the string to be converted.
391 
392     @return   The atoll function returns the converted value.
393 **/
394 long long
395         atoll(const char *nptr);
396 
397 /** The strtol, strtoll, strtoul, and strtoull functions convert the initial
398     portion of the string pointed to by nptr to long int, long long int,
399     unsigned long int, and unsigned long long int representation, respectively.
400     First, they decompose the input string into three parts: an initial,
401     possibly empty, sequence of white-space characters (as specified by the
402     isspace function), a subject sequence resembling an integer represented in
403     some radix determined by the value of base, and a final string of one or
404     more unrecognized characters, including the terminating null character of
405     the input string. Then, they attempt to convert the subject sequence to an
406     integer, and return the result.
407 
408     If the value of base is zero, the expected form of the subject sequence is
409     that of an integer constant, optionally preceded
410     by a plus or minus sign, but not including an integer suffix. If the value
411     of base is between 2 and 36 (inclusive), the expected form of the subject
412     sequence is a sequence of letters and digits representing an integer with
413     the radix specified by base, optionally preceded by a plus or minus sign,
414     but not including an integer suffix. The letters from a (or A) through z
415     (or Z) are ascribed the values 10 through 35; only letters and digits whose
416     ascribed values are less than that of base are permitted. If the value of
417     base is 16, the characters 0x or 0X may optionally precede the sequence of
418     letters and digits, following the sign if present.
419 
420     The subject sequence is defined as the longest initial subsequence of the
421     input string, starting with the first non-white-space character, that is of
422     the expected form. The subject sequence contains no characters if the input
423     string is empty or consists entirely of white space, or if the first
424     non-white-space character is other than a sign or a permissible letter or digit.
425 
426     If the subject sequence has the expected form and the value of base is
427     zero, the sequence of characters starting with the first digit is
428     interpreted as an integer constant. If the subject sequence has the
429     expected form and the value of base is between 2 and 36, it is used as the
430     base for conversion, ascribing to each letter its value as given above. If
431     the subject sequence begins with a minus sign, the value resulting from the
432     conversion is negated (in the return type). A pointer to the final string
433     is stored in the object pointed to by endptr, provided that endptr is
434     not a null pointer.
435 
436     In other than the "C" locale, additional locale-specific subject sequence
437     forms may be accepted.
438 
439     If the subject sequence is empty or does not have the expected form, no
440     conversion is performed; the value of nptr is stored in the object pointed
441     to by endptr, provided that endptr is not a null pointer.
442 
443     @param[in]    nptr    Pointer to the string to be converted.
444     @param[out]   endptr  If not NULL, points to an object to receive a pointer to the final string.
445     @param[in]    base    The base, 0 to 36, of the number represented by the input string.
446 
447     @return   The strtol, strtoll, strtoul, and strtoull functions return the
448               converted value, if any. If no conversion could be performed, zero
449               is returned. If the correct value is outside the range of
450               representable values, LONG_MIN, LONG_MAX, LLONG_MIN, LLONG_MAX,
451               ULONG_MAX, or ULLONG_MAX is returned (according to the return type
452               and sign of the value, if any), and the value of the macro ERANGE
453               is stored in errno.
454 **/
455 long    strtol(const char * __restrict nptr, char ** __restrict endptr, int base);
456 
457 /** The strtoul function converts the initial portion of the string pointed to
458     by nptr to unsigned long int representation.
459 
460     See the description for strtol for more information.
461 
462     @param[in]    nptr    Pointer to the string to be converted.
463     @param[out]   endptr  If not NULL, points to an object to receive a pointer to the final string.
464     @param[in]    base    The base, 0 to 36, of the number represented by the input string.
465 
466     @return   The strtoul function returns the converted value, if any. If no
467               conversion could be performed, zero is returned. If the correct
468               value is outside the range of representable values, ULONG_MAX is
469               returned and the value of the macro ERANGE is stored in errno.
470 **/
471 unsigned long
472         strtoul(const char * __restrict nptr, char ** __restrict endptr, int base);
473 
474 /** The strtoll function converts the initial portion of the string pointed to
475     by nptr to long long int representation.
476 
477     See the description for strtol for more information.
478 
479     @param[in]    nptr    Pointer to the string to be converted.
480     @param[out]   endptr  If not NULL, points to an object to receive a pointer to the final string.
481     @param[in]    base    The base, 0 to 36, of the number represented by the input string.
482 
483     @return   The strtoll function returns the converted value, if any. If no
484               conversion could be performed, zero is returned. If the correct
485               value is outside the range of representable values, LLONG_MIN or
486               LLONG_MAX is returned (according to the sign of the value, if any),
487               and the value of the macro ERANGE is stored in errno.
488 **/
489 long long
490         strtoll(const char * __restrict nptr, char ** __restrict endptr, int base);
491 
492 /** The strtoull function converts the initial portion of the string pointed to
493     by nptr to unsigned long long int representation.
494 
495     See the description for strtol for more information.
496 
497     @param[in]    nptr    Pointer to the string to be converted.
498     @param[out]   endptr  If not NULL, points to an object to receive a pointer to the final string.
499     @param[in]    base    The base, 0 to 36, of the number represented by the input string.
500 
501     @return   The strtoull function returns the converted value, if any. If no
502               conversion could be performed, zero is returned. If the correct
503               value is outside the range of representable values, ULLONG_MAX is
504               returned and the value of the macro ERANGE is stored in errno.
505 **/
506 unsigned long long
507         strtoull(const char * __restrict nptr, char ** __restrict endptr, int base);
508 
509 /* #########  Floating-point Numeric conversion functions  ################ */
510 
511 /** Convert the initial part of a string to double representation.
512 
513     @param[in]  nptr  Pointer to the string to be converted.
514 
515     @return   The floating-point value representing the string nptr.
516 **/
517 double  atof(const char *nptr);
518 
519 /** @{
520     The strtod, strtof, and strtold functions convert the initial portion of
521     the string pointed to by nptr to double, float, and long double
522     representation, respectively. First, they decompose the input string into
523     three parts: an initial, possibly empty, sequence of white-space characters
524     (as specified by the isspace function), a subject sequence resembling a
525     floating-point constant or representing an infinity or NaN; and a final
526     string of one or more unrecognized characters, including the terminating
527     null character of the input string. Then, they attempt to convert the
528     subject sequence to a floating-point number, and return the result.
529 */
530 
531 /** Convert a string to a double and point to the character after the last converted.
532 
533     @param[in]    nptr    Pointer to the string to be converted.
534     @param[out]   endptr  If not NULL, points to an object to receive a pointer to the final string.
535 
536     @return   A floating-point value representing the string nptr.
537               A pointer to the final string is stored in the object pointed to
538               by endptr, provided that endptr is not a null pointer.
539               If the subject sequence is empty or does not have the expected
540               form, no conversion is performed; the value of nptr is stored in
541               the object pointed to by endptr, provided that endptr is not a null pointer.
542 **/
543 double  strtod(const char * __restrict nptr, char ** __restrict endptr);
544 
545 /** Convert a string to a float and point to the character after the last converted.
546 
547     @param[in]    nptr    Pointer to the string to be converted.
548     @param[out]   endptr  If not NULL, points to an object to receive a pointer to the final string.
549 
550     @return   A floating-point value representing the string nptr.
551               A pointer to the final string is stored in the object pointed to
552               by endptr, provided that endptr is not a null pointer.
553               If the subject sequence is empty or does not have the expected
554               form, no conversion is performed; the value of nptr is stored in
555               the object pointed to by endptr, provided that endptr is not a null pointer.
556 **/
557 float   strtof(const char * __restrict nptr, char ** __restrict endptr);
558 
559 /** Convert a string to a long double and point to the character after the last converted.
560 
561     @param[in]    nptr    Pointer to the string to be converted.
562     @param[out]   endptr  If not NULL, points to an object to receive a pointer to the final string.
563 
564     @return   A floating-point value representing the string nptr.
565               A pointer to the final string is stored in the object pointed to
566               by endptr, provided that endptr is not a null pointer.
567               If the subject sequence is empty or does not have the expected
568               form, no conversion is performed; the value of nptr is stored in
569               the object pointed to by endptr, provided that endptr is not a null pointer.
570 **/
571 long double
572         strtold(const char * __restrict nptr, char ** __restrict endptr);
573 /*@}*/
574 
575 /* ################  Pseudo-random sequence generation functions  ######### */
576 
577 /** The rand function computes a sequence of pseudo-random integers in the
578     range 0 to RAND_MAX.
579 
580     @return   The rand function returns a pseudo-random integer.
581 **/
582 int     rand(void);
583 
584 /** The srand function uses the argument as a seed for a new sequence of
585     pseudo-random numbers to be returned by subsequent calls to rand.
586 
587     If srand is then called with the same seed value, the sequence of
588     pseudo-random numbers shall be repeated. If rand is called before any calls
589     to srand have been made, the same sequence shall be generated as when srand
590     is first called with a seed value of 1.
591 
592     @param[in]  seed    The value used to "seed" the random number generator with.
593 **/
594 void    srand(unsigned seed);
595 
596 /* ################  Memory management functions  ######################### */
597 
598 /** The calloc function allocates space for an array of Num objects, each of
599     whose size is Size.  The space is initialized to all bits zero.
600 
601     @param[in]  Num   The number of objects to allocate space for.
602     @param[in]  Size  The size, in bytes, of each object.
603 
604     @return   NULL is returned if the space could not be allocated and errno
605               contains the cause.  Otherwise, a pointer to an 8-byte aligned
606               region of the requested size is returned.
607 **/
608 void   *calloc(size_t Num, size_t Size);
609 
610 /** The free function causes the space pointed to by Ptr to be deallocated,
611     that is, made available for further allocation.
612 
613     If Ptr is a null pointer, no action occurs.  Otherwise, if the argument
614     does not match a pointer earlier returned by the calloc, malloc, or realloc
615     function, or if the space has been deallocated by a call to free or
616     realloc, the behavior is undefined.
617 
618     @param  Ptr     Pointer to a previously allocated region of memory to be freed.
619 **/
620 void    free(void *Ptr);
621 
622 /** The malloc function allocates space for an object whose size is specified
623     by size and whose value is indeterminate.
624 
625     This implementation uses the UEFI memory allocation boot services to get a
626     region of memory that is 8-byte aligned and of the specified size.  The
627     region is allocated with type EfiLoaderData.
628 
629     @param  Size    Size, in bytes, of the region to allocate.
630 
631     @return   NULL is returned if the space could not be allocated and errno
632               contains the cause.  Otherwise, a pointer to an 8-byte aligned
633               region of the requested size is returned.<BR>
634               If NULL is returned, errno may contain:
635               - EINVAL: Requested Size is zero.
636               - ENOMEM: Memory could not be allocated.
637 **/
638 void   *malloc(size_t Size);
639 
640 /** The realloc function changes the size of the object pointed to by Ptr to
641     the size specified by NewSize.
642 
643     The contents of the object are unchanged up to the lesser of the new and
644     old sizes.  If the new size is larger, the value of the newly allocated
645     portion of the object is indeterminate.
646 
647     If Ptr is a null pointer, the realloc function behaves like the malloc
648     function for the specified size.
649 
650     If Ptr does not match a pointer earlier returned by the calloc, malloc, or
651     realloc function, or if the space has been deallocated by a call to the free
652     or realloc function, the behavior is undefined.
653 
654     If the space cannot be allocated, the object pointed to by Ptr is unchanged.
655 
656     If NewSize is zero and Ptr is not a null pointer, the object it points to
657     is freed.
658 
659     This implementation uses the UEFI memory allocation boot services to get a
660     region of memory that is 8-byte aligned and of the specified size.  The
661     region is allocated with type EfiLoaderData.
662 
663     @param  Ptr     Pointer to a previously allocated region of memory to be resized.
664     @param  NewSize Size, in bytes, of the new object to allocate space for.
665 
666     @return   NULL is returned if the space could not be allocated and errno
667               contains the cause.  Otherwise, a pointer to an 8-byte aligned
668               region of the requested size is returned.  If NewSize is zero,
669               NULL is returned and errno will be unchanged.
670 **/
671 void   *realloc(void *Ptr, size_t NewSize);
672 
673 /* ################  Searching and Sorting utilities  ##################### */
674 
675 /** The bsearch function searches an array of Nmemb objects, the initial
676     element of which is pointed to by Base, for an element that matches the
677     object pointed to by Key. The size of each element of the array is
678     specified by Size.
679 
680     The comparison function pointed to by Compar is called with two arguments
681     that point to the Key object and to an array element, in that order. The
682     function returns an integer less than, equal to, or greater than zero if
683     the Key object is considered, respectively, to be less than, to match, or
684     to be greater than the array element. The array consists of: all the
685     elements that compare less than, all the elements that compare equal to,
686     and all the elements that compare greater than the key object,
687     in that order.
688 
689     @param[in]  Key     Pointer to the object to search for.
690     @param[in]  Base    Pointer to the first element of an array to search.
691     @param[in]  Nmemb   Number of objects in the search array.
692     @param[in]  Size    The size of each object in the search array.
693     @param[in]  Compar  Pointer to the function used to compare two objects.
694 
695     @return   The bsearch function returns a pointer to a matching element of the
696               array, or a null pointer if no match is found. If two elements
697               compare as equal, which element is matched is unspecified.
698 **/
699 void   *bsearch(  const void *Key,  const void *Base,
700                   size_t Nmemb,     size_t Size,
701                   int (*Compar)(const void *, const void *)
702         );
703 
704 /** The qsort function sorts an array of Nmemb objects, the initial element of
705     which is pointed to by Base.  The size of each object is specified by Size.
706 
707     The contents of the array are sorted into ascending order according to a
708     comparison function pointed to by Compar, which is called with two
709     arguments that point to the objects being compared. The function shall
710     return an integer less than, equal to, or greater than zero if the first
711     argument is considered to be respectively less than, equal to, or greater
712     than the second.
713 
714     If two elements compare as equal, their order in the resulting sorted array
715     is unspecified.
716 
717     @param[in,out]  Base    Pointer to the first element of an array to sort.
718     @param[in]      Nmemb   Number of objects in the array.
719     @param[in]      Size    The size of each object in the array.
720     @param[in]      Compar  Pointer to the function used to compare two objects.
721 **/
722 void    qsort( void *base, size_t nmemb, size_t size,
723                int (*compar)(const void *, const void *));
724 
725 /* ################  Multibyte/wide character conversion functions  ####### */
726 
727 /** Determine the number of bytes comprising a multibyte character.
728 
729   If S is not a null pointer, the mblen function determines the number of bytes
730   contained in the multibyte character pointed to by S. Except that the
731   conversion state of the mbtowc function is not affected, it is equivalent to
732     mbtowc((wchar_t *)0, S, N);
733 
734   @param[in]  S   NULL to query whether multibyte characters have
735                   state-dependent encodings.  Otherwise, points to a
736                   multibyte character.
737   @param[in]  N   The maximum number of bytes in a multibyte character.
738 
739   @return   If S is a null pointer, the mblen function returns a nonzero or
740             zero value, if multibyte character encodings, respectively, do
741             or do not have state-dependent encodings. If S is not a null
742             pointer, the mblen function either returns 0 (if S points to the
743             null character), or returns the number of bytes that are contained
744             in the multibyte character (if the next N or fewer bytes form a
745             valid multibyte character), or returns -1 (if they do not form a
746             valid multibyte character).
747 **/
748 int     mblen(const char *S, size_t N);
749 
750 /** Convert a multibyte character into a wide character.
751 
752     If S is not a null pointer, the mbtowc function inspects at most N bytes
753     beginning with the byte pointed to by S to determine the number of bytes
754     needed to complete the next multibyte character (including any shift
755     sequences). If the function determines that the next multibyte character
756     is complete and valid, it determines the value of the corresponding wide
757     character and then, if Pwc is not a null pointer, stores that value in
758     the object pointed to by Pwc. If the corresponding wide character is the
759     null wide character, the function is left in the initial conversion state.
760 
761     @param[out]   Pwc Pointer to a wide-character object to receive the converted character.
762     @param[in]    S   Pointer to a multibyte character to convert.
763     @param[in]    N   Maximum number of bytes in a multibyte character.
764 
765     @return   If S is a null pointer, the mbtowc function returns a nonzero or
766               zero value, if multibyte character encodings, respectively, do
767               or do not have state-dependent encodings. If S is not a null
768               pointer, the mbtowc function either returns 0 (if S points to
769               the null character), or returns the number of bytes that are
770               contained in the converted multibyte character (if the next N or
771               fewer bytes form a valid multibyte character), or returns -1
772               (if they do not form a valid multibyte character).
773 
774               In no case will the value returned be greater than N or the value
775               of the MB_CUR_MAX macro.
776 **/
777 int     mbtowc(wchar_t * __restrict Pwc, const char * __restrict S, size_t N);
778 
779 /** Convert a wide character into a multibyte character.
780 
781     The wctomb function determines the number of bytes needed to represent the
782     multibyte character corresponding to the wide character given by WC
783     (including any shift sequences), and stores the multibyte character
784     representation in the array whose first element is pointed to by S (if S is
785     not a null pointer). At most MB_CUR_MAX characters are stored. If WC is a
786     null wide character, a null byte is stored, preceded by any shift sequence
787     needed to restore the initial shift state, and the function is left in the
788     initial conversion state.
789 
790     @param[out]   S   Pointer to the object to receive the converted multibyte character.
791     @param[in]    WC  Wide character to be converted.
792 
793     @return   If S is a null pointer, the wctomb function returns a nonzero or
794               zero value, if multibyte character encodings, respectively, do or
795               do not have state-dependent encodings. If S is not a null pointer,
796               the wctomb function returns -1 if the value of WC does not
797               correspond to a valid multibyte character, or returns the number
798               of bytes that are contained in the multibyte character
799               corresponding to the value of WC.
800 
801               In no case will the value returned be greater than the value of
802               the MB_CUR_MAX macro.
803 **/
804 int     wctomb(char *S, wchar_t WC);
805 
806 /* ################  Multibyte/wide string conversion functions  ########## */
807 
808 /** Convert a multibyte character string into a wide-character string.
809 
810     The mbstowcs function converts a sequence of multibyte characters that
811     begins in the initial shift state from the array pointed to by Src into
812     a sequence of corresponding wide characters and stores not more than limit
813     wide characters into the array pointed to by Dest.  No multibyte
814     characters that follow a null character (which is converted into a null
815     wide character) will be examined or converted. Each multibyte character
816     is converted as if by a call to the mbtowc function, except that the
817     conversion state of the mbtowc function is not affected.
818 
819     No more than Limit elements will be modified in the array pointed to by Dest.
820     If copying takes place between objects that overlap,
821     the behavior is undefined.
822 
823     @param[out]   Dest    Pointer to the array to receive the converted string.
824     @param[in]    Src     Pointer to the string to be converted.
825     @param[in]    Limit   Maximum number of elements to be written to Dest.
826 
827     @return   If an invalid multibyte character is encountered, the mbstowcs
828               function returns (size_t)(-1). Otherwise, the mbstowcs function
829               returns the number of array elements modified, not including a
830               terminating null wide character, if any.
831 **/
832 size_t  mbstowcs(wchar_t * __restrict Dest, const char * __restrict Src, size_t Limit);
833 
834 /** Convert a wide-character string into a multibyte character string.
835 
836     The wcstombs function converts a sequence of wide characters from the
837     array pointed to by Src into a sequence of corresponding multibyte
838     characters that begins in the initial shift state, and stores these
839     multibyte characters into the array pointed to by Dest, stopping if a
840     multibyte character would exceed the limit of Limit total bytes or if a
841     null character is stored. Each wide character is converted as if by
842     a call to the wctomb function, except that the conversion state of
843     the wctomb function is not affected.
844 
845     No more than Limit bytes will be modified in the array pointed to by Dest.
846     If copying takes place between objects that overlap,
847     the behavior is undefined.
848 
849     @param[out]   Dest    Pointer to the array to receive the converted string.
850     @param[in]    Src     Pointer to the string to be converted.
851     @param[in]    Limit   Maximum number of bytes to be written to Dest.
852 
853     @return   If a wide character is encountered that does not correspond to a
854               valid multibyte character, the wcstombs function returns
855               (size_t)(-1). Otherwise, the wcstombs function returns the number
856               of bytes modified, not including a terminating null character,
857               if any.
858 **/
859 size_t  wcstombs(char * __restrict Dest, const wchar_t * __restrict Src, size_t Limit);
860 
861 /* ##############  Miscelaneous functions for *nix compatibility  ########## */
862 
863 /** The realpath() function shall derive, from the pathname pointed to by
864     file_name, an absolute pathname that names the same file, whose resolution
865     does not involve '.', '..', or symbolic links. The generated pathname shall
866     be stored as a null-terminated string, up to a maximum of {PATH_MAX} bytes,
867     in the buffer pointed to by resolved_name.
868 
869     If resolved_name is a null pointer, the behavior of realpath() is
870     implementation-defined.
871 
872     @param[in]      file_name         The filename to convert.
873     @param[in,out]  resolved_name     The resultant name.
874 
875     @retval NULL                    An error occured.
876     @retval resolved_name.
877 **/
878 char * realpath(char *file_name, char *resolved_name);
879 
880 /** The getprogname() function returns the name of the program.  If the name
881     has not been set yet, it will return NULL.
882 
883   @return   The getprogname function returns NULL if the program's name has not
884             been set, otherwise it returns the name of the program.
885 **/
886 const char * getprogname(void);
887 
888 /** The setprogname() function sets the name of the program.
889 
890   @param[in]  progname    The name of the program.  This memory must be retained
891                           by the caller until no calls to "getprogname" will be
892                           called.
893 **/
894 void setprogname(const char *progname);
895 
896 /* ###############  Functions specific to this implementation  ############# */
897 
898 /*  Determine the number of bytes needed to represent a Wide character
899     as a MBCS character.
900 
901     A single wide character may convert into a one, two, three, or four byte
902     narrow (MBCS or UTF-8) character.  The number of MBCS bytes can be determined
903     as follows.
904 
905     If WCS char      < 0x00000080      One Byte
906     Else if WCS char < 0x0000D800      Two Bytes
907     Else                               Three Bytes
908 
909     Since UEFI only supports the Unicode Base Multilingual Plane (BMP),
910     Four-byte characters are not supported.
911 
912     @param[in]    InCh      Wide character to test.
913 
914     @retval     -1      Improperly formed character
915     @retval      0      InCh is 0x0000
916     @retval     >0      Number of bytes needed for the MBCS character
917 */
918 int
919 EFIAPI
920 OneWcToMcLen(const wchar_t InCh);
921 
922 /*  Determine the number of bytes needed to represent a Wide character string
923     as a MBCS string of given maximum length.  Will optionally return the number
924     of wide characters that would be consumed.
925 
926     @param[in]    Src       Pointer to a wide character string.
927     @param[in]    Limit     Maximum number of bytes the converted string may occupy.
928     @param[out]   NumChar   Pointer to where to store the number of wide characters, or NULL.
929 
930     @return     The number of bytes required to convert Src to MBCS,
931                 not including the terminating NUL.  If NumChar is not NULL, the number
932                 of characters represented by the return value will be written to
933                 where it points.
934 **/
935 size_t
936 EFIAPI
937 EstimateWtoM(const wchar_t * Src, size_t Limit, size_t *NumChar);
938 
939 /** Determine the number of characters in a MBCS string.
940 
941     @param[in]    Src     The string to examine
942 
943     @return   The number of characters represented by the MBCS string.
944 **/
945 size_t
946 EFIAPI
947 CountMbcsChars(const char *Src);
948 
949 __END_DECLS
950 
951 #endif  /* _STDLIB_H */
952