6 LIBRARIES

This chapter contains the following sections:

Introduction
Header Files
C Libraries
Single Precision Floating Point
C Library Implementation Details
C Library Interface Description
C Library Reentrancy
Run-time Library

6.1 Introduction

This chapter describes the library functions delivered with the compiler. Some functions (e.g. printf(), scanf() ) can be edited to match your needs. ctri come with libraries in object format and with header files containing the appropriate prototype of the library functions. The library functions are also shipped in source code (C or assembly).

A number of standard operations within C are too complex to generate inline code for. These operations are implemented as run-time library functions. The run-time library routines are added to the C library.

6.2 Header Files

The following header files are delivered with the C compiler:

<assert.h> assert

<ctype.h> isalnum, isalpha, isascii, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit, toascii, _tolower, tolower, _toupper, toupper

<errno.h> Error numbers. No C functions.

<fcntl.h> Definition of flags used by open().

<float.h> copysign, isfinite, isinf, isnan, scalb. Constants related to floating point arithmetic.

<fss.h> Definitions for file system simulation.

<limits.h> Limits and sizes of integral types. No C functions.

<locale.h> localeconv, setlocale. Delivered as skeletons.

<malloc.h> Non-ANSI C header file with prototypes of malloc and free.

<math.h> acos, asin, atan, atan2, ceil, cos, cosh, exp, fabs, floor, fmod, frexp, ldexp, log, log10, modf, pow, sin, sinh, sqrt, tan, tanh

<setjmp.h> longjmp, setjmp

<signal.h> raise, signal. Functions are delivered as skeletons.

<stdarg.h> va_arg, va_end, va_start

<stddef.h> offsetof, definition of special types.

<stdio.h> clearerr, _close, fclose, feof, ferror, fflush, fgetc, fgetpos, fgets, fopen, fprintf, fputc, fputs, fread, freopen, fscanf, fseek, fsetpos, ftell, fwrite, getc, getchar, gets, _lseek, _open, perror, printf, putc, putchar, puts, _read, remove, rename, rewind, scanf, setbuf, setvbuf, sprintf, sscanf, tmpfile, tmpnam, ungetc, vfprintf, vprintf, vsprintf, _unlink, _write

<stdlib.h> abort, abs, atexit, atof, atoi, atol, bsearch, calloc, div, exit, free, getenv, labs, ldiv, malloc, mblen, mbstowcs, mbtowc, qsort, rand, realloc, srand, strtod, strtol, strtoul, system, wcstombs, wctomb

<string.h> memchr, memcmp, memcpy, memmove, memset, strcat, strchr, strcmp, strcol, strcpy, strcspn, strerror, strlen, strncat, strncmp, strncpy, strpbrk, strrchr, strspn, strstr, strtok, strxfrm

<time.h> asctime, clock, ctime, difftime, gmtime, localtime, mktime, strftime, time. All functions are delivered as skeletons.

<unistd.h> Non-ANSI C header file with prototypes for standard POSIX I/O functions. access, chdir, close, getcwd, lseek, read, stat, unlink, write.

6.3 C Libraries

The C library contains C library functions. All C library functions are described in this chapter. These functions are only called by explicit function calls in your application program.

Library directories

The protected library sets provide software bypasses for all TC112 and TC113 supported CPU functional problems. They must be used in conjunction with the appropriate C compiler workarounds for CPU functional problems. For more details refer to Appendix C, CPU Functional Problems.

The C library uses the following name syntax:

Library to link Description
libc.a (def.) C library double precision
libcs.a C library single precision (-F option)
libcs_fpu.a C library single precision with FPU instructions
(-F and -FPU options)
libfpn.a (def.) Floating point library (no trapping)
libfpt.a Floating point library (trapping)
libfpn_fpu.a Floating point library with FPU instructions
(no trapping, -FPU option)
libfpt_fpu.a Floating point library with FPU instructions
trapping, -FPU option)

Table 6-1: C and floating point library name syntax

The lktri linker is using this naming convention when specifying the -l option. For example, with -lc the linker is looking for libc.a in the system lib\tc1 directory. Specifying the libraries is a job taken care of by the control program.

When you use floating point, the floating point library must always be the last library linked, it should be placed after the C library. Arithmetic routines like sin(), cos(), etc. are not present in these libraries, they only contain basic floating point operations like ADD and MUL. These operations are only called implicitly in your application program.

The non-trapping floating point libraries libfpn.a and libfpn_fpu.a have been optimized for speed. As a result, they do not completely follow the IEEE-754 floating point standard for all exceptional cases.

6.3.1 Single Precision Floating Point

In ANSI C all mathematical functions (<math.h>), are based on double arguments and double return type. So, even if you are using only float variables in your code, the language definition dictates promotion to double, when using the math functions or floating point formatters (printf() and scanf()). The result is more code and less execution speed. In fact the ANSI approach introduces a performance penalty.

To improve the code size and execution speed, the compiler supports the option -F to force single precision floating point usage. If you use -F, a float variable passed as an argument is no longer promoted to double when calling a variable argument function or an old style K&R function, and the type double is treated as float. It is obvious that this affects the whole application (including libraries). Therefore, special single precision versions of the floating point libraries are delivered with the package. When using -F, these libraries must be used. It is not possible to mix C modules created with the -F option and C modules which are using the regular ANSI approach.

The -Fc option only treats floating point constants (having no suffix) as float instead of double.

6.3.2 C Library Implementation Details

A detailed description of the delivered C library is shown in the following list.

Explanation :

Y - Fully implemented
I - Implemented via file system simulation
L - Delivered as a skeleton

File Imple-
mented
Routine name Description / Reason
assert.h Y 'assert()' macro Macro definition
ctype.h Y




Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y





isalnum
isalpha
iscntrl
isdigit
isgraph
islower
isprint
ispunct
isspace
isupper
isxdigit
tolower
toupper
_tolower
_toupper
isascii
toascii
Most of the routines are
delivered as macro AND as
function (as prescribed by
ANSI).














Not defined by ANSI
Not defined by ANSI
Not defined by ANSI
Not defined by ANSI
errno.h Y Only Macros
fcntl.h Y
I

open
Definitions of flags used by _open
float.h Y
limits.h Y Only Macros
locale.h Y
L
L

localeconv
setlocale

No OS present
No OS present
math.h Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y

acos
asin
atan
atan2
ceil
cos
cosh
exp
fabs
floor
fmod
frexp
ldexp
log
log10
modf
pow
sin
sinh
sqrt
tan
tanh
setjmp.h Y
Y
Y

longjmp
setjmp
signal.h Y
Y
Y

raise
signal
stdarg.h Y
Y
Y
Y

va_arg
va_end
va_start
stddef.h Y Only Macros
stdio.h Y
Y
I
Y
Y
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
Y
I
I
I
I
L
L
I
I
Y
Y
Y
Y
L
L


Y
I
I
Y

clearerr
fclose
feof
ferror
fflush
fgetc
fgetpos
fgets
fopen
fprintf
fputc
fputs
fread
freopen
fscanf
fseek
fsetpos
ftell
fwrite
getc
getchar
gets
perror
printf
putc
putchar
puts
remove
rename
rewind
scanf
setbuf
setvbuf
sprintf
sscanf
tmpfile
tmpnam


ungetc
vfprintf
vprintf
vsprintf





































Delivered as a random name
generator, but should use
some process ID.
I
I
I
I
I
I
_close
_open
_lseek
_read
_unlink
_write





stdlib.h Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
L
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y

L
L
L
L
L
L

abort
abs
atexit
atof
atoi
atol
bsearch
calloc
div
exit
free
getenv
labs
ldiv
malloc
qsort
strtod
strtol
strtoul
rand
realloc
srand

system
mblen
mbstowcs
mbtowc
wcstombs
wctomb

Calls _exit() in cstart








Calls _exit() in cstart

No OS present











No OS present
wide chars not supported
wide chars not supported
wide chars not supported
wide chars not supported
wide chars not supported
string.h Y
Y
Y
Y
Y
Y
Y
Y
Y
L
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
L

memchr
memcmp
memcpy
memmove
memset
strcat
strchr
strcmp
strcoll
strcpy
strcspn
strerror
strlen
strncat
strncmp
strncpy
strpbrk
strrchr
strspn
strstr
strtok
strxfrm









wide chars not supported












wide chars not supported
time.h Y
Y
L
Y
Y
Y
Y
Y
Y
Y

asctime
clock
ctime
difftime
gmtime
localtime
mktime
strftime
time
real time clock not supported

Uses SYSTIM0 register
unistd.h Y
I
I
I
I
I
I
I
I
I

access
chdir
close
getcwd
lseek
read
stat
unlink
write
standard UNIX I/O functions

6.3.3 C Library Interface Description

_close

Low level file close function. _close is used by the functions close and fclose. The given file descriptor should be properly closed, any buffer is already flushed. This function interfaces to CrossView Pro's file system simulation.

_lseek

Low level file positioning function. _lseek is used by all file positioning functions (fgetpos, fseek, fsetpos, ftell, rewind). This function interfaces to CrossView Pro's file system simulation.

_open

Low level file open function. _open is used by the functions fopen and freopen. The given file descriptor should be properly opened. This function interfaces to CrossView Pro's file system simulation.

_read

Low level input function. It reads a sequence of characters from a file. This function interfaces to CrossView Pro's file system simulation.

Returns the number of characters read.

_tolower

Converts c to a lowercase character, does not check if c really is an uppercase character. This is a non-ANSI function.

Returns the converted character.

_toupper

Converts c to an uppercase character, does not check if c really is a lowercase character. This is a non-ANSI function.

Returns the converted character.

_unlink

Low level file remove function. _unlink is used by the function remove. This function interfaces to CrossView Pro's file system simulation.

_write

Low level ouput function. It writes a sequence of characters to a file. This function interfaces to CrossView Pro's file system simulation.

Returns the number of characters correctly written.

abort

Terminates the program abnormally. It calls the function _exit, which is defined in the start-up module.

Returns nothing.

abs

Returns the absolute value of the signed int argument.

access

Use the file system simulation feature of CrossView Pro to check the permissions of a file on the host. mode specifies the type of access and is a bit pattern constructed by a logical OR of the following values:

R_OK Checks read permission.
W_OK Checks write permission.
X_OK Checks execute (search) permission.
F_OK Checks to see if the file exists.

Returns zero if successful,
-1 on error.

acos

Returns the arccosine cos-1(x) of x in the range [0, pi],
x c [-1, 1].

asctime

Converts the time in the structure *tp into a string of the form:

Returns the time in string form.

asin

Returns the arcsine sin-1(x) of x in the range [-pi/2, pi/2],
x c [-1, 1].

assert

When compiled with NDEBUG, this is an empty macro. When compiled without NDEBUG defined, it checks if expr is true. If it is true, then a line like:

is printed.

Returns nothing.

atan

Returns the arctangent tan-1(x) of x in the range [-pi/2, pi/2].
x c [-1, 1].

atan2

Returns the result of: tan-1(y/x) in the range [-pi, pi].

atexit

Registers the function fcn to be called when the program terminates normally.

Returns zero, if program terminates normally.
non-zero, if the registration cannot be made.

atof

Converts the given string to a double value. White space is skipped, conversion is terminated at the first unrecognized character.

Returns the double value.

atoi

Converts the given string to an integer value. White space is skipped, conversion is terminated at the first unrecognized character.

Returns the integer value.

atol

Converts the given string to a long value. White space is skipped, conversion is terminated at the first unrecognized character.

Returns the long value.

bsearch

This function searches in an array of n members, for the object pointed to by ptr. The initial base of the array is given by base. The size of each member is specified by size. The given array must be sorted in ascending order, according to the results of the function pointed to by cmp.

Returns a pointer to the matching member in the array, or NULL when not found.

calloc

The allocated space is filled with zeros. The maximum space that can be allocated can be changed by customizing the heap size (see the section Heap ). By default no heap is allocated. When "calloc()" is used while no heap is defined, the locator gives an error.

Returns a pointer to space in external memory for nobj items of size bytes length.
NULL if there is not enough space left.

ceil

Returns the smallest integer not less than x, as a double.

chdir

Use the file system simulation feature of CrossView Pro to change the current directory on the host to the directory indicated by path.

Returns zero if successful,
-1 on error.

clearerr

Clears the end of file and error indicators for stream.

Returns nothing.

clock

Determines the processor time used.

Returns number of microseconds since the last reset, assuming a 100 MHz cpu.

close

File close function. The given file descriptor should be properly closed. This function calls _close.

Returns zero if successful,
-1 on error.

copysign

IEEE-754-1985 recommended function. Copy the sign of the second argument to the value of the first argument and return that as result.

Returns the first argument with the sign of the second argument.

cos

Returns the cosine of x.

cosh

Returns the hyperbolic cosine of x.

ctime

Converts the calender time *tp into local time, in string form. This function is the same as:

Returns the local time in string form.

difftime

Returns the result of time2 - time1 in seconds.

div

Both arguments are integers. The returned quotient and remainder are also integers.

Returns a structure containing the quotient and remainder of num divided by denom.

exit

Terminates the program normally. Acts as if 'main()' returns with status as the return value.

Returns zero, on successful termination.

exp

Returns the result of the exponential function ex.

fabs

Returns the absolute double value of x. |x|

fclose

Flushes any unwritten data for stream, discards any unread buffered input, frees any automatically allocated buffer, then closes the stream.

Returns zero if the stream is successfully closed, or EOF on error.

feof

Returns a non-zero value if the end-of-file indicator for stream is set.

ferror

Returns a non-zero value if the error indicator for stream is set.

fflush

Writes any buffered but unwritten date, if stream is an output stream. If stream is an input stream, the effect is undefined.

Returns zero if successful, or EOF on a write error.

fgetc

Reads one character from the given stream.

Returns the read character, or EOF on error.

fgetpos

Stores the current value of the file position indicator for the stream pointed to by stream in the object pointed to by ptr. The type fpos_t is suitable for recording such values.

Returns zero if successful,
a non-zero value on error.

fgets

Reads at most the next n-1 characters from the given stream into the array s until a newline is found.

Returns s, or NULL on EOF or error.

floor

Returns the largest integer not greater than x, as a double.

fmod

Returns the floating-point remainder of x/y, with the same sign as x. If y is zero, the result is implementation-defined.

fopen

Opens a file for a given mode.

Returns a stream. If the file cannot not be opened, NULL is returned.

You can specify the following values for mode:

 "r" read; open text file for reading

"w" write; create text file for writing; if the file already exists its contents is discarded

"a" append; open existing text file or create new text file for writing at end of file

"r+" open text file for update; reading and writing

"w+" create text file for update; previous contents if any is discarded

"a+" append; open or create text file for update, writes at end of file

The update mode (with a '+') allows reading and writing of the same file. In this mode the function fflush must be called between a read and a write or vice versa. By including the letter b after the initial letter, you can indicate that the file is a binary file. E.g. "rb" means read binary, "w+b" means create binary file for update. The filename is limited to FILENAME_MAX characters. At most FOPEN_MAX files may be open at once.

fprintf

Performs a formatted write to the given stream.

See also printf(), _write().

fputc

Puts one character onto the given stream.

See also _write().

Returns EOF on error.

fputs

Writes the string to a stream. The terminating NULL character is not written.

See also _write().

Returns NULL if successful, or EOF on error.

fread

Reads nobj members of size bytes from the given steam into the array pointed to by ptr.

See also _read().

Returns the number of successfully read objects.

free

Deallocates the space pointed to by p. p Must point to space earlier allocated by a call to "calloc()", "malloc()" or "realloc()". Otherwise the behavior is undefined.

See also calloc(), malloc() and realloc().

Returns nothing

freopen

Opens a file for a given mode associates the stream with it. This function is normally used to change the files associated with stdin, stdout, or stderr.

See also fopen().

Returns stream, or NULL on error.

frexp

Splits x into a normalized fraction in the interval [1/2, 1>, which is returned, and a power of 2, which is stored in *exp. If x is zero, both parts of the result are zero. For example: frexp( 4.0, &var ) results in 0.5·23. The function returns 0.5, and 3 is stored in var.

Returns the normalized fraction.

fscanf

Performs a formatted read from the given stream.

See also scanf(), _read().

Returns the number of items converted successfully.

fseek

Sets the file position indicator for stream. A subsequent read or write will access data beginning at the new position. For a binary file, the position is set to offset characters from origin, which may be SEEK_SET for the beginning of the file, SEEK_CUR for the current position in the file, or SEEK_END for the end-of-file. For a text stream, offset must be zero, or a value returned by ftell. In this case origin must be SEEK_SET.

Returns zero if successful,
a non-zero value on error.

fsetpos

Positions stream at the position recorded by fgetpos in *ptr.

Returns zero if successful,
a non-zero value on error.

ftell

Returns the current file position for stream, or
-1L on error.

fwrite

Writes nobj members of size bytes to the given stream from the array pointed to by ptr.

Returns the number of successfully written objects.

getc

Reads one character out of the given stream. Currently #defined as getchar(), because FILE I/O is not supported.

See also _read().

Returns the character read or EOF on error.

getchar

Reads one character from standard input.

See also _read().

Returns the character read or EOF on error.

getcwd

Use the file system simulation feature of CrossView Pro to retrieve the current directory on the host.

Returns the directory name if successful,
NULL on error.

getenv

Returns the environment string associated with name, or NULL if no string exists.

gets

Reads all characters from standard input until a newline is found. The newline is replaced by a NULL-character.

See also _read().

Returns a pointer to the read string or NULL on error.

gmtime

Converts the calender time *tp into Coordinated Universal Time (UTC).

Returns a structure representing the UTC, or NULL if UTC is not available.

isalnum

Returns a non-zero value when c is an alphabetic character or a number ([A-Z][a-z][0-9]).

isalpha

Returns a non-zero value when c is an alphabetic character ([A-Z][a-z]).

isascii

Returns a non-zero value when c is in the range of 0 and 127. This is a non-ANSI function.

iscntrl

Returns a non-zero value when c is a control character.

isdigit

Returns a non-zero value when c is a numeric character ([0-9]).

isfinite

IEEE-754-1985 recommended function. Test the given variable on being a finite (IEEE-754) value.

Returns zero if the variable is not finite, else non-zero.

isgraph

Returns a non-zero value when c is printable, but not a space.

isinf

IEEE-754-1985 recommended function. Test the given variable on being an infinite (IEEE-754) value.

Returns zero if the variable is not +-infinite, else non-zero.

islower

Returns a non-zero value when c is a lowercase character ([a-z]).

isnan

IEEE-754-1985 recommended function. Test the given variable on being a NaN (Not a Number, IEEE-754) value.

Returns zero if the variable is not NaN, else non-zero.

isprint

Returns a non-zero value when c is printable, including spaces.

ispunct

Returns a non-zero value when c is a punctuation character (such as '.', ',', '!', etc.).

isspace

Returns a non-zero value when c is a space type character (space, tab, vertical tab, formfeed, linefeed, carriage return).

isupper

Returns a non-zero value when c is an uppercase character ([A-Z]).

isxdigit

Returns a non-zero value when c is a hexadecimal digit ([0-9][A-F][a-f]).

labs

Returns the absolute value of the signed long argument.

ldexp

Returns the result of: 2 n.

ldiv

Both arguments are long integers. The returned quotient and remainder are also long integers.

Returns a structure containing the quotient and remainder of num divided by denom.

localeconv

Sets the components of an object with type struct lconv with values appropriate for the formatting of numeric quantities according to the rules of the current locale.

Returns a pointer to the filled-in object.

localtime

Converts the calender time *tp into local time.

Returns a structure representing the local time.

log

Returns the natural logarithm ln(x), x>0.

log10

Returns the base 10 logarithm log10(x), x>0.

longjmp

Restores the environment previously saved with a call to setjmp(). The function calling the corresponding call to setjmp() may not be terminated yet. The value of val may not be zero.

Returns nothing.

lseek

Moves read-write file offset. This function calls _lseek.

Returns the resulting pointer location if successful,
-1 on error.

malloc

The allocated space is not initialized. The maximum space that can be allocated can be changed by customizing the heap size (see the section Heap ). By default no heap is allocated. When "malloc()" is used while no heap is defined, the locator gives an error.

Returns a pointer to space in external memory of size bytes length. NULL if there is not enough space left.

mblen

Determines the number of bytes comprising the multi-byte character pointed to by s, if s is not a null pointer. Except that the shift state is not affected. At most n characters will be examined, starting at the character pointed to by s.

Returns the number of bytes, or 0 if s points to the null character, or -1 if the bytes do not form a valid multi-byte character.

mbstowcs

Converts a sequence of multi-byte characters that begins in the initial shift state from the array pointed to by s, into a sequence of corresponding codes and stores these codes into the array pointed to by pwcs, stopping after n codes are stored or a code with value zero is stored.

Returns the number of array elements modified (not including a terminating zero code, if any), or (size_t)-1 if an invalid multi-byte character is encountered.

mbtowc

Determines the number of bytes that comprise the multi-byte character pointed to by s. It then determines the code for value of type wchar_t that corresponds to that multi-byte character. If the multi-byte character is valid and pwc is not a null pointer, the mbtowc function stores the code in the object pointed to by pwc. At most n characters will be examined, starting at the character pointed to by s.

Returns the number of bytes, or 0 if s points to the null character, or -1 if the bytes do not form a valid multi-byte character.

memchr

Checks the first n bytes of cs on the occurrence of character c.

Returns NULL when not found, otherwise a pointer to the found character is returned.

memcmp

Compares the first n bytes of cs with the contents of ct.

Returns a value < 0 if cs < ct,
0 if cs = = ct,
or a value > 0 if cs > ct.

memcpy

Copies n characters from ct to s. No care is taken if the two objects overlap.

Returns s

memmove

Copies n characters from ct to s. Overlapping objects will be
handled correctly.

Returns s

memset

Fills the first n bytes of s with character c.

Returns s

mktime

Converts the local time in the structure *tp into calendar time.

Returns the calendar time, or -1 if it cannot be represented.

modf

Splits x into integral and fractional parts, each with the same sign as x. It stores the integral part in *ip.

Returns the fractional part.

offsetof

Returns the offset for the given member in an object of type.

open

Opens a file a file for reading or writing. This function calls _open.

See also fopen().

Returns the file descriptor if successful (a non-negative integer), or
-1 on error.

perror

Prints s and an implementation-defined error message corresponding to the integer errno, as if by:

fprintf( stderr, "%s: %s\n", s, "error message" );

The contents of the error message are the same as those returned by the strerror function with the argument errno.

See also the strerror() function.

Returns nothing.

pow

A domain error occurs if x=0 and y<=0, or if x<0 and y is not an integer.

Returns the result of x raised to the power of y: xy.

printf

Performs a formatted write to the standard output stream.

See also _write().

Returns the number of characters written to the output stream.

The format string may contain plain text mixed with conversion specifiers. Each conversion specifier should be preceded by a '%' character. The conversion specifier should be build in order:

- Flags (in any order):

- specifies left adjustment of the converted argument.

+ a number is always preceded with a sign character.
+ has higher precedence as space.

space a negative number is preceded with a sign, positive numbers with a space.

0 specifies padding to the field width with zeros (only for numbers).

# specifies an alternate output form. For o, the first digit will be zero. For x or X, "0x" and "0X" will be prefixed to the number. For e, E, f, g, G, the output always contains a decimal point, trailing zeros are not removed.

- A number specifying a minimum field width. The converted argument is printed in a field with at least the length specified here. If the converted argument has fewer characters than specified, it will be padded at the left side (or at the right when the flag '-' was specified) with spaces. Padding to numeric fields will be done with zeros when the flag '0' is also specified (only when padding left). Instead of a numeric value, also '*' may be specified, the value is then taken from the next argument, which is assumed to be of type int.

- A period. This separates the minimum field width from the precision.

- A number specifying the maximum length of a string to be printed. Or the number of digits printed after the decimal point (only for floating point conversions). Or the minimum number of digits to be printed for an integer conversion. Instead of a numeric value, also '*' may be specified, the value is then taken from the next argument, which is assumed to be of type int.

- A length modifier 'h', 'l' or 'L'. 'h' indicates that the argument is to be treated as a short or unsigned short number. 'l' should be used if the argument is a long integer. 'L' indicates that the argument is a long double.

Flags, length specifier, period, precision and length modifier are optional, the conversion character is not. The conversion character must be one of the following, if a character following '%' is not in the list, the behavior is undefined:

Character Printed as
d, i int, signed decimal
o int, unsigned octal
x, X int, unsigned hexadecimal in lowercase or uppercase respectively
u int, unsigned decimal
c int, single character (converted to unsigned char)
s char *, the characters from the string are printed until a NULL character is found. When the given precision is met before, printing will also stop
f double
e, E double
g, G double
n int *, the number of characters written so far is written into the argument. This should be a pointer to an integer in default memory. No value is printed.
p pointer (hexadecimal 24-bit value)
r _fract, _sfract
R _accum
% No argument is converted, a '%' is printed.

Table 6-2: Printf conversion characters

putc

Puts one character onto the given stream.

See also _write().

Returns EOF on error.

putchar

Puts one character onto standard output.

See also _write().

Returns the character written or EOF on error.

puts

Writes the string to stdout, the string is terminated by a newline.

See also _write().

Returns NULL if successful, or EOF on error.

qsort

This function sorts an array of n members. The initial base of the array is given by base. The size of each member is specified by size. The given array is sorted in ascending order, according to the results of the function pointed to by cmp.

Returns nothing.

raise

Sends the signal sig to the program.

See also signal().

Returns zero if successful, or a non-zero value if unsuccessful.

rand

Returns a sequence of pseudo-random integers, in the range 0 to RAND_MAX.

read

Reads a sequence of characters from a file. This function calls _read.

See also _read().

realloc

Reallocates the space for the object pointed to by p. The contents of the object will be the same as before calling realloc().The maximum space that can be allocated can be changed by customizing the heap size (see the section Heap ). By default no heap is allocated. When "realloc()" is used while no heap is defined, the linker gives an error.

See also malloc().

Returns NULL and *p is not changed, if there is not enough space for the new allocation. Otherwise a pointer to the newly allocated space for the object is returned.

remove

Removes the named file, so that a subsequent attempt to open it fails.

Returns zero if file is successfully removed, or
a non-zero value, if the attempt fails.

rename

Changes the name of the file.

Returns zero if file is successfully renamed, or
a non-zero value, if the attempt fails.

rewind

Sets the file position indicator for the stream pointed to by stream to the beginning of the file. This function is equivalent to:

(void) fseek( stream, 0L, SEEK_SET );
clearerr( stream );

Returns nothing.

scalb

IEEE-754-1985 Recommended function.

Returns d * 2^power for integral values power without computing 2^N.

scanf

Performs a formatted read from the standard input stream.

See also _read().

Returns the number of items converted successfully.

All arguments to this function should be pointers to variables (in default memory) of the type which is specified in the format string.

The format string may contain :

- Blanks or tabs, which are skipped.

- Normal characters (not '%'), which should be matched exactly in the input stream.

- Conversion specifications, starting with a '%' character.

Conversion specifications should be built as follows (in order) :

- A '*', meaning that no assignment is done for this field.

- A number specifying the maximum field width.

- The conversion characters d, i, n, o, u and x can be preceeded by 'h' if the argument is a pointer to short rather than int, or by 'l' (letter ell) if the argument is a pointer to long. The conversion characters e, f, and g can be preceeded by 'l' if a pointer double rather than float is in the argument list, and by 'L' if a pointer to a long double.

- A conversion specifier. '*', maximum field width and length modifier are optional, the conversion character is not. The conversion character must be one of the following, if a character following '%' is not in the list, the behavior is undefined.

Length specifier and length modifier are optional, the conversion character is not. The conversion character must be one of the following, if a character following '%' is not in the list, the behavior is undefined.

Character Scanned as
d int, signed decimal.
i int, the integer can be octal (i.e. with a leading 0) or hexadecimal (leading "0x" or "0X"), or just decimal.
o int, unsigned octal.
u int, unsigned decimal.
x int, unsigned hexadecimal in lowercase or uppercase.
c single character (converted to unsigned char).
s char *, a string of non white space characters. The argument should point to an array of characters, large enough to hold the string and a terminating NULL character.
f float
e, E float
g, G float
n int *, the number of characters written so far is written into the argument. No scanning is done.
p pointer; hexadecimal 24-bit value which must be entered without 0x- prefix.
r _fract, _sfract
R _accum
[...] Matches a string of input characters from the set between the brackets. A NULL character is added to terminate the string. Specifying []...] includes the ']' character in the set of scanning characters.
[^...] Matches a string of input characters not in the set between the brackets. A NULL character is added to terminate the string. Specifying [^]...] includes the ']' character in the set.
% Literal '%', no assignment is done.

Table 6-3: Scanf conversion characters

setbuf

Buffering is turned off for the stream, if buf is NULL.
Otherwise, setbuf is equivalent to:

Returns nothing.

See also setvbuf().

setjmp

Saves the current environment for a subsequent call to longjmp.

Returns 0 after a direct call to setjmp(). Calling the function "longjmp()" using the saved env restores the current environment and jumps to this place with a non-zero return value.

See also longjmp().

setlocale

Selects the appropriate portion of the program's locale as specified by the category and locale arguments.

Returns the string associated with the specified category for the new locale if the selection can be honored.
null pointer if the selectioin cannot be honored.

setvbuf

Controls buffering for the stream; this function must be called before reading or writing. mode can have the following values:

_IOFBF causes full buffering
_IOLBF causes line buffering of text files
_IONBF causes no buffering

If buf is not NULL, it will be used as a buffer; otherwise a buffer will be allocated. size determines the buffer size.

Returns zero if successful
a non-zero value for an error.

See also setbuf().

signal

Determines how subsequent signals will be handled. If handler is SIG_DFL, the default behavior is used; if handler is SIG_IGN, the signal is ignored; otherwise, the function pointed to by handler will be called, with the argument of the type of signal. Valid signals are:

SIGABRT abnormal termination, e.g. from abort
SIGFPE arithmetic error, e.g. zero divide or overflow
SIGILL illegal function image, e.g. illegal instruction
SIGINT interactive attention, e.g. interrupt
SIGSEGV illegal storage access, e.g. access outside
memory limits
SIGTERM termination request sent to this program

When a signal sig subsequenly occurs, the signal is restored to its default behavior; then the signal-handler function is called, as if by (*handler)(sig). If the handler returns, the execution will resume where it was when the signal occurred.

Returns the previous value of handler for the specific signal, or SIG_ERR if an error occurs.

sin

Returns the sine of x.

sinh

Returns the hyperbolic sine of x.

sprintf

Performs a formatted write to a string.

See also printf().

sqrt

Returns the square root of x. Vx, where x >= 0.

srand

This function uses seed as the start of a new sequence of pseudo-random numbers to be returned by subsequent calls to srand(). When srand is called with the same seed value, the sequence of pseudo-random numbers generated by rand() will be repeated.

Returns pseudo random numbers.

sscanf

Performs a formatted read from a string.

See also scanf().

stat

Use the file system simulation feature of CrossView Pro to stat() a file on the host platform.

Returns zero if successful,
-1 on error.

strcat

Concatenates string ct to string s, including the trailing NULL character.

Returns s

strchr

Returns a pointer to the first occurrence of character c in the string cs. If not found, NULL is returned.

strcmp

Compares string cs to string ct.

Returns <0 if cs < ct,
0 if cs == ct,
>0 if cs > ct.

strcoll

Compares string cs to string ct. The comparison is based on strings interpreted as appropriate to the program's locale.

Returns <0 if cs < ct,
0 if cs = = ct,
>0 if cs > ct.

strcpy

Copies string ct into the string s, including the trailing NULL character.

Returns s

strcspn

Returns the length of the prefix in string cs, consisting of characters not in the string ct.

strerror

Returns pointer to implementation-defined string corresponding to error n.

strftime

Formats date and time information from the structure *tp into s according to the specified format fmt. fmt is analogous to a printf format. Each %c is replaced as described below:

Ordinary characters (including the terminating `\0`) are copied into s. No more than smax characters are placed into s.

Returns the number of characters ('\0' not included), or
zero if more than smax characters where produced.

strlen

Returns the length of the string in cs, not counting the NULL character.

strncat

Concatenates string ct to string s, at most n characters are copied. Add a trailing NULL character.

Returns s

strncmp

Compares at most n bytes of string cs to string ct.

Returns <0 if cs < ct,
0 if cs == ct,
>0 if cs > ct.

strncpy

Copies string ct onto the string s, at most n characters are copied. Add a trailing NULL character if the string is smaller than n characters.

Returns s

strpbrk

Returns a pointer to the first occurrence in cs of any character out of string ct. If none are found, NULL is returned.

strrchr

Returns a pointer to the last occurrence of c in the string cs. If not found, NULL is returned.

strspn

Returns the length of the prefix in string cs, consisting of characters in the string ct.

strstr

Returns a pointer to the first occurrence of string ct in the string cs. Returns NULL if not found.

strtod

Converts the initial portion of the string pointed to by s to a double value. Initial white spaces are skipped. When endp is not a NULL pointer, after this function is called, *endp will point to the first character not used by the conversion.

Returns the read value.

strtok

Search the string s for tokens delimited by characters from string ct. It terminates the token with a NULL character.

Returns a pointer to the token. A subsequent call with
s == NULL will return the next token in the string.

strtol

Converts the initial portion of the string pointed to by s to a long integer. Initial white spaces are skipped. Then a value is read using the given base. When base is zero, the base is taken as defined for integer constants. I.e. numbers starting with an '0' are taken octal, numbers starting with '0x' or '0X' are taken hexadecimal. Other numbers are taken decimal. When endp is not a NULL pointer, after this function is called, *endp will point to the first character not used by the conversion.

Returns the read value.

strtoul

Converts the initial portion of the string pointed to by s to an unsigned long integer. Initial white spaces are skipped. Then a value is read using the given base. When base is zero, the base is taken as defined for integer constants. I.e. numbers starting with an '0' are taken octal, numbers starting with '0x' or '0X' are taken hexadecimal. Other numbers are taken decimal. When endp is not a NULL pointer, after this function is called, *endp will point to the first character not used by the conversion.

Returns the read value.

strxfrm

Transforms the string pointed to by cs and places the resulting string into the array pointed to by ct. No more than n characters are placed into the resulting string pointed to by ct, including the terminating null character.

Returns the length of the transformed string.

system

Passes the string s to the environment for execution.

Returns a non-zero value if there is a command processor, if s is NULL; or an implementation-dependent value, if s is not NULL.

tan

Returns the tangent of x.

tanh

Returns the hyperbolic tangent of x.

time

The return value is also assigned to *tp, if tp is not NULL.

Returns the current calendar time, or -1 if the time is not available.

tmpfile

Creates a temporary file of the mode "wb+" that will be automatically removed when closed or when the program terminates normally.

Returns a stream if successful, or NULL if the file could not be created.

tmpnam

Creates a temporary name (not a file). Each time tmpnam is called a different name is created.
tmpnam(NULL) creates a string that is not the name of an existing file, and returns a pointer to an internal static array. tmpnam(s) creates a string and stores it in s and also returns it as the function value. s must have room for at least L_tmpnam characters. At most TMP_MAX different names are guaranteed during execution of the program.

Returns a pointer to the temporary name, as described above.

toascii

Converts c to an ascii value (strip highest bit). This is a non-ANSI function.

Returns the converted value.

tolower

Returns c converted to a lowercase character if it is an uppercase character, otherwise c is returned.

toupper

Returns c converted to an uppercase character if it is a lowercase character, otherwise c is returned.

ungetc

Pushes at the most one character back onto the input buffer.

Returns EOF on error.

unlink

Removes the named file, so that a subsequent attempt to open it fails. This function calls _unlink.

Returns zero if file is successfully removed, or
a non-zero value, if the attempt fails.

va_arg

Returns the value of the next argument in the variable argument list. It's return type has the type of the given argument type. A next call to this macro will return the value of the next argument.

va_end

This macro must be called after the arguments have been processed. It should be called before the function using the macro 'va_start' is terminated (ANSI specification).

va_start

This macro initializes ap. After this call, each call to va_arg() will return the value of the next argument. In our implementation, va_list cannot contain any bit type variables. Also the given argument lastarg must be the last non-bit type argument in the list.

vfprintf

Is equivalent to vprintf, but writes to the given stream.

See also vprintf(), _write().

vprintf

Does a formatted write to standard output. Instead of a variable argument list as for printf(), this function expects a pointer to the list.

See also printf(), _write().

vsprintf

Does a formatted write a string. Instead of a variable argument list as for printf(), this function expects a pointer to the list.

See also printf(), _write().

wcstombs

Converts a sequence of codes that correspond to multi-byte characters from the array pointed to by pwcs, into a sequence of multi-byte characters that begins in the initial shift state and stores these multi-byte characters into the array pointed to by s, stopping if a multi-byte character would exceed the limit of n total bytes or if a null character is stored.

Returns the number of bytes modified (not including a terminating null character, if any), or (size_t)-1 if a code is encountered that does not correspond to a valid multi-byte character.

wctomb

Determines the number of bytes needed to represent the multi-byte corresponding to the code whose value is wchar (including any change in the shift state). It stores the multi-byte character representation in the array pointed to by s (if s is not a null pointer). At most MB_CUR_MAX characters are stored. If the value of wchar is zero, the wctomb function is left in the initial shift state.

Returns the number of bytes, or -1 if the value of wchar does not correspond to a valid multi-byte character.

write

Write a sequence of characters to a file. This function calls _write.

See also _write().

6.3.4 C Library Reentrancy

Some of the functions in the C library are reentrant, others are not. The table below shows the functions in the C library, whether they are reentrant and, if not, the reason why. Note that some of the functions are not reentrant because they set the global variable 'errno'. If your program does not check this variable and errno is the only reason for the function not being reentrant, these functions can be assumed reentrant as well.

The explanation of the cause why a function is not reentrant sometimes refers to a footnote because the explanation is to lengthy for the table.

Function Reentrant Cause
abort no Calls exit
abs yes -
access no Uses global File System Simulation buffer, _fss_buffer
acos no Function sets errno when error occurs. If errno not used, acos is reentrant.
asctime no asctime defines static array for broken-down time string.
asin no Function sets errno when error occurs. If errno not used, asin is reentrant.
atan yes -
atan2 yes -
atexit no atexit defines static array with function pointers to execute at exit of program.
atof yes -
atoi yes -
atol yes -
bsearch yes -
calloc no calloc uses static buffer management structures. See malloc (5).
ceil yes -
chdir no Uses global File System Simulation buffer, _fss_buffer
cleanup no Calls fclose. See (1)
clearerr no Modifies iob[]. See (1)
clock yes -
close no Calls _close
_close no Uses global File System Simulation buffer, _fss_buffer
cos yes -
cosh no cosh calls exp(), which sets errno. If errno is discarded, cosh is reentrant.
ctime no Calls asctime
difftime yes -
div yes -
_doflt no Uses I/O functions which modify iob[].
See (1).
_doprint no Uses indirect access to static iob[] array. See (1).
_doscan no Uses indirect access to iob[] and calls ungetc (access to local static ungetc[] buffer). See (1).
exit no Calls fclose indirectly which uses iob[] calls functions in _atexit array. See (1). To make exit reentrant kernel support is required.
exp no Sets errno. If errno not used, exp is reentrant.
fabs yes -
fclose no Uses values in iob[]. See (1).
feof no Uses values in iob[]. See (1).
ferror no Uses values in iob[]. See (1).
fflush no Modifies iob[]. See (1).
fgetc no Uses pointer to iob[]. See (1).
fgetpos no Sets the variable errno and uses pointer to iob[]. See (1) / (2).
fgets no Uses iob[]. See (1).
_filbuf no Uses iob[]. See (1).
floor yes -
_flsbuf no Uses iob[]. See (1).
fmod yes -
fopen no Uses iob[] and calls malloc when file open for buffered IO. See (1)
fprintf no Uses iob[]. See (1).
fputc no Uses iob[]. See (1).
fputs no Uses iob[]. See (1).
fread no Calls fgetc. See (1).
free no free uses static buffer management structures. See malloc (5).
freopen no Modifies iob[]. See (1).
frexp yes -
fscanf no Uses iob[]. See (1)
fseek no Uses iob[] and calls _doscan. Acesses ungetc[] array. See (1).
fsetpos no Uses iob[] and sets errno. See (1) / (2).
ftell no Uses iob[] and sets errno. Calls _lseek. See (1) / (2).
fwrite no Uses iob[]. See (1).
getc no Uses iob[]. See (1).
getchar no Uses iob[]. See (1).
getcwd no Uses global File System Simulation buffer, _fss_buffer
getenv yes Skeleton only.
_getflt no Uses iob[ ]. See (1).
gets no Uses iob[ ]. See (1).
gmtime no gmtime defines static structure
halloc no Needs kernel support. See malloc (5).
hcalloc no hcalloc uses static buffer management structures. See malloc (5).
hfree no hfree uses static buffer management structures. See malloc (5).
hrealloc no See malloc (5).
_iob no Defines static iob[]. See (1).
_ioread no Depends on low level I/O implementation. Uses iob[]. See (1).
_iowrite no Depends on low level I/O implementation. Uses iob[ ]. See (1).
isalnum yes -
isalpha yes -
isascii yes -
iscntrl yes -
isdigit yes -
isgraph yes -
islower yes -
isprint yes -
ispunct yes -
isspace yes -
isupper yes -
isxdigit yes -
_itoa yes -
labs yes -
ldexp no Sets errno. See (2).
ldiv yes -
localeconv - Skeleton function
localtime yes
log no Sets errno. See (2).
log10 no Calls log. See (2).
longjmp yes -
lseek no Calls _lseek
_lseek no Uses global File System Simulation buffer, _fss_buffer
ltoa yes -
malloc no Needs kernel support. See (5).
mblen - Skeleton function
mbstowcs - Skeleton function
mbtowc - Skeleton function
memchr yes -
memcmp yes -
memcpy yes -
memmove yes -
memset yes -
mktime yes -
modf yes -
open no Calls _open
_open no Uses global File System Simulation buffer, _fss_buffer
perror no Uses errno. See (2)
pow no Sets errno. See (2)
printf no Uses iob[ ]. See (1)
putc no Uses iob[ ]. See (1)
putchar no Uses iob[ ]. See (1)
puts no Uses iob[ ]. See (1)
qsort yes -
raise no Updates the signal handler table
rand no Uses static variable to remember latest random number. Must diverge from ANSI standard to define reentrant rand. See (4).
read no Calls _read
_read no Uses global File System Simulation buffer, _fss_buffer
realloc no See malloc (5).
remove - Skeleton only.
rename - Skeleton only.
rewind - Skeleton only.
sbrk no Allocates memory which is assigned at locate time. Needs kernel for memory management.
scanf no Uses iob[ ], calls _doscan. See (1).
setbuf no Sets iob[ ]. See (1).
setjmp yes -
setlocale - Skeleton function
setvbuf no Sets iob and calls malloc. See (1) / (5).
signal no Updates the signal handler table
sin yes -
sinh no Sinh calls exp() which sets errno.
If errno is discarded sinh is reentrant.
sprintf no Calls doprint. See (1).
sqrt no Sets errno. See (2).
srand no See rand
sscanf no Calls _doscan
stat no Uses global File System Simulation buffer, _fss_buffer
strcat yes -
strchr yes -
strcmp yes -
strcoll - Skeleton function
strcpy yes -
strcspn yes -
strerror yes -
strftime yes -
strlen yes -
strncat yes -
strncmp yes -
strncpy yes -
strpbrk yes -
strrchr yes -
strspn yes -
strstr yes -
strtod yes -
strtok no Strtok saves last position in string in local static variable. This function is not reentrant by design. See (4).
strtol no Sets errno. See (2).
strtoul no Sets errno. See (2).
strxfrm - Skeleton function
system - Skeleton function
tan no Sets errno. See (2).
tanh no Uses sinh for calculation.
time no Uses static variable which defines initial start time
tmpfile no Uses iob[ ]. See (1).
tmpnam no Uses local buffer to build filename.
Function can be adapted to use user buffer. This makes the function non ANSI. See (4).
toascii yes -
tolower yes -
toupper yes -
ungetc no Uses static buffer to hold ungetted characters for each file. Can be moved into iob structure. See (1).
unlink no Calls _unlink
_unlink no Uses global File System Simulation buffer, _fss_buffer
vfprintf no Uses iob[ ], calls doprint. See (1).
vprintf no Uses iob[ ], calls doprint. See (1).
vsprintf no Calls doprint.
wcstombs - Skeleton function
wctomb - Skeleton function
write no Calls _write
_write no Uses global File System Simulation buffer, _fss_buffer

Table 6-4: C library reentrancy


Several functions in the C library are not reentrant due to the following reasons:

- The iob[] structure is static. This influences all I/O functions.

- The ungetc[] array is static. This array holds the characters (one for each stream) when ungetc() is called.

- The variable errno is globally defined. The following functions read or modify errno:

- _doprint and _doscan use static variables for e.g. character counting in strings.

- Some string functions use locally defined (static) buffers. This is prescribed by ANSI.

- malloc uses a static heap space.

The following description discusses these items into more detail. The numbers at the begin of each paragraph relate to the number references in the table above.

(1) iob structures

The I/O part of the C library is not reentrant by design. This is mainly caused by the static declaration of the iob[] array. The functions which use elements of this array access these elements via pointers ( FILE * ).

Building a multi-process system that is created in one link-run is hard to do. The C language scoping rules for external variables make it difficult to create a private copy of the iob[] array. Currently, the iob[] array has external scope. Thus it is visible in every module involved in one link phase. If these modules comprise several tasks (processes) in a system each of which should have its private copy of iob[], it is apparent that the iob[] declaration should be changed. This requires adaption of the library to the multi-tasking environment. The library modules must use a process identification as an index for determining which iob[] array to use. Thus the library is suitable for interfacing to that kernel only.

Another approach for the iob[] declaration problem is to declare the array static in one of the modules which create a task. Thus there can be more than one iob[] array is the system without having conflicts at link time. This brings several restrictions: Only the module that holds the declaration of the static iob[] can use the standard file handles stdin, stdout and stderr (which are the first three entries in iob[]). Thus all I/O for these three file handles should be located in one module.

(2) errno declaration

Several functions in the C library set the global variable errno. After completion of the function the user program may consult this variable to see if some error occurred. Since most of the functions that set errno already have a return type (this is the reason for using errno) it is not possible to check successful completion via the return type.

The library routines can set errno to the values defined in errno.h. See the file errno.h for more information.

errno can be set to ERR_FORMAT by the print and scan functions in the C library if you specify illegal format strings.

errno can be set to ERR_NOFLOAT by the scan functions if you use floating point formatting while using the SMALL formatting routines. See also the next section Printf and Scanf Formatting Routines.

errno will never be set to ERR_NOLONG or ERR_NOPOINT since the Tricore C library supports long and pointer conversion routines for input and output.

errno can be set to ERANGE by the following functions: exp(), strtol(), strtoul() and tan(). These functions may produce results that are out of the valid range for the return type. If so, the result of the function will be the largest representable value for that type and errno is set to ERANGE.

errno is set to EDOM by the following functions: acos(), asin(), log(), pow() and sqrt(). If the arguments for these functions are out of their valid range ( e.g. sqrt( -1 ) ), errno is set to EDOM.

errno can be set to ERR_POS by the file positioning functions ftell(), fsetpos() and fgetpos().

(3) ungetc

Currently the ungetc buffer is static. For each file entry in the iob[] structure array, there is one character available in the buffer to unget a character.

(4) local buffers

tmpnam() creates a temporary filename and returns a pointer to a local static buffer. This is according to the ANSI definition. Changing this function such that it creates the name in a user specified buffer requires another calling interface. Thus the function would be no longer portable.

strtok() scans through a string and remembers that the string and the position in the string for subsequent calls. This function is not reentrant by design. Making it reentrant requires support of a kernel to store the information on a per process basis.

rand() generates a sequence of random numbers. The function uses the value returned by a previous call to generate the next value in the sequence. This function can be made reentrant by specifying the previous random value as one of the arguments. However, then it is no longer a standard function.

(5) malloc

Malloc uses a heap space which is assigned at locate time. Thus this implementation is not reentrant. Making a reentrant malloc requires that the sbrk() function can do some sort of system call to obtain free memory space on a per process basis. This is not easy to solve within the current context of the library. This requires adaption to a kernel.

This paragraph on reentrancy applies to multi-process environments only. If reentrancy is required for calling library functions from an exception handler, another approach is required. For such a situation it is of no use to allocate e.g. multiple iob[] structures. In such a situation several pieces of code in the library have to be declared 'atomic': this means that interrupts have to be disabled while executing an atomic piece of code.

6.4 Run-time Library

Some compiler generated code contains calls to run-time library functions that would use too much code if generated as inline code. The name of a run-time library function always contains two leading underscores.

The run-time library functions are included in the C library (libc.a or libcs.a).


Copyright © 2002 Altium BV