safec  3.0
Safe C Library - ISO TR24731 Bounds Checking Interface
safe_lib.h File Reference
#include "safe_config.h"
#include "safe_lib_errno.h"
#include "safe_types.h"
#include <time.h>
+ Include dependency graph for safe_lib.h:

Macros

#define EXTERN   extern
 
#define sl_default_handler   ignore_handler_s
 
#define TMP_MAX_S   308915776
 
#define L_tmpnam_s   1024
 

Functions

EXTERN void abort_handler_s (const char *restrict msg, void *restrict ptr, errno_t error)
 This function writes a message on the standard error stream in an implementation-defined format. More...
 
EXTERN void ignore_handler_s (const char *restrict msg, void *restrict ptr, errno_t error)
 This function simply returns to the caller. More...
 
EXTERN errno_t tmpnam_s (char *filename_s, rsize_t maxsize)
 Creates a unique valid file name (no longer than L_tmpnam in length) and stores it in character string pointed to by filename. More...
 
EXTERN errno_t tmpfile_s (FILE *restrict *restrict streamptr)
 The tmpfile_s function creates a temporary binary file that is different from any other existing file and that will automatically be removed when it is closed or at program termination. More...
 
EXTERN char * gets_s (char *dest, rsize_t dmax)
 
EXTERN errno_t fopen_s (FILE *restrict *restrict streamptr, const char *restrict filename, const char *restrict mode)
 The fopen_s function opens a file indicated by filename and updates the pointer to the file stream associated with that file. More...
 
EXTERN errno_t freopen_s (FILE *restrict *restrict newstreamptr, const char *restrict filename, const char *restrict mode, FILE *restrict stream)
 The freopen_s function first, attempts to close the file associated with the stream, ignoring any errors. More...
 
EXTERN errno_t asctime_s (char *dest, rsize_t dmax, const struct tm *tm)
 The asctime_s function converts the given calendar time tm to a textual representation of the following fixed 25-character form: "Www Mmm dd hh:mm:ss yyyy\n", as with asctime. More...
 
EXTERN errno_t ctime_s (char *dest, rsize_t dmax, const time_t *timer)
 The ctime_s function converts the given time since epoch to a calendar local time and then to a textual representation, as if by calling asctime_s(buffer, bufsz, localtime_s(time, &(struct tm){0})). More...
 
EXTERN struct tm * gmtime_s (const time_t *restrict timer, struct tm *restrict dest)
 The gmtime_s function converts the given time since epoch to a calendar time, expressed in Coordinated Universal Time (UTC) in the struct tm format. More...
 
EXTERN struct tm * localtime_s (const time_t *restrict timer, struct tm *restrict dest)
 The localtime_s function converts the given time since epoch to a calendar time, expressed in the current timezone in the struct tm format. More...
 
EXTERN errno_t getenv_s (size_t *restrict len, char *restrict dest, rsize_t dmax, const char *restrict name)
 The getenv_s function searches for an environmental variable with name name in the host-specified environment list and returns a pointer to the string that is associated with the matched environment variable. More...
 
EXTERN void * bsearch_s (const void *key, const void *base, rsize_t nmemb, rsize_t size, int(*compar)(const void *k, const void *y, void *context), void *context)
 The bsearch_s function finds an element equal to element pointed to by key in an array pointed to by base. More...
 
EXTERN errno_t qsort_s (void *base, rsize_t nmemb, rsize_t size, int(*compar)(const void *x, const void *y, void *context), void *context)
 

Macro Definition Documentation

◆ EXTERN

#define EXTERN   extern

◆ sl_default_handler

#define sl_default_handler   ignore_handler_s

◆ TMP_MAX_S

#define TMP_MAX_S   308915776

◆ L_tmpnam_s

#define L_tmpnam_s   1024

Function Documentation

◆ abort_handler_s()

EXTERN void abort_handler_s ( const char *restrict  msg,
void *restrict  ptr,
errno_t  error 
)

This function writes a message on the standard error stream in an implementation-defined format.

The message shall include the string pointed to by msg. The abort_handler_s function then calls the abort function.

Remarks
SPECIFIED IN ISO/IEC JTC1 SC22 WG14 N1172, Programming languages, environments and system software interfaces, Extensions to the C Library, Part I: Bounds-checking interfaces
Parameters
[in]msgPointer to the message describing the error
[in]ptrPointer to aassociated data. Can be NULL.
[in]errorThe error code encountered.
See also
ignore_handler_s()

◆ ignore_handler_s()

EXTERN void ignore_handler_s ( const char *restrict  msg,
void *restrict  ptr,
errno_t  error 
)

This function simply returns to the caller.

Remarks
SPECIFIED IN ISO/IEC JTC1 SC22 WG14 N1172, Programming languages, environments and system software interfaces, Extensions to the C Library, Part I: Bounds-checking interfaces
Parameters
[in]msgPointer to the message describing the error
[in]ptrPointer to aassociated data. Can be NULL.
[in]errorThe error code encountered.
See also
abort_handler_s()

◆ tmpnam_s()

EXTERN errno_t tmpnam_s ( char *  filename_s,
rsize_t  maxsize 
)

Creates a unique valid file name (no longer than L_tmpnam in length) and stores it in character string pointed to by filename.

The function is capable of generating up to TMP_MAX_S of unique filenames, but some or all of them may be in use in the filesystem and thus not suitable return values.

Remarks
SPECIFIED IN
Parameters
[out]filename_spointer to the character array capable of holding at least L_tmpnam_s bytes, to be used as a result buffer.
[in]maxsizemaximum number of characters the function is allowed to write (typically the size of the filename_s array).
Precondition
No more than TMP_MAX_S files may be opened
filename_s is a null pointer
maxsize is greater than RSIZE_MAX_STR
maxsize is less than the generated file name string
Returns
Returns zero and writes the file name to filename_s on success. On error, returns non-zero and writes the null character to filename_s[0] (only if filename_s is not null and maxsize is not zero and is not greater than RSIZE_MAX_STR).
Return values
EOKon success
ESNULLPwhen filename_s is a NULL pointer
ESZEROLwhen maxsize = 0
ESLEMAXwhen maxsize > RSIZE_MAX_STR or more than TMP_MAX_S files were opened.
errno()when tmpnam() failed, typically -ENOENT
Note
Although the names generated by tmpnam_s are difficult to guess, it is possible that a file with that name is created by another process between the moment tmpnam returns and the moment this program attempts to use the returned name to create a file. The standard function tmpfile and the POSIX function mkstemp do not have this problem (creating a unique directory using only the standard C library still requires the use of tmpnam_s).

POSIX systems additionally define the similarly named function tempnam(), which offers the choice of a directory (which defaults to the optionally defined macro P_tmpdir).

◆ tmpfile_s()

EXTERN errno_t tmpfile_s ( FILE *restrict *restrict  streamptr)

The tmpfile_s function creates a temporary binary file that is different from any other existing file and that will automatically be removed when it is closed or at program termination.

If the program terminates abnormally, whether an open temporary file is removed is implementation-defined. The file is opened for update with "wb+" mode with the meaning that mode has in the fopen_s function (including the mode’s effect on exclusive access and file permissions).

Remarks
SPECIFIED IN
Parameters
streamptrpointer to a pointer that will be updated by this function call
Precondition
streamptr shall not be a null pointer.
No more than TMP_MAX_S files may be opened

If the file was created successfully, then the pointer to FILE pointed to by streamptr will be set to the pointer to the object controlling the opened file. Otherwise, the pointer to FILE pointed to by streamptr will be set to a null pointer.

Returns
The tmpfile_s function returns zero if it created the file. If it did not create the file or there was a runtime-constraint violation, tmpfile_s returns a nonzero value. If there is a runtime-constraint violation, tmpfile_s does not attempt to create a file. Sets the streamptr on success.
Return values
EOKon success
ESNULLPwhen streamptr is a NULL pointer
ESLEMAXwhen more than TMP_MAX_S files were opened.
errno()when tmpfile() failed, typically ENOENT

◆ gets_s()

EXTERN char* gets_s ( char *  dest,
rsize_t  dmax 
)

◆ fopen_s()

EXTERN errno_t fopen_s ( FILE *restrict *restrict  streamptr,
const char *restrict  filename,
const char *restrict  mode 
)

The fopen_s function opens a file indicated by filename and updates the pointer to the file stream associated with that file.

mode is used to determine the file access mode.

Remarks
SPECIFIED IN
Parameters
[out]streamptrpointer to a FILE stream that will be updated by this function call
[in]filename
[in]modeas in fopen
Precondition
Neither streamptr, filename nor mode shall be a null pointer.

If the file was created successfully, then the pointer to the FILE pointed to by streamptr will be set to the pointer to the object controlling the opened file. Otherwise, the pointer to the FILE pointed to by streamptr will be set to a null pointer.

Returns
The fopen_s function returns zero if it created the file. If it did not create the file or there was a runtime-constraint violation, fopen_s returns a nonzero error code, sets streamptr to NULL. If there is a runtime-constraint violation, fopen_s does not attempt to create a file. Sets the streamptr on success.
Return values
EOKon success
ESNULLPwhen any argument is a NULL pointer
>0 any other errno

◆ freopen_s()

EXTERN errno_t freopen_s ( FILE *restrict *restrict  newstreamptr,
const char *restrict  filename,
const char *restrict  mode,
FILE *restrict  stream 
)

The freopen_s function first, attempts to close the file associated with the stream, ignoring any errors.

Then, if filename is not null, attempts to open the file specified by filename using mode as if by fopen, and associates that file with the file stream pointed to by stream. If filename is a null pointer, then the function attempts to reopen the file that is already associated with stream (it is implementation defined which mode changes are allowed in this case).

Remarks
SPECIFIED IN
Parameters
[out]newstreamptrpointer to a FILE stream that will be updated by this function call
[in]filenamefile name to associate the file stream to
[in]modeas in fopen
[in]streamthe file stream to modify
Precondition
Neither streamptr, stream nor mode shall be a null pointer.

If the file was reopened successfully, then the pointer to the FILE pointed to by newstreamptr will be set to the pointer to the object controlling the opened file. Otherwise, the pointer to the FILE pointed to by newstreamptr will be set to a null pointer.

Returns
The freopen_s function returns zero if it reopened the file. If not or there was a runtime-constraint violation, freopen_s returns a nonzero error code, and sets newstreamptr to NULL. If there is a runtime-constraint violation, freopen_s does not attempt to reopen the file. Sets the newstreamptr on success.
Return values
EOKon success
ESNULLPwhen any argument is a NULL pointer
>0 any other errno

◆ asctime_s()

EXTERN errno_t asctime_s ( char *  dest,
rsize_t  dmax,
const struct tm *  tm 
)

The asctime_s function converts the given calendar time tm to a textual representation of the following fixed 25-character form: "Www Mmm dd hh:mm:ss yyyy\n", as with asctime.

The message is copied into user-provided dest buffer, which is guaranteed to be null-terminated.

No more than dmax-1 bytes are written, the buffer is always null-terminated. Uses the re-entrant asctime_r() if available.

Remarks
SPECIFIED IN
  • C11 standard (ISO/IEC 9899:2011): K.3.8.2.1 The asctime_s function (p: 624-625) http://en.cppreference.com/w/c/chrono/asctime
  • ISO/IEC TR 24731, Programming languages, environments and system software interfaces, Extensions to the C Library, Part I: Bounds-checking interfaces
Parameters
[out]destpointer to a user-provided buffer.
[in]dmaxrestricted maximum length of dest
[in]tmpointer to a tm object specifying the time to print
Precondition
dest and tm shall not be a null pointer.
dmax shall not be less than 26 and greater than RSIZE_MAX_STR.
not all members of *tm are within their normal ranges, the year indicated by tm->tm_year is between 0-8099.
Returns
Zero if the entire message was successfully stored in dest, non-zero otherwise.
Return values
EOKon success
ESNULLPwhen dest or tm is a NULL pointer
ESLEMAXwhen dmax > RSIZE_MAX_STR or a tm member is too large
ESLEMINwhen dmax < 26 or a tm member is too small
ESNOSPCwhen dmax is too small for the result buffer
-1when asctime_r or asctime returned NULL
Note
This function returns a pointer to static data and is not thread-safe. POSIX marks this function obsolete and recommends strftime instead. The C standard also recommends strftime instead of asctime and asctime_s because strftime is more flexible and locale-sensitive. POSIX limits undefined behaviors only to when the output string would be longer than 25 characters, when tm->tm_wday or tm->tm_mon are not within the expected ranges, or when tm->tm_year exceeds INT_MAX-1990. Some implementations handle tm->tm_mday==0 as meaning the last day of the preceding month.
See also
ctime_s()

◆ ctime_s()

EXTERN errno_t ctime_s ( char *  dest,
rsize_t  dmax,
const time_t *  timer 
)

The ctime_s function converts the given time since epoch to a calendar local time and then to a textual representation, as if by calling asctime_s(buffer, bufsz, localtime_s(time, &(struct tm){0})).

The message is copied into the user-provided dest buffer, which is guaranteed to be null-terminated.

No more than dmax-1 bytes are written, the buffer is always null-terminated. The function does not support localization. Uses the re-entrant ctime_r() if available.

Remarks
SPECIFIED IN
  • C11 standard (ISO/IEC 9899:2011): K.3.8.2.2 The ctime_s function (p: 624-625) http://en.cppreference.com/w/c/chrono/ctime
  • ISO/IEC TR 24731, Programming languages, environments and system software interfaces, Extensions to the C Library, Part I: Bounds-checking interfaces
Parameters
[out]destpointer to a user-provided buffer.
[in]dmaxrestricted maximum length of dest
[in]timerpointer to a epoch (long, seconds since 1970)
Precondition
dest and timer shall not be a null pointer.
dmax shall not be less than 26 and greater than RSIZE_MAX_STR.
Returns
Zero if the entire message was successfully stored in dest, non-zero otherwise.
Return values
EOKon success
ESNULLPwhen dest or tm is a NULL pointer
ESLEMAXwhen dmax > RSIZE_MAX_STR
ESLEMINwhen dmax < 26 or *timer < 0
ESLEMAXwhen *timer > 313360441200L, the year 10000, resp. LONG_MAX on 32bit systems
ESNOSPCwhen dmax is too small for the result buffer
-1when ctime_r or ctime returned NULL
Note
ctime returns a pointer to static data and is not thread-safe. In addition, it modifies the static tm object which may be shared with gmtime and localtime. POSIX marks this function obsolete and recommends strftime instead. The C standard also recommends strftime instead of ctime and ctime_s because strftime is more flexible and locale-sensitive. The behavior of ctime may be undefined for the values of time_t that result in the string longer than 25 characters (e.g. year 10000).
See also
asctime_s()

◆ gmtime_s()

EXTERN struct tm* gmtime_s ( const time_t *restrict  timer,
struct tm *restrict  dest 
)

The gmtime_s function converts the given time since epoch to a calendar time, expressed in Coordinated Universal Time (UTC) in the struct tm format.

The result is copied into the user-provided tm struct.

Remarks
SPECIFIED IN
  • C11 standard (ISO/IEC 9899:2011): K.3.8.2.3 The gmtime_s function (p: 626-627) http://en.cppreference.com/w/c/chrono/gmtime
  • ISO/IEC TR 24731, Programming languages, environments and system software interfaces, Extensions to the C Library, Part I: Bounds-checking interfaces
Parameters
[in]timerpointer to a epoch (long, seconds since 1970)
[out]destpointer to a user-provided struct tm.
Precondition
timer and dest shall not be a null pointer.
Returns
copy of the dest pointer, or null pointer on error (which may be a runtime constraint violation or a failure to convert the specified time to UTC). May set errno to EOVERFLOW when *timer > 313360441200L, the year 10000, resp. LONG_MAX on 32bit systems or < 0, or to ESNULLP when dest or timer is a NULL pointer.
Note
gmtime returns a pointer to static data and is not thread-safe. When gmtime_r is available it used instead.

POSIX requires that this function sets errno to EOVERFLOW if it fails because the argument is too large. POSIX defines a thread-safe alternative gmtime_r, which is similar to the C11 function gmtime_s, except that it does not check the validity of its input parameters.

This function is available under windows with a different API, reversed argument order, and is not available with safeclib.

See also
localtime_s(), ctime_s()

◆ localtime_s()

EXTERN struct tm* localtime_s ( const time_t *restrict  timer,
struct tm *restrict  dest 
)

The localtime_s function converts the given time since epoch to a calendar time, expressed in the current timezone in the struct tm format.

The result is copied into the user-provided tm struct.

Remarks
SPECIFIED IN
  • C11 standard (ISO/IEC 9899:2011): K.3.8.2.4 The localtime_s function (p: 627) http://en.cppreference.com/w/c/chrono/localtime
  • ISO/IEC TR 24731, Programming languages, environments and system software interfaces, Extensions to the C Library, Part I: Bounds-checking interfaces
Parameters
[in]timerpointer to a epoch (long, seconds since 1970)
[out]destpointer to a user-provided struct tm.
Precondition
timer and dest shall not be a null pointer.
Returns
copy of the dest pointer, or null pointer on error (which may be a runtime constraint violation or a failure to convert the specified time to the current timezone). May set errno to EOVERFLOW when *timer > 313360441200L, the year 10000, resp. LONG_MAX on 32bit systems or < 0, or to ESNULLP when dest or timer is a NULL pointer.
Note
localtime returns a pointer to static data and is not thread-safe. When localtime_r is available it used instead.

POSIX requires that this function sets errno to EOVERFLOW if it fails because the argument is too large. POSIX defines a thread-safe alternative localtime_r, which is similar to the C11 function localtime_s, except that it does not check the validity of its input parameters.

This function is available under windows with a different API, reversed argument order, and is not available with safeclib.

See also
gmtime_s(), ctime_s()

◆ getenv_s()

EXTERN errno_t getenv_s ( size_t *restrict  len,
char *restrict  dest,
rsize_t  dmax,
const char *restrict  name 
)

The getenv_s function searches for an environmental variable with name name in the host-specified environment list and returns a pointer to the string that is associated with the matched environment variable.

The set of environmental variables and methods of altering it are implementation-defined. The value of the environment variable is written to the user-provided buffer value (unless null) and the number of bytes written is stored in the user-provided location *len (unless null). If the environment variable is not set in the environment, zero is written to *len (unless null) and '\0' is written to value[0] (unless null). With SAFECLIB_STR_NULL_SLACK defined all elements following the terminating null character (if any) written in the array of dmax characters pointed to by dest are nulled. If secure_getenv() is available, it is used.

Remarks
SPECIFIED IN
Parameters
[out]lenpointer to a size_t where getenv_s will store the length of the found environment variable. Might be NULL.
[out]destpointer to a string where getenv_s will store the contents of the found environment variable.
[in]dmaxmaximum number of characters that getenv_s is allowed to write to dest (size of the buffer).
[in]namenull-terminated character string identifying the name of the environmental variable to look for.
Precondition
name and dest shall not be a null pointer.
dmax shall not be greater than RSIZE_MAX_STR.
dmax shall not equal zero.
dmax shall be greater than the strlen of the returned env value.
Returns
zero if the environment variable was found, non-zero if it was not found of if a runtime constrant violation occurred. On any error, writes zero to *len (unless len is a null pointer).
Return values
EOKon success
-ESNULLPwhen dest or name are a NULL pointer
-ESZEROLwhen dmax = 0
-ESLEMAXwhen dmax > RSIZE_MAX_STR
-ESNOSPCwhen dmax is too small for the value
-1when not found

◆ bsearch_s()

EXTERN void* bsearch_s ( const void *  key,
const void *  base,
rsize_t  nmemb,
rsize_t  size,
int(*)(const void *k, const void *y, void *context)  compar,
void *  context 
)

The bsearch_s function finds an element equal to element pointed to by key in an array pointed to by base.

The array contains count elements of size bytes and must be partitioned with respect to key, that is, all the elements that compare less than must appear before all the elements that compare equal to, and those must appear before all the elements that compare greater than the key object. A fully sorted array satisfies these requirements. The elements are compared using function pointed to by comp. The behavior is undefined if the array is not already partitioned with respect to *key in ascending order according to the same criterion that compar uses.

Remarks
SPECIFIED IN
Parameters
[in]keypointer to the element to search for
[in]basepointer to the array to examine
[in]nmembnumber of elements in the array
[in]sizesize of each element in the array in bytes
[in]comparcomparison function which returns ​a negative integer value if the first argument is less than the second, a positive integer value if the first argument is greater than the second and zero if the arguments are equal. key is passed as the first argument, an element from the array as the second. The signature of the comparison function should be equivalent to the following: int cmp(const void *a, const void *b); The function must not modify the objects passed to it and must return consistent results when called for the same objects, regardless of their positions in the array.
[in]contextadditional information (e.g., collating sequence), passed to compar as the third argument
Precondition
key, base or compar shall not be a null pointer (unless nmemb is zero).
nmemb or size shall not be greater than RSIZE_MAX_MEM.

If the array contains several elements that compar would indicate as equal to the element searched for, then it is unspecified which element the function will return as the result.

Returns
Pointer to an element in the array that compares equal to *key, or null pointer if such element has not been found, or any run-time constraint violation.
Note
Despite the name, neither C nor POSIX standards require this function to be implemented using binary search or make any complexity guarantees. Unlike other bounds-checked functions, bsearch_s does not treat arrays of zero size as a runtime constraint violation and instead indicates element not found (the other function that accepts arrays of zero size is qsort_s).
Return values
NULLwhen not found or any error

errno values: ESNULLP when key, base or compar are a NULL pointer, and nmemb is > 0 ESLEMAX when nmemb or size > RSIZE_MAX_MEM

See also
qsort_s()

◆ qsort_s()

EXTERN errno_t qsort_s ( void *  base,
rsize_t  nmemb,
rsize_t  size,
int(*)(const void *x, const void *y, void *context)  compar,
void *  context 
)