a64l
Converts base64 to 32-bit integer, the posix way.
- const char* s
- long
abort
Terminates program abnormally.
This function first tries to trigger your SIGABRT handler. If the
signal handler returns, then signal(SIGABRT, SIG_DFL)
is called
before SIGABRT is raised again.
abs
Returns absolute value of ๐ฅ.
This function is a footgun since your argument may be narrrowed. Consider using labs(), llabs(), or better yet a macro like this:
#define ABS(X) ((X) >= 0 ? (X) : -(X))Note that passing
x
as INT_MIN
is undefined behavior, which
depends on whether or not your c library as well as the objects
that call it were built using the -fwrapv
or -ftrapv
flags.
- int x
- int
accept
Creates client socket file descriptor for incoming connection.
- int fd
- is the server socket file descriptor
- struct sockaddr* opt_out_addr
- will receive the remote address
- unsigned int* opt_inout_addrsize
- provides and receives addr's byte length
- int
- client fd which needs close(), or -1 w/ errno
accept4
Creates client socket file descriptor for incoming connection.
- int fd
- is the server socket file descriptor
- struct sa* opt_out_addr
- will receive the remote address
- unsigned int* opt_inout_addrsize
- provides and receives out_addr's byte length
- int flags
- can have SOCK_{CLOEXEC,NONBLOCK}, which may apply to both the newly created socket and the server one
- int
- client fd which needs close(), or -1 w/ errno
access
Checks if effective user can access path in particular ways.
This is equivalent to saying:
faccessat(AT_FDCWD, path, mode, 0);
- const char* path
- is a filename or directory
- int mode
- can be R_OK, W_OK, X_OK, F_OK
- int
- 0 if ok, or -1 w/ errno
acos
Returns arc cosine of ๐ฅ.
- double x
- double
- value in range [0,M_PI]
- NAN if ๐ฅ โ {NAN,+INFINITY,-INFINITY}
- NAN if ๐ฅ โ [-1,1]
- NAN if ๐ฅ โ {NAN,+INFINITY,-INFINITY}
acosh
Returns inverse hyperbolic cosine of ๐ฅ.
- double x
- double
acoshf
Returns inverse hyperbolic cosine of ๐ฅ.
- float x
- float
acosl
Returns arc cosine of ๐ฅ.
- long double x
- long double
AcquireToken
Atomically decrements signed byte index if it's positive.
Multiple threads are able to call this method, to determine if enough
tokens exist to perform an operation. Return values greater than zero
mean a token was atomically acquired. Values less than, or equal zero
means the bucket is empty. There must exist 1 << c
signed bytes (or
buckets) in the b
array.
Since this design uses signed bytes, your returned number may be used to control how much burstiness is allowed. For example:
int t = AcquireToken(tok.b, ip, 22); if (t < 64) { if (t > 8) write(client, "HTTP/1.1 429 \r\n\r\n", 17); close(client); return; }Could be used to send rejections to clients that exceed their tokens, whereas clients who've grossly exceeded their tokens, could simply be dropped.
- _Atomic char* b
- is array of token buckets
- unsigned int x
- is ipv4 address
- int c
- is cidr
- int
__addvdi3
Returns ๐ฅ+๐ฆ, aborting on overflow.
- long x
- long y
- long
__addvsi3
Returns ๐ฅ+๐ฆ, aborting on overflow.
- int x
- int y
- int
__addvti3
Returns ๐ฅ+๐ฆ, aborting on overflow.
- __int128 x
- __int128 y
- __int128
adler32
Updates running Adler-32 checksum with the bytes buf[0..len-1] and return the updated checksum. If buf is Z_NULL, this function returns the required initial value for the checksum.
- unsigned long
adler32_combine
Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note that the off_t type (like off_t) is a signed integer. If len2 is negative, the result has no meaning or utility.
- unsigned long
alarm
Asks for single-shot SIGALRM to be raise()'d after interval.
- unsigned int seconds
- is how long to wait before raising SIGALRM (which will only happen once) or zero to clear any previously scheduled alarm
- unsigned int
- seconds that were remaining on the previously scheduled alarm, or zero if there wasn't one (failure isn't possible)
aligned_alloc
Same as memalign(a, n) but requires IS2POW(a).
- unsigned long a
- unsigned long n
- number of bytes needed
- void*
- memory address, or NULL w/ errno
__appendd
Appends data to buffer, e.g.
char *b = 0; appendd(&b, "hello", 5); free(b);The resulting buffer is guaranteed to be NUL-terminated, i.e.
!b[appendz(b).i]
will be the case.
- char** b
- void* s
- may contain nul characters and may be null if
l
is zero - unsigned long l
- is byte length of
s
- long
- bytes appended (always
l
) or -1 ifENOMEM
__appendf
Appends formatted string to buffer, e.g.
char *b = 0; appendf(&b, "hello %d\n", 123); free(b);
- char** b
- const char* fmt
- ...
- const char* fmt
- long
- bytes appended or -1 if
ENOMEM
__appendr
Resets length of append buffer, e.g.
char *b = 0; appends(&b, "hello"); appendr(&b, 1); assert(!strcmp(b, "h")); appendr(&b, 0); assert(!strcmp(b, "")); free(b);If
i
is greater than the current length then the extra bytes are
filled with NUL characters. If i
is less than the current length
then memory is released to the system.
The resulting buffer is guaranteed to be NUL-terminated, i.e.
!b[appendz(b).i]
will be the case even if both params are 0.
- char** b
- unsigned long i
- long
i
or -1 ifENOMEM
AppendResourceReport
Generates process resource usage report.
- char** b
- struct rusage* ru
- const char* nl
- struct rusage* ru
- void
__appends
Appends string to buffer, e.g.
char *b = 0; appends(&b, "hello"); free(b);The resulting buffer is guaranteed to be NUL-terminated, i.e.
!b[appendz(b).i]
will be the case.
- char** b
- const char* s
- long
- bytes appended (always
strlen(s)
) or -1 ifENOMEM
__appendw
Appends character or word-encoded string to buffer.
Up to eight characters can be appended. For example:
appendw(&s, 'h'|'i'<<8); appendw(&s, READ64LE("hi\0\0\0\0\0"));Are equivalent to:
appends(&s, "hi");The special case:
appendw(&s, 0);Will append a single NUL character.
This function is slightly faster than appendd() and appends(). Its main advantage is it improves code size in functions that call it.
The resulting buffer is guaranteed to be NUL-terminated, i.e.
!b[appendz(b).i]
will be the case.
- char** b
- unsigned long w
- long
- bytes appended or -1 if
ENOMEM
__appendz
Returns size of append buffer.
- char* p
- must be 0 or have been allocated by an append*() function
- struct z
- i is number of bytes stored in buffer
- n is number of bytes in allocation
__asan_check
Checks validity of memory range.
This is normally abstracted by the compiler. In some cases, it may be
desirable to perform an ASAN memory safety check explicitly, e.g. for
system call wrappers that need to vet memory passed to the kernel, or
string library routines that use the dontasan
keyword due to compiler
generated ASAN being too costly. This function is fast especially for
large memory ranges since this takes a few picoseconds for each byte.
- void* p
- is starting virtual address
- long n
- is number of bytes to check
- struct f
- kind is 0 on success or <0 if invalid
- shadow points to first poisoned shadow byte
__asan_check_str
Checks validity of nul-terminated string.
This is similar to __asan_check(p, 1)
except it checks the validity
of the entire string including its trailing nul byte, and goes faster
than calling strlen() beforehand.
- const char* p
- is starting virtual address
- struct f
- kind is 0 on success or <0 if invalid
- shadow points to first poisoned shadow byte
__asan_is_valid
Checks memory validity of memory region.
- void* p
- long n
- _Bool
__asan_is_valid_iov
Checks memory validity of iov
array and each buffer it describes.
- struct iovec* iov
- int iovlen
- _Bool
__asan_is_valid_str
Checks memory validity of nul-terminated string.
- const char* p
- _Bool
__asan_is_valid_strlist
Checks memory validity of null-terminated nul-terminated string list.
- char** p
- _Bool
asin
Returns arc sine of ๐ฅ.
- double x
- double
- value in range [-M_PI/2,M_PI/2]
- NAN if ๐ฅ โ {NAN,+INFINITY,-INFINITY}
- NAN if ๐ฅ โ [-1,1]
- NAN if ๐ฅ โ {NAN,+INFINITY,-INFINITY}
asinhf
Returns inverse hyperbolic sine of ๐ฅ.
- float x
- float
asinl
Returns arc sine of ๐ฅ.
- long double x
- long double
asprintf
Formats string, allocating needed memory.
- char** strp
- const char* fmt
- ...
- const char* fmt
- int
- bytes written (excluding NUL) or -1 w/ errno
__assert_fail
Handles assert() failure.
- const char* expr
- const char* file
- int line
- const char* file
- void
atanh
Returns inverse hyperbolic tangent of ๐ฅ.
- double x
- double
atanhf
Returns inverse hyperbolic tangent of ๐ฅ.
- float x
- float
atanhl
Returns inverse hyperbolic tangent of ๐ฅ.
- long double x
- long double
atexit
Adds global destructor.
Destructors are called in reverse order. They won't be called if the program aborts or _exit() is called. Invocations of this function are usually generated by the C++ compiler.
- void(*)() f
- int
- 0 on success or nonzero if out of space
atoi
Decodes decimal integer from ASCII string.
atoi 10โธ 22๐ 7๐๐ strtol 10โธ 37๐ 12๐๐ strtoul 10โธ 35๐ 11๐๐ wcstol 10โธ 30๐ 10๐๐ wcstoul 10โธ 30๐ 10๐๐ strtoimax 10โธ 80๐ 26๐๐ strtoumax 10โธ 78๐ 25๐๐ wcstoimax 10โธ 77๐ 25๐๐ wcstoumax 10โธ 76๐ 25๐๐
- const char* s
- is a non-null nul-terminated string
- int
- the decoded signed saturated integer
atol
Decodes decimal integer from ASCII string.
- const char* s
- is a non-null nul-terminated string
- long
- the decoded signed saturated integer
AttachDebugger
Launches GDB debugger GUI for current process.
This function abstracts the toilsome details of configuring the best possible UX for debugging your app, for varying levels of available information, on most of the various platforms.
Before calling this function, consider placing ShowCrashReports() in your main function and calling DebugBreak() wherever you want; it's safer. Also note the "GDB" environment variable can be set to empty string, as a fail-safe for disabling this behavior.
- long continuetoaddr
- can be a code address, 0, or -1 for auto
- int
- gdb pid if continuing, 0 if detached, or -1 w/ errno
basename
Returns pointer to last filename component in path, e.g.
path โ dirname() โ basename() โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 0 โ . โ . . โ . โ . .. โ . โ .. / โ / โ / usr โ . โ usr /usr/ โ / โ usr /usr/lib โ /usr โ libBoth / and \ are are considered valid component separators on all platforms. Trailing slashes are ignored. We don't grant special consideration to things like foo/., c:/, \\?\Volume, etc.
- char* path
- is UTF-8 and may be mutated, but not expanded in length
- char*
- pointer to path, or inside path, or to a special r/o string
bcmp
Tests inequality of first ๐ bytes of ๐ and ๐.
bcmp n=0 992 picoseconds bcmp n=1 992 ps/byte 984 mb/s bcmp n=2 661 ps/byte 1,476 mb/s bcmp n=3 441 ps/byte 2,214 mb/s bcmp n=4 330 ps/byte 2,952 mb/s bcmp n=5 264 ps/byte 3,690 mb/s bcmp n=6 165 ps/byte 5,905 mb/s bcmp n=7 189 ps/byte 5,166 mb/s bcmp n=8 124 ps/byte 7,873 mb/s bcmp n=9 183 ps/byte 5,314 mb/s bcmp n=15 110 ps/byte 8,857 mb/s bcmp n=16 62 ps/byte 15,746 mb/s bcmp n=17 175 ps/byte 5,577 mb/s bcmp n=31 96 ps/byte 10,169 mb/s bcmp n=32 93 ps/byte 10,497 mb/s bcmp n=33 80 ps/byte 12,179 mb/s bcmp n=80 37 ps/byte 26,244 mb/s bcmp n=128 36 ps/byte 26,994 mb/s bcmp n=256 27 ps/byte 35,992 mb/s bcmp n=16384 19 ps/byte 49,411 mb/s bcmp n=32768 27 ps/byte 34,914 mb/s bcmp n=131072 30 ps/byte 32,303 mb/s
- void* a
- void* b
- unsigned long n
- void* b
- int
- 0 if a and b have equal contents, otherwise nonzero
bcopy
Moves memory the BSD way.
Please use memmove() instead. Note the order of arguments.
- void* src
- void* dest
- unsigned long n
- void* dest
- void
bind
Assigns local address and port number to socket, e.g.
struct sockaddr_in in = {AF_INET, htons(12345), {htonl(0x7f000001)}}; int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); bind(fd, (struct sockaddr *)&in, sizeof(in));On Windows, Cosmopolitan's implementation of bind() takes care of always setting the WIN32-specific
SO_EXCLUSIVEADDRUSE
option on
inet stream sockets in order to safeguard your servers from tests
- int fd
- is the file descriptor returned by socket()
- struct sa* addr
- is usually the binary-encoded ip:port on which to listen
- unsigned int addrsize
- is the byte-length of addr's true polymorphic form
- int
- 0 on success or -1 w/ errno
bing
Turns binary octet into unicode glyph representation.
Cosmopolitan displays RADIX-256 numbers using these digits:
0123456789abcdef 0ย โบโปโฅโฆโฃโ โขโโโโโโชโซโผ 1โบโโโผยถยงโฌโจโโโโโโโฒโผ 2 !"#$%&'()*+,-./ 30123456789:;<=>? 4@ABCDEFGHIJKLMNO 5PQRSTUVWXYZ[\]^_ 6`abcdefghijklmno 7pqrstuvwxyz{|}~โ 8รรผรฉรขรคร รฅรงรชรซรจรฏรฎรฌรร 9รรฆรรดรถรฒรปรนรฟรรยขยฃยฅโฌฦ aรกรญรณรบรฑรยชยบยฟโยฌยฝยผยกยซยป bโโโโโคโกโขโโโฃโโโโโโ cโโดโฌโโโผโโโโโฉโฆโ โโฌโง dโจโคโฅโโโโโซโชโโโโโโโ eฮฑรฮฯฮฃฯฮผฯฮฆฮฮฉฮดโฯฮตโฉ fโกยฑโฅโคโ โกรทโยฐโยทโโฟยฒโ ฮปIBM designed these glyphs for the PC to map onto the display bytes at (char *)0xb8000. Because IBM authorized buyers of its PCs to inspect and/or modify this region of memory, it became widely understood by many developers as a quick way to visualize arbitrary data that's so superior to hexdump -- a use-case that's lived on longer than the CGA graphics card for which it was designed.
- int b
- is binary octet to pictorally represent
- int intent
- controls canonical multimappings: โ โย ,\nโ,ฮตโโโฌ,ย ฮป,etc.
- int
BLAKE2B256
Computes blake2b 256bit message digest.
blake2b256 n=0 191 nanoseconds blake2b256 n=8 23 ns/byte 40,719 kb/s blake2b256 n=31 6 ns/byte 153 mb/s blake2b256 n=32 6 ns/byte 158 mb/s blake2b256 n=63 3 ns/byte 312 mb/s blake2b256 n=64 3 ns/byte 317 mb/s blake2b256 n=128 1 ns/byte 640 mb/s blake2b256 n=256 1 ns/byte 662 mb/s blake2b256 n=22851 1 ns/byte 683 mb/s
- void* data
- is binary memory to hash
- unsigned long len
- is bytes in
data
- unsigned char* out
- receives 32 byte binary digest
- int
- 0 on success (always successful)
BLAKE2B256_Process
- struct ctx* b2b
- const unsigned long* data
- int
BLAKE2B256_Update
- struct ctx* b2b
- void* in_data
- unsigned long len
- void* in_data
- int
bsearch
Searches sorted array for exact item in logarithmic time.
- void* key
- void* base
- unsigned long nmemb
- unsigned long size
- int(*)() cmp
- void* base
- void*
bsearch_r
Searches sorted array for exact item in logarithmic time.
- void* key
- void* base
- unsigned long nmemb
- unsigned long size
- int(*)() cmp
- void* arg
- void* base
- void*
_bsf
Returns position of first bit set.
ctz(๐ฅ) 31^clz(๐ฅ) clz(๐ฅ) uint32 ๐ฅ _bsf(๐ฅ) tzcnt(๐ฅ) ffs(๐ฅ) _bsr(๐ฅ) lzcnt(๐ฅ) 0x00000000 wut 32 0 wut 32 0x00000001 0 0 1 0 31 0x80000001 0 0 1 31 0 0x80000000 31 31 32 31 0 0x00000010 4 4 5 4 27 0x08000010 4 4 5 27 4 0x08000000 27 27 28 27 4 0xffffffff 0 0 1 31 0
- int x
- is a 32-bit integer
- int
- number in range 0..31 or undefined if ๐ฅ is 0
_bsfl
Returns position of first bit set.
ctz(๐ฅ) 31^clz(๐ฅ) clz(๐ฅ) uint32 ๐ฅ _bsf(๐ฅ) tzcnt(๐ฅ) ffs(๐ฅ) _bsr(๐ฅ) lzcnt(๐ฅ) 0x00000000 wut 32 0 wut 32 0x00000001 0 0 1 0 31 0x80000001 0 0 1 31 0 0x80000000 31 31 32 31 0 0x00000010 4 4 5 4 27 0x08000010 4 4 5 27 4 0x08000000 27 27 28 27 4 0xffffffff 0 0 1 31 0
- long x
- int
- number in range 0..63 or undefined if ๐ฅ is 0
_bsr
Returns binary logarithm of ๐ฅ.
ctz(๐ฅ) 31^clz(๐ฅ) clz(๐ฅ) uint32 ๐ฅ _bsf(๐ฅ) tzcnt(๐ฅ) ffs(๐ฅ) _bsr(๐ฅ) lzcnt(๐ฅ) 0x00000000 wut 32 0 wut 32 0x00000001 0 0 1 0 31 0x80000001 0 0 1 31 0 0x80000000 31 31 32 31 0 0x00000010 4 4 5 4 27 0x08000010 4 4 5 27 4 0x08000000 27 27 28 27 4 0xffffffff 0 0 1 31 0
- int x
- is a 32-bit integer
- int
- number in range 0..31 or undefined if ๐ฅ is 0
_bsr128
Returns binary logarithm of integer ๐ฅ.
uint32 ๐ฅ _bsf(๐ฅ) tzcnt(๐ฅ) ffs(๐ฅ) bsr(๐ฅ) lzcnt(๐ฅ) 0x00000000 wut 32 0 wut 32 0x00000001 0 0 1 0 31 0x80000001 0 0 1 31 0 0x80000000 31 31 32 31 0 0x00000010 4 4 5 4 27 0x08000010 4 4 5 27 4 0x08000000 27 27 28 27 4 0xffffffff 0 0 1 31 0
- rsi:rdi
- is 128-bit unsigned ๐ฅ value
- eax number in range [0,128) or undef if ๐ฅ is 0
_bsrl
Returns binary logarithm of ๐ฅ.
ctz(๐ฅ) 31^clz(๐ฅ) clz(๐ฅ) uint32 ๐ฅ _bsf(๐ฅ) tzcnt(๐ฅ) ffs(๐ฅ) _bsr(๐ฅ) lzcnt(๐ฅ) 0x00000000 wut 32 0 wut 32 0x00000001 0 0 1 0 31 0x80000001 0 0 1 31 0 0x80000000 31 31 32 31 0 0x00000010 4 4 5 4 27 0x08000010 4 4 5 27 4 0x08000000 27 27 28 27 4 0xffffffff 0 0 1 31 0
- long x
- is a 64-bit integer
- int
- number in range 0..63 or undefined if ๐ฅ is 0
_bt
Shows backtrace if crash reporting facilities are linked.
- const char* fmt
- ...
- void
bulk_free
Frees and clears (sets to NULL) each non-null pointer in given array.
This is twice as fast as freeing them one-by-one. If footers are used, pointers that have been allocated in different mspaces are not freed or cleared, and the count of all such pointers is returned. For large arrays of pointers with poor locality, it may be worthwhile to sort this array before calling bulk_free.
- void** p
- unsigned long n
- unsigned long
bzero
Sets memory to zero.
bzero n=0 661 picoseconds bzero n=1 661 ps/byte 1,476 mb/s bzero n=2 330 ps/byte 2,952 mb/s bzero n=3 220 ps/byte 4,428 mb/s bzero n=4 165 ps/byte 5,904 mb/s bzero n=7 94 ps/byte 10,333 mb/s bzero n=8 41 ps/byte 23,618 mb/s bzero n=15 44 ps/byte 22,142 mb/s bzero n=16 20 ps/byte 47,236 mb/s bzero n=31 21 ps/byte 45,760 mb/s bzero n=32 20 ps/byte 47,236 mb/s bzero n=63 10 ps/byte 92,997 mb/s bzero n=64 15 ps/byte 62,982 mb/s bzero n=127 15 ps/byte 62,490 mb/s bzero n=128 10 ps/byte 94,473 mb/s bzero n=255 14 ps/byte 68,439 mb/s bzero n=256 9 ps/byte 105 gb/s bzero n=511 15 ps/byte 62,859 mb/s bzero n=512 11 ps/byte 83,976 mb/s bzero n=1023 15 ps/byte 61,636 mb/s bzero n=1024 10 ps/byte 88,916 mb/s bzero n=2047 9 ps/byte 105 gb/s bzero n=2048 8 ps/byte 109 gb/s bzero n=4095 8 ps/byte 115 gb/s bzero n=4096 8 ps/byte 118 gb/s bzero n=8191 7 ps/byte 129 gb/s bzero n=8192 7 ps/byte 130 gb/s bzero n=16383 6 ps/byte 136 gb/s bzero n=16384 6 ps/byte 137 gb/s bzero n=32767 6 ps/byte 140 gb/s bzero n=32768 6 ps/byte 141 gb/s bzero n=65535 15 ps/byte 64,257 mb/s bzero n=65536 15 ps/byte 64,279 mb/s bzero n=131071 15 ps/byte 63,166 mb/s bzero n=131072 15 ps/byte 63,115 mb/s bzero n=262143 15 ps/byte 62,052 mb/s bzero n=262144 15 ps/byte 62,097 mb/s bzero n=524287 15 ps/byte 61,699 mb/s bzero n=524288 15 ps/byte 61,674 mb/s bzero n=1048575 16 ps/byte 60,179 mb/s bzero n=1048576 15 ps/byte 61,330 mb/s bzero n=2097151 15 ps/byte 61,071 mb/s bzero n=2097152 15 ps/byte 61,065 mb/s bzero n=4194303 16 ps/byte 60,942 mb/s bzero n=4194304 16 ps/byte 60,947 mb/s bzero n=8388607 16 ps/byte 60,872 mb/s bzero n=8388608 16 ps/byte 60,879 mb/s
- void* p
- is memory address
- unsigned long n
- is byte length
- void
- p
c16rtomb
- char* s
- unsigned short c16
- unsigned int* ps
- unsigned short c16
- unsigned long
c32rtomb
- char* s
- unsigned int c
- unsigned int* t
- unsigned int c
- unsigned long
calloc
Allocates n * itemsize bytes, initialized to zero.
- unsigned long n
- is number of items
- unsigned long itemsize
- is size of each item
- void*
- rax is memory address, or NULL w/ errno
CategorizeIp
Classifies IP address.
- unsigned int x
- int
- integer e.g. kIpLoopback, kIpPrivate, etc.
cfgetispeed
Returns input baud rate.
- struct termios* t
- unsigned int
cfgetospeed
Returns output baud rate.
- struct termios* t
- unsigned int
cfsetispeed
Sets input baud rate.
- struct termios* t
- unsigned int speed
- can be
B0
,B50
,B38400
,B4000000
, etc.
- int
- 0 on success, or -1 w/ errno
speed
isn't valid
cfsetospeed
Sets output baud rate.
- struct termios* t
- unsigned int speed
- can be
B0
,B50
,B38400
,B4000000
, etc.
- int
- 0 on success, or -1 w/ errno
speed
isn't valid
cfsetspeed
Sets input and output baud rate.
- struct termios* t
- unsigned int speed
- can be
B0
,B50
,B38400
,B4000000
, etc.
- int
- 0 on success, or -1 w/ errno
speed
isn't valid
chdir
Sets current directory.
This does *not* update the PWD
environment variable.
- const char* path
- int
- 0 on success, or -1 w/ errno
__check_fail
Handles failure of CHECK_xx() macros.
- const char* suffix
- const char* opstr
- unsigned long want
- const char* wantstr
- unsigned long got
- const char* gotstr
- const char* file
- int line
- const char* fmt
- ...
- const char* opstr
- void
_check_sigchld
Checks to see if SIGCHLD should be raised on Windows.
- void
- true if a signal was raised
CheckForMemoryLeaks
Tests for memory leaks.
This function needs to call __cxa_finalize(). Therefore any runtime services that depend on malloc() cannot be used, after calling this function.
- void
chmod
Changes permissions on file, e.g.:
CHECK_NE(-1, chmod("foo/bar.txt", 0644)); CHECK_NE(-1, chmod("o/default/program.com", 0755)); CHECK_NE(-1, chmod("privatefolder/", 0700));The esoteric bits generally available on System Five are:
CHECK_NE(-1, chmod("/opt/", 01000)); // sticky bit CHECK_NE(-1, chmod("/usr/bin/sudo", 04755)); // setuid bit CHECK_NE(-1, chmod("/usr/bin/wall", 02755)); // setgid bit
- const char* pathname
- must exist
- unsigned int mode
- contains octal flags (base 8)
- int
_chomp
Mutates line to remove line-ending characters.
- char* line
- is NULL-propagating
- char*
_chomp16
Mutates line to remove line-ending characters.
- unsigned short* line
- is NULL-propagating
- unsigned short*
chown
Changes owner and/or group of pathname.
- const char* pathname
- unsigned int uid
- is user id, or -1u to not change
- unsigned int gid
- is group id, or -1u to not change
- int
- 0 on success, or -1 w/ errno
chroot
Changes root directory.
Please consider using unveil() instead of chroot(). If you use this system call then consider using both chdir() and closefrom() before calling this function. Otherwise there's a small risk that fchdir() could be used to escape the chroot() environment. Cosmopolitan Libc focuses on static binaries which make chroot() infinitely easier to use since you don't need to construct an entire userspace each time however unveil() is still better to use on modern Linux and OpenBSD because it doesn't require root privileges.
- const char* path
- shall become the new root directory
- int
- 0 on success, or -1 w/ errno
path
path
exists as non-directory
path
length exceeds PATH_MAX
path
exists longer than NAME_MAX
path
is bad memory
path
doesn't exist
_classifypath
Classifies file path name.
For the purposes of this function, we always consider backslash interchangeable with forward slash, even though the underlying operating system might not. Therefore, for the sake of clarity, remaining documentation will only use the forward slash.
This function behaves the same on all platforms. For instance, this
function will categorize C:/FOO.BAR
as a DOS path, even if you're
running on UNIX rather than DOS.
If you wish to check if a pathname is absolute, in a manner that's inclusive of DOS drive paths, DOS rooted paths, in addition to the New Technology UNC paths, then you may do the following:
if (_classifypath(str) & _kPathAbs) { ... }To check if path is a relative path:
if (~_classifypath(str) & _kPathAbs) { ... }Please note the above check includes rooted paths such as
\foo
which is considered absolute by MSDN and we consider it absolute
although, it's technically relative to the current drive letter.
Please note that /foo/bar
is an absolute path on Windows, even
though it's actually a rooted path that's considered relative to
current drive by WIN32.
- const char* s
- int
- integer value that's one of following:
0
if non-weird relative path e.g.c
_kPathAbs
if absolute (or rooted dos) path e.g./โฏ
_kPathDos
ifc:
,d:foo
i.e. drive-relative path_kPathAbs|_kPathDos
if proper dos path e.g.c:/foo
_kPathDos|_kPathDev
if dos device path e.g.nul
,conin$
_kPathAbs|_kPathWin
if//c
,//?c
, etc._kPathAbs|_kPathWin|_kPathDev
if//./โฏ
,//?/โฏ
_kPathAbs|_kPathWin|_kPathDev|_kPathRoot
if//.
or//?
_kPathAbs|_kPathNt
e.g.\??\\โฏ
(undoc. strict backslash)
clearerr
Clears eof and error state indicators on stream.
- struct FILE* f
- is file object stream pointer
- void
clearerr_unlocked
Clears eof and error state indicators on stream.
- struct FILE* f
- is file object stream pointer
- void
__clk_tck
Returns system clock ticks per second.
The returned value is memoized. This function is intended to be
used via the CLK_TCK
macro wrapper.
The returned value is always greater than zero. It's usually 100 hertz which means each clock tick is 10 milliseconds long.
- int
clock
Returns sum of CPU time consumed by current process since birth.
This function provides a basic idea of how computationally expensive your program is, in terms of both the userspace and kernel processor resources it's hitherto consumed. Here's an example of how you might display this information:
printf("consumed %g seconds of cpu time\n", (double)clock() / CLOCKS_PER_SEC);This function offers at best microsecond accuracy on all supported platforms. Please note the reported values might be a bit chunkier depending on the kernel scheduler sampling interval see
CLK_TCK
.
- long
- units of CPU time consumed, where each unit's time length
should be
1./CLOCKS_PER_SEC
seconds; Cosmopolitan currently returns the unit count in microseconds, i.e.CLOCKS_PER_SEC
is hard-coded as 1000000. On failure this returns -1 / errno.
clock_getres
Returns granularity of clock.
- int clock
- ANONYMOUS-STRUCT* ts
- int
- 0 on success, or -1 w/ errno
clock
isn't supported on this system
ts
points to bad memory
clock_gettime
Returns nanosecond time.
This is a high-precision timer that supports multiple definitions of time. Among the more popular is CLOCK_MONOTONIC. This function has a zero syscall implementation of that on modern x86.
rdtsc l: 13๐ 4๐๐ gettimeofday l: 44๐ 14๐๐ clock_gettime l: 40๐ 13๐๐ __clock_gettime l: 35๐ 11๐๐ sys_clock_gettime l: 220๐ 71๐๐
- int clock
- can be one of:
-
CLOCK_REALTIME
: universally supported -CLOCK_REALTIME_FAST
: ditto but faster on freebsd -CLOCK_REALTIME_PRECISE
: ditto but better on freebsd -CLOCK_REALTIME_COARSE
: : likeCLOCK_REALTIME_FAST
w/ Linux 2.6.32+ -CLOCK_MONOTONIC
: universally supported -CLOCK_MONOTONIC_FAST
: ditto but faster on freebsd -CLOCK_MONOTONIC_PRECISE
: ditto but better on freebsd -CLOCK_MONOTONIC_COARSE
: : likeCLOCK_MONOTONIC_FAST
w/ Linux 2.6.32+ -CLOCK_MONOTONIC_RAW
: is actually monotonic but needs Linux 2.6.28+ -CLOCK_PROCESS_CPUTIME_ID
: linux and bsd -CLOCK_THREAD_CPUTIME_ID
: linux and bsd -CLOCK_MONOTONIC_COARSE
: linux, freebsd -CLOCK_PROF
: linux and netbsd -CLOCK_BOOTTIME
: linux and openbsd -CLOCK_REALTIME_ALARM
: linux-only -CLOCK_BOOTTIME_ALARM
: linux-only -CLOCK_TAI
: linux-only - ANONYMOUS-STRUCT* ts
- is where the result is stored
- int
- 0 on success, or -1 w/ errno
clock
isn't supported on this system
ts
points to bad memory
__clock_gettime_get
Returns pointer to fastest clock_gettime().
- _Bool* opt_out_isfast
- int(*)()
clock_nanosleep
Sleeps for particular amount of time.
Here's how you could sleep for one second:
clock_nanosleep(0, 0, &(struct timespec){1}, 0);Your sleep will be interrupted automatically if you do something like press ctrl-c during the wait. That's an
EINTR
error and it lets you
immediately react to status changes. This is always the case, even if
you're using SA_RESTART
since this is a @norestart
system call.
void OnCtrlC(int sig) {} // EINTR only happens after delivery signal(SIGINT, OnCtrlC); // do delivery rather than kill proc printf("save me from sleeping forever by pressing ctrl-c\n"); clock_nanosleep(0, 0, &(struct timespec){INT_MAX}, 0); printf("you're my hero\n");If you want to perform an uninterruptible sleep without having to use sigprocmask() to block all signals then this function provides a good solution to that problem. For example:
struct timespec rel, now, abs; clock_gettime(CLOCK_REALTIME, &now); rel = timespec_frommillis(100); abs = timespec_add(now, rel); while (clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &abs, 0));will accurately spin on
EINTR
errors. That way you're not impeding
signal delivery and you're not loosing precision on the wait timeout.
This function has first-class support on Linux, FreeBSD, and NetBSD;
on OpenBSD it's good; on XNU it's bad; and on Windows it's ugly.
- int clock
- should be
CLOCK_REALTIME
and you may consult the docs of your preferred platforms to see what other clocks might work - int flags
- can be 0 for relative and
TIMER_ABSTIME
for absolute - struct now* req
- can be a relative or absolute time, depending on
flags
- struct now* rem
- shall be updated with the remainder of unslept time when
(1) it's non-null; (2)
flags
is 0; and (3) -1 w/EINTR
is returned; if this function returns 0 thenrem
is undefined; if flags isTIMER_ABSTIME
thenrem
is ignored
- int
- 0 on success, or errno on error
clock
is known but we can't use it here
req
or null or bad memory was passed
clock
is unknown to current platform
flags
has an unrecognized value
req->tv_nsec โ [0,1000000000)
clone
Creates thread without malloc being linked.
If you use clone() you're on your own. Example:
int worker(void *arg) { return 0; } struct CosmoTib tib = {.tib_self = &tib, .tib_tid = -1}; atomic_int tid; char *stk = NewCosmoStack(); clone(worker, stk, GetStackSize() - 16, CLONE_VM | CLONE_THREAD | CLONE_FS | CLONE_FILES | CLONE_SYSVSEM | CLONE_SIGHAND | CLONE_PARENT_SETTID | CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID | CLONE_SETTLS, arg, &tid, &tib, &tib.tib_tid); while (atomic_load(&tid) == 0) sched_yield(); // thread is known while (atomic_load(&tib.tib_tid) < 0) sched_yield(); // thread is running while (atomic_load(&tib.tib_tid) > 0) sched_yield(); // thread has terminated FreeCosmoStack(stk);Threads are created in a detached manner. They currently can't be synchronized using wait() or posix signals. Threads created by this function should be synchronized using shared memory operations.
Any memory that's required by this system call wrapper is allocated to the top of your stack. This shouldn't be more than 128 bytes.
Your function is called from within the stack you specify. A return address is pushed onto your stack, that causes returning to jump to _Exit1() which terminates the thread. Even though the callback says it supports a return code, that'll only work on Linux and Windows.
This function follows the same ABI convention as the Linux userspace libraries, with a few small changes. The varargs has been removed to help prevent broken code, and the stack size and tls size parameters are introduced for compatibility with FreeBSD.
To keep this system call lightweight, only the thread creation use case is polyfilled across platforms. For example, if you want fork that works on OpenBSD for example, don't do it with clone(SIGCHLD) and please just call fork(). Even if you do that on Linux, it will effectively work around libc features like atfork(), so that means other calls like getpid() may return incorrect values.
- void* func
- is your callback function, which this wrapper requires
not be null, otherwise EINVAL is raised. It is passed two args
within the child thread: (1) the caller-supplied
arg
and (2) the new tid is always passed in the second arg for convenience - void* stk
- points to the bottom of a caller allocated stack, which must be allocated via mmap() using the MAP_STACK flag, or else you won't get optimal performance and it won't work on OpenBSD
- unsigned long stksz
- is the size of that stack in bytes, we recommend that that this be set to GetStackSize() or else memory safety tools like kprintf() can't do as good and quick of a job; this value must be 16-aligned plus it must be at least 4192 bytes in size and it's advised to have the bottom-most page, be a guard page
- int flags
- which SHOULD always have all of these flags:
CLONE_THREAD
CLONE_VM
CLONE_FS
CLONE_FILES
CLONE_SIGHAND
CLONE_SYSVSEM
Your
flags
may also optionally also additionally bitwise-OR any combination of the following additional flags:CLONE_CHILD_SETTID
must be specified if you intend to set thectid
argument, which will updated with the child tid once the child has started.CLONE_PARENT_SETTID
must be specified if you intend to set theptid
argument, which is updated at the most opportune moment. On all platforms except XNU, this happens before clone() returns. On XNU, it happens once the thread starts.CLONE_CHILD_CLEARTID
causes*ctid = 0
upon child thread termination. This is used to implement join so that the parent may know when it's safe to free the child's stack memory, and as such, is guaranteed to happen AFTER the child thread has either terminated or has finished using its stack memoryCLONE_SETTLS
is needed if you intend to specify thetls
argument, which after thread creation may be accessed using __get_tls(). Doing this means thaterrno
, gettid(), etc. correctly work. Caveat emptor if you choose not to do this.
- void* arg
- is passed as an argument to
func
in the child thread - void* ptid
- void* tls
- may be used to set the thread local storage segment;
this parameter is ignored if
CLONE_SETTLS
is not set - void* ctid
- lets the child receive its thread id without having to
call gettid() and is ignored if
CLONE_CHILD_SETTID
isn't set
- int
- 0 on success, or errno on errno
close
Closes file descriptor.
This function releases resources returned by functions such as:
- openat()
- socket()
- accept()
- epoll_create()
- landlock_create_ruleset()
EINTR
.
- int fd
- int
- 0 on success, or -1 w/ errno
fd
is negative or not open; however, an exception
is made by Cosmopolitan Libc for close(-1)
which returns zero
and does nothing, in order to assist with code that may wish to
close the same resource multiple times without dirtying errno
close_range
Closes inclusive range of file descriptors, e.g.
// close all non-stdio file descriptors if (close_range(3, -1, 0) == -1) { for (int i = 3; i < 256; ++i) { close(i); } }The following flags are available:
CLOSE_RANGE_UNSHARE
(Linux-only)CLOSE_RANGE_CLOEXEC
(Linux-only)
- unsigned int first
- unsigned int last
- unsigned int flags
- unsigned int last
- int
- 0 on success, or -1 w/ errno
closedir
Closes directory object returned by opendir().
- struct dirstream* dir
- int
- 0 on success or -1 w/ errno
closefrom
Closes extra file descriptors, e.g.
if (closefrom(3)) for (int i = 3; i < 256; ++i) close(i);
- int first
- int
- 0 on success, or -1 w/ errno
first
is negative
first
is greater than highest fd
CloseHandle
Closes an open object handle.
- long hObject
- int
closelog
Closes the file descriptor being used to write to the system logger
Use of closelog is optional
- void
CloseSymbolTable
Frees symbol table.
- struct SymbolTable** table
- int
- 0 on success or -1 on system error
commandv
Resolves full pathname of executable.
- const char* name
- char* pathbuf
- unsigned long pathbufsz
- char* pathbuf
- char*
- execve()'able path, or NULL w/ errno
commandvenv
Finds full executable path in overridable way.
This is a higher level version of the commandv() function. Programs that spawn subprocesses can use this function to determine the path at startup. Here's an example how you could use it:
if ((strace = commandvenv("STRACE", "strace"))) { strace = strdup(strace); } else { fprintf(stderr, "error: please install strace\n"); exit(1); }
- const char* var
- is environment variable which may be used to override PATH search, and it can force a NULL result if it's empty
- const char* cmd
- is name of program, which is returned asap if it's an absolute path
- const char*
- pointer to exe path string, or NULL if it couldn't be found or the environment variable was empty; noting that the caller should copy this string before saving it
CompareDnsNames
Compares DNS hostnames in reverse lexicographical asciibetical order.
- const char* A
- const char* B
- int
- <0, 0, or >0
compress
Compresses source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed data. compress() is equivalent to compress2() with a level parameter of Z_DEFAULT_COMPRESSION.
- int
- Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer.
compress2
Compresses source buffer into the destination buffer. The level parameter has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed data.
- int
- Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid.
compressBound
Returns an upper bound on the compressed size after compress() or compress2() on sourceLen bytes. It would be used before a compress() or compress2() call to allocate the destination buffer.
- unsigned long
connect
Connects socket to remote end.
ProTip: Connectionless sockets, e.g. UDP, can be connected too. The benefit is not needing to specify the remote address on each send. It also means getsockname() can be called to retrieve routing details.
- int fd
- struct sa* addr
- unsigned int addrsize
- struct sa* addr
- int
- 0 on success or -1 w/ errno
copy_file_range
Transfers data between files.
If this system call is available (Linux c. 2018 or FreeBSD c. 2021) and the file system supports it (e.g. ext4) and the source and dest files are on the same file system, then this system call shall make copies go about 2x faster.
This implementation requires Linux 5.9+ even though the system call was introduced in Linux 4.5. That's to ensure ENOSYS works reliably due to a faulty backport, that happened in RHEL7. FreeBSD detection on the other hand will work fine.
- int infd
- is source file, which should be on same file system
- long* opt_in_out_inoffset
- may be specified for pread() behavior
- int outfd
- should be a writable file, but not
O_APPEND
- long* opt_in_out_outoffset
- may be specified for pwrite() behavior
- unsigned long uptobytes
- is maximum number of bytes to transfer
- unsigned int flags
- is reserved for future use and must be zero
- long
- number of bytes transferred, or -1 w/ errno
infd
or outfd
aren't open files or append-only
fdout
refers to an immutable file on Linux
infd
or outfd
is a zip file descriptor
flags
is non-zero
setrlimit(RLIMIT_FSIZE)
is exceeded
copyfd
Copies data between file descriptors the old fashioned way.
This function is intended for simple programs without signals. If
signals are in play, then SA_RESTART
needs to be used.
- int in
- is input file descriptor
- int out
- is input file descriptor
- unsigned long n
- is number of bytes to exchange, or -1 for until eof
- long
- bytes successfully exchanged, or -1 w/ errno
_copyfile
Copies file.
This implementation goes 2x faster than the cp
command that comes
included with most systems since we use the newer copy_file_range()
system call rather than sendfile().
- const char* src
- const char* dst
- int flags
- const char* dst
- may have COPYFILE_PRESERVE_TIMESTAMPS, COPYFILE_NOCLOBBER
- int
- 0 on success, or -1 w/ errno
copysignl
Returns ๐ฅ with same sign as ๐ฆ.
- long double x
- long double y
- long double
cos
Returns cosine of ๐ฅ.
- double x
- double
cosh
Returns hyperbolic cosine of ๐ฅ.
cosh(x) = (exp(x) + 1/exp(x))/2 = 1 + 0.5*(exp(x)-1)*(exp(x)-1)/exp(x) = 1 + x*x/2 + o(x^4)
- double x
- double
coshf
Returns hyperbolic cosine of ๐ฅ.
cosh(x) = (exp(x) + 1/exp(x))/2 = 1 + 0.5*(exp(x)-1)*(exp(x)-1)/exp(x) = 1 + x*x/2 + o(x^4)
- float x
- float
cosmo
Cosmopolitan runtime.
- edi
- is argc
- rsi
- is argv
- rdx
- is environ
- rcx
- is auxv
cosmo_once
Ensures initialization function is called exactly once.
This is the same as pthread_once
except that it always uses a tiny
spinlock implementation and won't make any system calls. It's needed
since this function is an upstream dependency of both pthread_once()
and nsync_once(). Most code should favor calling those functions.
- _Atomic unsigned int* once
- void(*)() init
- int
- 0 on success, or errno on error
_countbits
Returns population count of array.
- void* a
- is byte sequence
- unsigned long n
- unsigned long
- number of bits set to one
CountTokens
Returns current number of tokens in bucket.
- _Atomic char* b
- is array of token buckets
- unsigned int x
- is ipv4 address
- int c
- is cidr
- int
CPU_AND
- struct cpu_set_t* d
- struct cpu_set_t* x
- struct cpu_set_t* y
- struct cpu_set_t* x
- void
CPU_OR
- struct cpu_set_t* d
- struct cpu_set_t* x
- struct cpu_set_t* y
- struct cpu_set_t* x
- void
CPU_XOR
- struct cpu_set_t* d
- struct cpu_set_t* x
- struct cpu_set_t* y
- struct cpu_set_t* x
- void
crc32
Update a running CRC-32 with the bytes buf[0..len-1] and return the updated CRC-32. If buf is Z_NULL, this function returns the required initial value for the crc. Pre- and post-conditioning (one's complement) is performed within this function so it shouldn't be done by the application.
Usage example:
uLong crc = crc32(0L, Z_NULL, 0); while (read_buffer(buffer, length) != EOF) { crc = crc32(crc, buffer, length); } if (crc != original_crc) error();
- unsigned long
crc32_combine
Combine two CRC-32 check values into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, CRC-32 check values were calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and len2.
- unsigned long
crc32c
Computes 32-bit Castagnoli Cyclic Redundancy Check.
x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1 0b00011110110111000110111101000001 _bitreverse32(0x1edc6f41)
- unsigned int init
- is the initial hash value
- void* data
- points to the data
- unsigned long size
- is the byte size of data
- unsigned int
- eax is the new hash value
creat
Creates file.
This is equivalent to saying:
int fd = openat(AT_FDCWD, file, O_CREAT | O_WRONLY | O_TRUNC, mode);
- const char* file
- specifies filesystem path to create
- unsigned int mode
- is octal bits, e.g. 0644 usually
- int
- file descriptor, or -1 w/ errno
CreateDirectory
Creates directory on the New Technology.
- const unsigned short* lpPathName
- struct NtSecurityAttributes* lpSecurityAttributes
- int
- handle, or -1 on failure
CreateFile
Opens file on the New Technology.
- const unsigned short* lpFileName
- unsigned int dwDesiredAccess
- unsigned int dwShareMode
- struct NtSecurityAttributes* opt_lpSecurityAttributes
- int dwCreationDisposition
- unsigned int dwFlagsAndAttributes
- long opt_hTemplateFile
- unsigned int dwDesiredAccess
- long
- handle, or -1 on failure
CreateFileMapping
Creates file mapping object on the New Technology.
- long opt_hFile
- may be -1 for MAP_ANONYMOUS behavior
- struct NtSecurityAttributes* opt_lpFileMappingAttributes
- unsigned int flProtect
- unsigned int dwMaximumSizeHigh
- unsigned int dwMaximumSizeLow
- const unsigned short* opt_lpName
- unsigned int flProtect
- long
- handle, or 0 on failure
CreateFileMappingNuma
Creates file mapping object on the New Technology.
- long opt_hFile
- may be -1 for MAP_ANONYMOUS behavior
- struct NtSecurityAttributes* opt_lpFileMappingAttributes
- unsigned int flProtect
- unsigned int dwMaximumSizeHigh
- unsigned int dwMaximumSizeLow
- const unsigned short* opt_lpName
- unsigned int nndDesiredNumaNode
- unsigned int flProtect
- long
- handle, or 0 on failure
CreateNamedPipe
Creates pipe.
- const unsigned short* lpName
- unsigned int dwOpenMode
- unsigned int dwPipeMode
- unsigned int nMaxInstances
- unsigned int nOutBufferSize
- unsigned int nInBufferSize
- unsigned int nDefaultTimeOutMs
- struct NtSecurityAttributes* opt_lpSecurityAttributes
- unsigned int dwOpenMode
- long
- handle to server end
CreatePipe
Creates anonymous pipe.
- long* out_hReadPipe
- long* out_hWritePipe
- struct NtSecurityAttributes* opt_lpPipeAttributes
- unsigned int nSize
- long* out_hWritePipe
- int
CreateProcess
Creates process on the New Technology.
- const unsigned short* opt_lpApplicationName
- unsigned short* lpCommandLine
- struct NtSecurityAttributes* opt_lpProcessAttributes
- struct NtSecurityAttributes* opt_lpThreadAttributes
- int bInheritHandles
- unsigned int dwCreationFlags
- void* opt_lpEnvironment
- const unsigned short* opt_lpCurrentDirectory
- struct NtStartupInfo* lpStartupInfo
- struct NtProcessInformation* opt_out_lpProcessInformation
- unsigned short* lpCommandLine
- int
CreateSymbolicLink
Creates symbolic link on the New Technology.
- const unsigned short* lpSymlinkFileName
- const unsigned short* lpTargetPathName
- unsigned int dwFlags
- const unsigned short* lpTargetPathName
- int
CreateThread
Opens file on the New Technology.
- struct NtSecurityAttributes* lpThreadAttributes
- unsigned long dwStackSize
- may be 0 for default per executable
- unsigned int(*)() lpStartAddress
- void* lpParameter
- unsigned int dwCreationFlags
- unsigned int* opt_lpThreadId
- void* lpParameter
- long
- thread handle, or 0 on failure
critbit0_allprefixed
Invokes callback for all items with prefix.
- struct critbit0* t
- const char* prefix
- long(*)() callback
- void* arg
- const char* prefix
- long
- 0 unless iteration was halted by CALLBACK returning nonzero, in which case that value is returned
critbit0_clear
Removes all items from ๐ก.
- struct critbit0* t
- tree
- void
critbit0_contains
Returns non-zero iff ๐ข โ ๐ก.
- struct critbit0* t
- tree
- const char* u
- NUL-terminated string
- _Bool
critbit0_delete
Removes ๐ข from ๐ก.
- struct critbit0* t
- tree
- const char* u
- NUL-terminated string
- _Bool
- true if ๐ก was mutated
critbit0_emplace
Inserts ๐ข into ๐ก without copying.
- struct critbit0* t
- is critical bit tree
- char* u
- is nul-terminated string which must be 8+ byte aligned and becomes owned by the tree afterwards
- unsigned long ulen
- int
- true if ๐ก was mutated, or -1 w/ errno
critbit0_get
Returns first item in ๐ก with prefix ๐ข.
- struct critbit0* t
- tree
- const char* u
- NUL-terminated string
- char*
- item or NULL if not found
critbit0_insert
Inserts ๐ข into ๐ก.
- struct critbit0* t
- tree
- const char* u
- NUL-terminated string
- int
- true if ๐ก was mutated, or -1 w/ errno
crypt
Encrypts password the old fashioned way.
The method of encryption depends on the first three chars of salt:
$1$
is MD5$2$
is Blowfish$5$
is SHA-256$6$
is SHA-512- Otherwise DES
- const char* key
- const char* salt
- char*
- static memory with encrypted password
crypt_r
Encrypts password the old fashioned way.
The method of encryption depends on the first three chars of salt:
$1$
is MD5$2$
is Blowfish$5$
is SHA-256$6$
is SHA-512- Otherwise DES
- const char* key
- const char* salt
- struct crypt_data* data
- const char* salt
- char*
- static memory with encrypted password
ctermid
Generates path of controlling terminal.
This function always returns /dev/tty since that's supported by all supported platforms, and polyfilled on Windows.
- char* s
- may optionally specify an outut buffer L_ctermid in size
- char*
- pointer to
s
(or image memory ifs
was null) which contains path of controlling terminal, or empty string if if this program is a win32 app running in gui mode
__cxa_atexit
Adds global destructor.
Destructors are called in reverse order. They won't be called if the program aborts or _exit() is called. Invocations of this function are usually generated by the C++ compiler. Behavior is limitless if some other module has linked calloc().
- void* fp
- is void(*)(T)
- void* arg
- is passed to callback
- void* pred
- can be non-null for things like dso modules
- int
- 0 on success or nonzero w/ errno
__cxa_demangle
- const char* mangled_name
- char* buf
- unsigned long* n
- int* status
- char* buf
- char*
- A pointer to the start of the NUL-terminated demangled
name, or a null pointer if the demangling fails. The caller is
responsible for deallocating this memory using @c free.
The demangling is performed using the C++ ABI mangling rules, with GNU extensions. For example, this function is used in __gnu_cxx::__verbose_terminate_handler.
See https://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html for other examples of use.
__cxa_demangle_gnu3
- const char* org
- char*
- New allocated demangled string or NULL if failed.
GNU GCC v3 use IA-64 standard ABI.
- Testing and more test case. 2. Code cleaning.
__cxa_finalize
Triggers global destructors.
They're called in LIFO order. If a destructor adds more destructors, then those destructors will be called immediately following, before iteration continues.
- void* pred
- can be null to match all
- void
__cxa_printexits
Prints global destructors.
- struct FILE* f
- void* pred
- can be null to match all
- void
daemon
Runs process in background.
On Unix this calls fork() and setsid(). On Windows this is implemented using CreateProcess(kNtDetachedProcess).
- int nochdir
- int noclose
- int
- 0 on success, or -1 w/ errno
DecodeBase64
Decodes base64 ascii representation to binary.
This supports the following alphabets:
- ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
- ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_
- const char* data
- is input value
- unsigned long size
- if -1 implies strlen
- unsigned long* out_size
- if non-NULL receives output length
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
DecodeLatin1
Decodes ISO-8859-1 to UTF-8.
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- unsigned long* z
- if non-NULL receives output length
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
_defer
Calls fn(arg) when function returns.
This garbage collector overwrites the return address on the stack so that the RET instruction calls a trampoline which calls free(). It's loosely analogous to Go's defer keyword rather than a true cycle gc.
- void* fn
- void* arg
- void*
deflate
deflate compresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush.
The detailed semantics are as follows. deflate performs one or both of the following actions:
- Compress more input starting at next_in and update next_in and
- Generate more output starting at next_out and update next_out and
Before the call of deflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating avail_in or avail_out accordingly; avail_out should never be zero before the call. The application can consume the compressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. See deflatePending(), which can be used if desired to determine whether or not there is more ouput in that case.
Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to decide how much data to accumulate before producing output, in order to maximize compression.
If the parameter flush is set to Z_SYNC_FLUSH, all pending output is flushed to the output buffer and the output is aligned on a byte boundary, so that the decompressor can get all input data available so far. (In particular avail_in is zero after the call if enough output space has been provided before the call.) Flushing may degrade compression for some compression algorithms and so it should be used only when necessary. This completes the current deflate block and follows it with an empty stored block that is three bits plus filler bits to the next byte, followed by four bytes (00 00 ff ff).
If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the output buffer, but the output is not aligned to a byte boundary. All of the input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. This completes the current deflate block and follows it with an empty fixed codes block that is 10 bits long. This assures that enough bytes are output in order for the decompressor to finish the block before the empty fixed codes block.
If flush is set to Z_BLOCK, a deflate block is completed and emitted, as for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to seven bits of the current block are held to be written as the next byte after the next deflate block is completed. In this case, the decompressor may not be provided enough bits at this point in order to complete decompression of the data provided so far to the compressor. It may need to wait for the next block to be emitted. This is for advanced applications that need to control the emission of deflate blocks.
If flush is set to Z_FULL_FLUSH, all output is flushed as with Z_SYNC_FLUSH, and the compression state is reset so that decompression can restart from this point if previous compressed data has been damaged or if random access is desired. Using Z_FULL_FLUSH too often can seriously degrade compression.
If deflate returns with avail_out == 0, this function must be called again with the same value of the flush parameter and more output space (updated avail_out), until the flush is complete (deflate returns with non-zero avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that avail_out is greater than six to avoid repeated flush markers due to avail_out == 0 on return.
If the parameter flush is set to Z_FINISH, pending input is processed, pending output is flushed and deflate returns with Z_STREAM_END if there was enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this function must be called again with Z_FINISH and more output space (updated avail_out) but no more input data, until it returns with Z_STREAM_END or an error. After deflate has returned Z_STREAM_END, the only possible operations on the stream are deflateReset or deflateEnd.
Z_FINISH can be used in the first deflate call after deflateInit if all the compression is to be done in a single step. In order to complete in one call, avail_out must be at least the value returned by deflateBound (see below). Then deflate is guaranteed to return Z_STREAM_END. If not enough output space is provided, deflate will not return Z_STREAM_END, and it must be called again as described above.
deflate() sets strm->adler to the Adler-32 checksum of all input read so far (that is, total_in bytes). If a gzip stream is being generated, then strm->adler will be the CRC-32 checksum of the input read so far. (See deflateInit2 below.)
deflate() may update strm->data_type if it can make a good guess about the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is considered binary. This field is only for information purposes and does not affect the compression algorithm in any manner.
- int
- Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if all input has been consumed and all output has been produced (only when flush is set to Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example if next_in or next_out was Z_NULL or the state was inadvertently written over by the application), or Z_BUF_ERROR if no progress is possible (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and deflate() can be called again with more input and more output space to continue compressing.
deflateBound
deflateBound() returns an upper bound on the compressed size after deflation of sourceLen bytes. It must be called after deflateInit() or deflateInit2(), and after deflateSetHeader(), if used. This would be used to allocate an output buffer for deflation in a single pass, and so would be called before deflate(). If that first deflate() call is provided the sourceLen input bytes, an output buffer allocated to the size returned by deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed to return Z_STREAM_END. Note that it is possible for the compressed size to be larger than the value returned by deflateBound() if flush options other than Z_FINISH or Z_NO_FLUSH are used.
- unsigned long
deflateCopy
Sets destination stream as a complete copy of the source stream.
This function can be useful when several compression strategies will be tried, for example when there are several ways of pre-processing the input data with a filter. The streams that will be discarded should then be freed by calling deflateEnd. Note that deflateCopy duplicates the internal compression state which can be quite large, so this strategy is slow and can consume lots of memory.
- int
- Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and destination.
deflateEnd
All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output.
- int
- Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent, Z_DATA_ERROR if the stream was freed prematurely (some input or output was discarded). In the error case, msg may be set but then points to a static string (which must not be deallocated).
deflateGetDictionary
Returns the sliding dictionary being maintained by deflate. dictLength is set to the number of bytes in the dictionary, and that many bytes are copied to dictionary. dictionary must have enough space, where 32768 bytes is always enough. If deflateGetDictionary() is called with dictionary equal to Z_NULL, then only the dictionary length is returned, and nothing is copied. Similary, if dictLength is Z_NULL, then it is not set.
deflateGetDictionary() may return a length less than the window size, even when more than the window size in input has been provided. It may return up to 258 bytes less in that case, due to how zlib's implementation of deflate manages the sliding window and lookahead for matches, where matches can be up to 258 bytes long. If the application needs the last window-size bytes of input, then that would need to be saved by the application outside of zlib.
- int
- Z_OK on success, or Z_STREAM_ERROR if the stream state is inconsistent.
deflateInit
Initializes the internal stream state for compression. The fields zalloc, zfree and opaque must be initialized before by the caller. If zalloc and zfree are set to Z_NULL, deflateInit updates them to use default allocation functions.
The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6).
- int
- Z_OK if success, Z_MEM_ERROR if there was not enough memory, or Z_STREAM_ERROR if level is not a valid compression level. msg is set to null if there is no error message. deflateInit does not perform any compression: this will be done by deflate().
deflateInit2
This is another version of deflateInit with more compression options. The fields next_in, zalloc, zfree and opaque must be initialized before by the caller.
The method parameter is the compression method. It must be Z_DEFLATED in this version of the library.
The windowBits parameter is the base two logarithm of the window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. Larger values of this parameter result in better compression at the expense of memory usage. The default value is 15 if deflateInit is used instead.
For the current implementation of deflate(), a windowBits value of 8 (a window size of 256 bytes) is not supported. As a result, a request for 8 will result in 9 (a 512-byte window). In that case, providing 8 to inflateInit2() will result in an error when the zlib header with 9 is checked against the initialization of inflate(). The remedy is to not use 8 with deflateInit2() with this initialization, or at least in that case use 9 with inflateInit2().
windowBits can also be -8..-15 for raw deflate. In this case, -windowBits determines the window size. deflate() will then generate raw deflate data with no zlib header or trailer, and will not compute a check value.
windowBits can also be greater than 15 for optional gzip encoding. Add 16 to windowBits to write a simple gzip header and trailer around the compressed data instead of a zlib wrapper. The gzip header will have no file name, no extra data, no comment, no modification time (set to zero), no header crc, and the operating system will be set to the appropriate value, if the operating system was determined at compile time. If a gzip stream is being written, strm->adler is a CRC-32 instead of an Adler-32.
For raw deflate or gzip encoding, a request for a 256-byte window is rejected as invalid, since only the zlib header provides a means of transmitting the window size to the decompressor.
The memLevel parameter specifies how much memory should be allocated for the internal compression state. memLevel=1 uses minimum memory but is slow and reduces compression ratio; memLevel=9 uses maximum memory for optimal speed. The default value is 8. See zconf.h for total memory usage as a function of windowBits and memLevel.
The strategy parameter is used to tune the compression algorithm. Use the value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no string match), or Z_RLE to limit match distances to one (run-length encoding). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect of Z_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications.
- int
- Z_OK if success, Z_MEM_ERROR if there was not enough memory, or Z_STREAM_ERROR if any parameter is invalid (such as an invalid method). msg is set to null if there is no error message. deflateInit2 does not perform any compression: this will be done by deflate().
deflateParams
Dynamically update the compression level and compression strategy. The interpretation of level and strategy is as in deflateInit2(). This can be used to switch between compression and straight copy of the input data, or to switch to a different kind of input data requiring a different strategy. If the compression approach (which is a function of the level) or the strategy is changed, and if any input has been consumed in a previous deflate() call, then the input available so far is compressed with the old level and strategy using deflate(strm, Z_BLOCK). There are three approaches for the compression levels 0, 1..3, and 4..9 respectively. The new level and strategy will take effect at the next call of deflate().
If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does not have enough output space to complete, then the parameter change will not take effect. In this case, deflateParams() can be called again with the same parameters and more output space to try again.
In order to assure a change in the parameters on the first try, the deflate stream should be flushed using deflate() with Z_BLOCK or other flush request until strm.avail_out is not zero, before calling deflateParams(). Then no more input data should be provided before the deflateParams() call. If this is done, the old level and strategy will be applied to the data compressed before deflateParams(), and the new level and strategy will be applied to the the data compressed after deflateParams().
deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if there was not enough output space to complete the compression of the available input data before a change in the strategy or approach. Note that in the case of a Z_BUF_ERROR, the parameters are not changed. A return value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be retried with more output space.
- int
deflatePending
deflatePending() returns the number of bytes and bits of output that have been generated, but not yet provided in the available output. The bytes not provided would be due to the available output space having being consumed. The number of bits of output not provided are between 0 and 7, where they await more bits to join them in order to fill out a full byte. If pending or bits are Z_NULL, then those values are not set.
- int
- Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent.
deflatePrime
deflatePrime() inserts bits in the deflate output stream. The intent is that this function is used to start off the deflate output with the bits leftover from a previous deflate stream when appending to it. As such, this function can only be used for raw deflate, and must be used before the first deflate() call after a deflateInit2() or deflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the output.
- int
- Z_OK if success, Z_BUF_ERROR if there was not enough room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the source stream state was inconsistent.
deflateReset
This function is equivalent to deflateEnd followed by deflateInit, but does not free and reallocate the internal compression state. The stream will leave the compression level and any other attributes that may have been set unchanged.
deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL).
- int
deflateSetDictionary
Initializes the compression dictionary from the given byte sequence without producing any compressed output. When using the zlib format, this function must be called immediately after deflateInit, deflateInit2 or deflateReset, and before any call of deflate. When doing raw deflate, this function must be called either before any call of deflate, or immediately after the completion of a deflate block, i.e. after all input has been consumed and all output has been delivered when using any of the flush options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The compressor and decompressor must use exactly the same dictionary (see inflateSetDictionary).
The dictionary should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary.
Depending on the size of the compression data structures selected by deflateInit or deflateInit2, a part of the dictionary may in effect be discarded, for example if the dictionary is larger than the window size provided in deflateInit or deflateInit2. Thus the strings most likely to be useful should be put at the end of the dictionary, not at the front. In addition, the current implementation of deflate will use at most the window size minus 262 bytes of the provided dictionary.
Upon return of this function, strm->adler is set to the Adler-32 value of the dictionary; the decompressor may later use this value to determine which dictionary has been used by the compressor. (The Adler-32 value applies to the whole dictionary even if only a subset of the dictionary is actually used by the compressor.) If a raw deflate was requested, then the Adler-32 value is not computed and strm->adler is not set.
- int
- Z_OK if success, or Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent (for example if deflate has already been called for this stream or if not at a block boundary for raw deflate). deflateSetDictionary does not perform any compression: this will be done by deflate().
deflateSetHeader
Provides gzip header information for when a gzip stream is requested by deflateInit2(). deflateSetHeader() may be called after deflateInit2() or deflateReset() and before the first call of deflate(). The text, time, os, extra field, name, and comment information in the provided gz_header structure are written to the gzip header (xflag is ignored -- the extra flags are set according to the compression level). The caller must assure that, if not Z_NULL, name and comment are terminated with a zero byte, and that if extra is not Z_NULL, that extra_len bytes are available there. If hcrc is true, a gzip header crc is included. Note that the current versions of the command-line version of gzip (up through version 1.3.x) do not support header crc's, and will report that it is a "multi-part gzip file" and give up.
If deflateSetHeader is not used, the default gzip header has text false, the time set to zero, and os set to 255, with no extra, name, or comment fields. The gzip header is returned to the default state by deflateReset().
deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent.
- int
deflateTune
Fine tune deflate's internal compression parameters. This should only be used by someone who understands the algorithm used by zlib's deflate for searching for the best matching string, and even then only by the most fanatic optimizer trying to squeeze out the last compressed bit for their specific input data. Read the deflate.c source code for the meaning of the max_lazy, good_length, nice_length, and max_chain parameters.
deflateTune() can be called after deflateInit() or deflateInit2(), and returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
- int
DeleteFile
Deletes existing file.
- const unsigned short* lpPathName
- int
DeserializeDnsHeader
Serializes DNS message h to wire.
- struct DnsHeader* h
- const unsigned char* p
- void
- number of bytes read (always 12) or -1 w/ errno
DeviceIoControl
Does device file stuff on the New Technology.
- long hDevice
- unsigned int dwIoControlCode
- void* lpInBuffer
- unsigned int nInBufferSize
- void* lpOutBuffer
- unsigned int nOutBufferSize
- unsigned int* lpBytesReturned
- struct inout_lpOverlapped* lpOverlapped
- unsigned int dwIoControlCode
- int
- handle, or -1 on failure
__die
Aborts process after printing a backtrace.
If a debugger is present then this will trigger a breakpoint.
dirfd
Returns file descriptor associated with DIR object.
- struct dirstream* dir
- int
dirname
Returns directory portion of path, e.g.
path โ dirname() โ basename() โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ . โ . โ . .. โ . โ .. / โ / โ / usr โ . โ usr /usr/ โ / โ usr /usr/lib โ /usr โ lib
- char* path
- is UTF-8 and may be mutated, but not expanded in length
- char*
- pointer to path, or inside path, or to a special r/o string
div
Divides integers yielding numerator and denominator.
- int num
- int den
- struct retval
__divmodti4
Divides 128-bit signed integers w/ remainder.
- __int128 a
- is numerator
- __int128 b
- is denominator
- unsigned __int128* opt_out_rem
- receives euclidean division remainder if not null
- __int128
- quotient or result of division
__divti3
Divides 128-bit signed integers.
- __int128 a
- is numerator
- __int128 b
- is denominator
- __int128
- quotient or result of division
djbsort
D.J. Bernstein's outrageously fast integer sorting algorithm.
- int* a
- unsigned long n
- void
djbsort_avx2
D.J. Bernstein's outrageously fast integer sorting algorithm.
- rdi
- is int32 array
- rsi
- is number of elements in rdi
dlindependent_calloc
- unsigned long n_elements
- unsigned long elem_size
- void** chunks
- unsigned long elem_size
- void**
dlindependent_comalloc
- unsigned long n_elements
- unsigned long* sizes
- void** chunks
- unsigned long* sizes
- void**
__dll_make_first
Inserts items into list, at the beginning.
The resulting list will start with elem
, followed by other items in
elem
, followed by the items previously in *list
.
- struct Dll** list
- is a doubly-linked list, where
!*list
means empty - struct Dll* elem
- must not be a member of
list
, or null for no-op
- void
__dll_make_last
Inserts items into list, at the end.
The resulting *list
will end with elem
, preceded by the other
items in elem
, preceded by the items previously in *list
.
- struct Dll** list
- is a doubly-linked list, where
!*list
means empty - struct Dll* elem
- must not be a member of
list
, or null for no-op
- void
__dll_remove
Removes item from doubly-linked list.
- struct Dll** list
- is a doubly-linked list, where
!*list
means empty - struct Dll* elem
- void
__dll_splice_after
Makes succ
and its successors come after elem
.
It's required that elem
and succ
aren't part of the same list.
- struct Dll* elem
- struct Dll* succ
- void
dlmalloc_requires_more_vespene_gas
Acquires more system memory for dlmalloc.
- unsigned long size
- void*
- memory map address on success, or null w/ errno
__dos2errno
Translates Windows error using superset of consts.sh.
This function is called by __winerr(). It can only be used on Windows, because it returns an errno. Normally, errnos will be programmed to be the same as DOS errnos, per consts.sh. But since there's so many more errors in DOS, this function provides an added optional benefit mapping additional constants onto the errnos in consts.sh.
- unsigned int error
- int
DosDateTimeToUnix
Converts MS-DOS timestamp to UNIX.
- unsigned int date
- unsigned int time
- long
dprintf
Formats string directly to file descriptor.
- int fd
- const char* fmt
- ...
- const char* fmt
- int
dsleep
Sleeps w/ higher precision.
- long double secs
- long double
dtime
Returns seconds since epoch w/ high-precision.
- int clockid
- can be CLOCK_{REALTIME,MONOTONIC}, etc.
- long double
DumpHexc
Turns data into "\x00..." string literal.
- const char* p
- unsigned long n
- unsigned long* z
- unsigned long n
- char*
dup
Duplicates file descriptor.
The O_CLOEXEC
flag shall be cleared from the resulting file
descriptor; see dup3() to preserve it.
One use case for duplicating file descriptors is to be able to reassign an open()'d file or pipe() to the stdio of an executed subprocess. On Windows, in order for this to work, the subprocess needs to be a Cosmopolitan program that has socket() linked.
Only small programs should duplicate sockets. That's because this implementation uses DuplicateHandle() on Windows, which Microsoft says might cause its resources to leak internally. Thus it likely isn't a good idea to design a server that does it a lot and lives a long time, without contributing a patch to this implementation.
- int fd
- remains open afterwards
- int
- some arbitrary new number for fd
fd
is a zip file descriptor
fd
is negative or not open
dup2
Duplicates file descriptor, granting it specific number.
Unlike dup3(), the dup2() function permits oldfd and newfd to be the same, in which case the only thing this function does is test if oldfd is open.
The O_CLOEXEC
flag shall be cleared from the resulting file
descriptor; see dup3() to preserve it.
One use case for duplicating file descriptors is to be able to reassign an open()'d file or pipe() to the stdio of an executed subprocess. On Windows, in order for this to work, the subprocess needs to be a Cosmopolitan program that has socket() linked.
Only small programs should duplicate sockets. That's because this implementation uses DuplicateHandle() on Windows, which Microsoft says might cause its resources to leak internally. Thus it likely isn't a good idea to design a server that does it a lot and lives a long time, without contributing a patch to this implementation.
- int oldfd
- isn't closed afterwards
- int newfd
- if already assigned, is silently closed beforehand; unless it's equal to oldfd, in which case dup2() is a no-op
- int
- new file descriptor, or -1 w/ errno
RLIMIT_NOFILE
has been reached
oldfd
is on zip file system
newfd
negative or too big
oldfd
isn't open
dup3
Duplicates file descriptor/handle.
The O_CLOEXEC
flag shall be cleared from the resulting file
descriptor; see dup3() to preserve it.
One use case for duplicating file descriptors is to be able to reassign an open()'d file or pipe() to the stdio of an executed subprocess. On Windows, in order for this to work, the subprocess needs to be a Cosmopolitan program that has socket() linked.
Only small programs should duplicate sockets. That's because this implementation uses DuplicateHandle() on Windows, which Microsoft says might cause its resources to leak internally. Thus it likely isn't a good idea to design a server that does it a lot and lives a long time, without contributing a patch to this implementation.
- int oldfd
- isn't closed afterwards
- int newfd
- if already assigned, is silently closed beforehand; unless it's equal to oldfd, in which case dup2() is a no-op
- int flags
- may have O_CLOEXEC which is needed to preserve the close-on-execve() state after file descriptor duplication
- int
- newfd on success, or -1 w/ errno
oldfd
is a zip file descriptor
flags
has unsupported bits
newfd
negative or too big
newfd
equals oldfd
oldfd
isn't open
eaccess
Performs access() check using effective user/group id.
- const char* filename
- int amode
- int
EAGAIN
Resource temporarily unavailable (e.g. SO_RCVTIMEO expired, too many processes, too much memory locked, read or write with O_NONBLOCK needs polling, etc.).
- const int
EFAULT
Pointer passed to system call that would otherwise segfault.
- const int
EfiMain
EFI Application Entrypoint.
This entrypoint is mutually exclusive from WinMain since Windows apps and EFI apps use the same PE binary format. So if you want to trade away Windows so that you can use UEFI instead of the normal BIOS boot process, do this:
__static_yoink("EfiMain"); int main() { ... }You can use QEMU to test this, but please note that UEFI goes thousands of times slower than the normal BIOS boot
qemu-system-x86_64 \ -bios OVMF.fd \ -nographic \ -net none \ -drive format=raw,file=fat:rw:o/tool/viz FS0: deathstar.com
- unsigned long ImageHandle
- struct EFI_SYSTEM_TABLE* SystemTable
- unsigned long
_EfiPostboot
Start the Cosmopolitan runtime after exiting UEFI Boot Services.
- rdi
- is mm
- rsi
- is new pml4t
- rdx
- is argc
- rcx
- is argv
__enable_tls
Enables thread local storage for main process.
Here's the TLS memory layout on x86_64:
__get_tls() โ %fs Linux/BSDs _Thread_local โ โโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโผโโโโ โpadโ .tdata โ .tbss โtibโ โโโโโดโโโโโโโโโโโดโโโโโโโโโโโผโโโโ โ Windows/Mac %gsHere's the TLS memory layout on aarch64:
x28 %tpidr_el0 โ โ _Thread_local โโโโโผโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโ โtibโdtvโ .tdata โ .tbss โ โโโโโดโโโโดโโโโโโโโโโโดโโโโโโโโโโโ โ __get_tls()This function is always called by the core runtime to guarantee TLS is always available to your program. You must build your code using -mno-tls-direct-seg-refs if you want to use _Thread_local.
You can use __get_tls() to get the linear address of your tib. When accessing TLS via privileged code you must use __get_tls_privileged because we need code morphing to support The New Technology and XNU
On XNU and The New Technology, this function imposes 1ms of latency during startup for larger binaries like Python.
If you don't want TLS and you're sure you're not using it, then you can disable it as follows:
int main() { __tls_enabled_set(false); // do stuff }This is useful if you want to wrestle back control of %fs using the arch_prctl() function. However, such programs might not be portable and your
errno
variable also won't be thread safe anymore.
- void
EncodeBase64
Encodes binary to base64 ascii representation.
- const char* data
- is input value
- unsigned long size
- if -1 implies strlen
- unsigned long* out_size
- if non-NULL receives output length
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
EncodeHttpHeaderValue
Encodes HTTP header value.
This operation involves the following:
- Trim whitespace.
- Turn UTF-8 into ISO-8859-1.
- Make sure no C0 or C1 control codes are present (except tab).
- const char* data
- is input value
- unsigned long size
- if -1 implies strlen
- unsigned long* out_size
- if non-NULL receives output length on success
- char*
- allocated NUL-terminated string, or NULL w/ errno
EncodeLatin1
Encodes UTF-8 to ISO-8859-1.
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- unsigned long* z
- if non-NULL receives output length
- int f
- can kControlC0, kControlC1, kControlWs to forbid
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
EncodeUrl
Encodes URL.
- struct Url* h
- unsigned long* z
- if not null receives string length of result
- char*
- nul-terminated url string needing free
_endswith
Returns true if s has suffix.
- const char* s
- is a NUL-terminated string
- const char* suffix
- is also NUL-terminated
- _Bool
_endswith16
Returns true if s has suffix.
- const unsigned short* s
- is a NUL-terminated string
- const unsigned short* suffix
- is also NUL-terminated
- _Bool
ENOSYS
System call unavailable.
- const int
__ensurefds
Grows file descriptor array memory if needed.
- int fd
- int
__ensurefds_unlocked
Grows file descriptor array memory if needed.
- int fd
- int
epoll_create
Creates new epoll instance.
- int size
- is ignored but must be greater than zero
- int
- epoll file descriptor, or -1 on failure
epoll_create1
Creates new epoll instance.
- int flags
- must be zero or can have O_CLOEXEC
- int
- epoll file descriptor, or -1 on failure
epoll_ctl
Controls which socket events are monitored.
It is recommended to always explicitly remove a socket from its epoll set using EPOLL_CTL_DEL before closing it. As on Linux, your closed sockets are automatically removed from the epoll set, but wepoll may not be able to detect that a socket was closed until the next call to epoll_wait().
- int epfd
- is file descriptor created by epoll_create()
- int op
- can be EPOLL_CTL_{ADD,MOD,DEL}
- int fd
- is file descriptor to monitor
- struct epoll_event* ev
- is ignored if op is EPOLL_CTL_DEL
- int
- 0 on success, or -1 w/ errno
epoll_pwait
Receives socket events.
- int epfd
- struct epoll_event* events
- will receive information about what happened
- int maxevents
- is array length of events
- int timeoutms
- is milliseconds, 0 to not block, or -1 for forever
- struct uc_sigmask* sigmask
- is an optional sigprocmask() to use during call
- int
- number of events stored, 0 on timeout, or -1 w/ errno
epoll_wait
Receives socket events.
- int epfd
- struct epoll_event* events
- will receive information about what happened
- int maxevents
- is array length of events
- int timeoutms
- is milliseconds, 0 to not block, or -1 for forever
- int
- number of events stored, 0 on timeout, or -1 w/ errno
erfc
Returns complementary error function of ๐ฅ.
- double x
- double
__errno
Global variable for last error.
The system call wrappers update this with WIN32 error codes. Unlike traditional libraries, Cosmopolitan error codes are defined as variables. By convention, system calls and other functions do not update this variable when nothing's broken.
- int
_escapedos
Escapes command so DOS can run it.
- unsigned short* buffer
- unsigned int buflen
- const unsigned short* unquoted
- unsigned int len
- unsigned int buflen
- _Bool
EscapeFragment
Escapes URL fragment.
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- unsigned long* z
- if non-NULL receives output length
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
EscapeHost
Escapes URL host or registry name.
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- unsigned long* z
- if non-NULL receives output length
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
EscapeHtml
Escapes HTML entities.
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- unsigned long* z
- if non-NULL receives output length
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
EscapeIp
Escapes URL IP-literal.
This is the same as EscapeHost except colon is permitted.
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- unsigned long* z
- if non-NULL receives output length
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
EscapeJsStringLiteral
Escapes UTF-8 data for JavaScript or JSON string literal.
HTML entities and forward slash are escaped too for added safety.
Single quote ('
) is \uxxxx-encoded for consistency, as it's
allowed in JavaScript, but not in JSON strings.
We assume the UTF-8 is well-formed and can be represented as UTF-16. Things that can't be decoded will fall back to binary. Things that can't be encoded will use invalid codepoint markers. This function is agnostic to numbers that have been used with malicious intent in the past under buggy software. Noncanonical encodings such as overlong NUL are canonicalized as NUL. Therefore it isn't necessary to say EscapeJsStringLiteral(Underlong(๐ฅ)) since EscapeJsStringLiteral(๐ฅ) will do the same thing.
- char** r
- is realloc'able output buffer reused between calls
- unsigned long* y
- is used to track byte length of
*r
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- unsigned long* z
- char*
- *r on success, or null w/ errno
EscapeParam
Escapes query/form name/parameter.
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- unsigned long* z
- if non-NULL receives output length
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
EscapePass
Escapes URL password.
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- unsigned long* z
- if non-NULL receives output length
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
EscapePath
Escapes URL path.
This is the same as EscapePathSegment() except slash is allowed.
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- unsigned long* z
- if non-NULL receives output length
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
EscapeSegment
Escapes URL path segment.
Please note this will URI encode the slash character. That's because segments are the labels between the slashes in a path.
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- unsigned long* z
- if non-NULL receives output length
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
EscapeUrl
Escapes URL component using generic table.
This function is agnostic to the underlying charset. Always using UTF-8 is a good idea.
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- unsigned long* z
- if non-NULL receives output length
- const char* T
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
EscapeUrlView
Escapes URL component using generic table w/ stpcpy() api.
- char* p
- struct fragment* v
- const char* T
- struct fragment* v
- char*
EscapeUser
Escapes URL user name.
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- unsigned long* z
- if non-NULL receives output length
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
euidaccess
Performs access() check using effective user/group id.
- const char* filename
- int amode
- int
execl
Executes program, with current environment.
The current process is replaced with the executed one.
- const char* exe
- const char* arg
- ...
- const char* arg
- int
- doesn't return on success, otherwise -1 w/ errno
execle
Executes program, with custom environment.
The current process is replaced with the executed one.
- const char* exe
- const char* arg
- ...
- const char* arg
- int
- doesn't return on success, otherwise -1 w/ errno
execlp
Executes program, with PATH search and current environment.
The current process is replaced with the executed one.
- const char* prog
- is program to launch (may be PATH searched)
- const char* arg
- ...
- int
- doesn't return on success, otherwise -1 w/ errno
execv
Replaces process with specific program, using default environment.
- const char* exe
- char** argv
- int
execve
Replaces current process with program.
On Windows, argv
and envp
can't contain binary strings. They need
to be valid UTF-8 in order to round-trip the WIN32 API, without being
corrupted.
On Windows, only file descriptors 0, 1 and 2 can be passed to a child process in such a way that allows them to be automatically discovered when the child process initializes. Cosmpolitan currently treats your other file descriptors as implicitly O_CLOEXEC.
- const char* prog
- char** argv
- char** envp
- char** argv
- int
- doesn't return, or -1 w/ errno
execvp
Replaces process, with path search, using default environment.
- const char* file
- char** argv
- int
execvpe
Executes program, with path environment search.
This function is a wrapper of the execve() system call that does path
resolution. The PATH
environment variable is taken from your global
environ
rather than the envp
argument.
- const char* prog
- is the program to launch
- char** argv
- is [file,argvโ..argvโโโ,NULL]
- char** envp
- is ["key=val",...,NULL]
- int
- doesn't return on success, otherwise -1 w/ errno
_Exit
Terminates process, ignoring destructors and atexit() handlers.
When running on bare metal, this function will reboot your computer by hosing the interrupt descriptors and triple faulting the system.
Exit codes are narrowed to an unsigned char on most platforms. The exceptions would be Windows, NetBSD, and OpenBSD, which should let you have larger exit codes.
- int exitcode
exit
Exits process with grace.
This calls functions registered by atexit() before terminating the current process, and any associated threads. It also calls all the legacy linker registered destructors in reversed order
This implementation allows exit() to be called recursively via atexit() handlers.
- int exitcode
- is masked with 255
_Exit1
Terminates thread with raw system call.
The function you want is pthread_exit(). If you call this function whilst using the pthreads then your joiners might not get woken up on non-Linux platforms where we zero __get_tls()->tib_tid manually
If this is the main thread, or an orphaned child thread, then this
function is equivalent to exiting the process; however, rc
shall
only be reported to the parent process on Linux, FreeBSD & Windows
whereas on other platforms, it'll be silently coerced to zero.
- int rc
- only works on Linux and Windows
_extend
Extends static allocation.
This simple fixed allocator has unusual invariants
!(p & 0xffff) && !(((p >> 3) + 0x7fff8000) & 0xffff)which must be the case when selecting a starting address. We also make the assumption that allocations can only grow monotonically. Furthermore allocations shall never be removed or relocated.
- void* p
- points to start of memory region
- unsigned long n
- specifies how many bytes are needed
- void* e
- points to end of memory that's allocated
- int f
- should be
MAP_PRIVATE
orMAP_SHARED
- long h
- is highest address to which
e
may grow
- void*
- new value for
e
or null w/ errno
fabs
Returns absolute value of floating point number.
- double x
- double
faccessat
Checks if effective user can access path in particular ways.
- int dirfd
- is normally AT_FDCWD but if it's an open directory and file is a relative path, then file is opened relative to dirfd
- const char* path
- is a filename or directory
- int amode
- can be
R_OK
,W_OK
,X_OK
, orF_OK
- int flags
- can have
AT_EACCESS
and/orAT_SYMLINK_NOFOLLOW
- int
- 0 if ok, or -1 and sets errno
mode
has bad value
mode
would be denied
path
exists as non-directory
path
doesn't exist or path
is empty
path
is a zip file and dirfd
isn't AT_FDCWD
flags
is only supported on Linux 5.8+
fadvise
Drops hints to O/S about intended I/O behavior.
It makes a huge difference. For example, when copying a large file, it can stop the system from persisting GBs of useless memory content.
- int fd
- unsigned long offset
- unsigned long len
- unsigned long offset
- 0 means until end of file
- int advice
- can be MADV_SEQUENTIAL, MADV_RANDOM, etc.
- int
- 0 on success, or -1 w/ errno
fd
isn't a valid file descriptor
fd
refers to a pipe
advice
was invalid
fchdir
Sets current directory based on file descriptor.
This does *not* update the PWD
environment variable.
- int dirfd
- int
fchmod
Changes file permissions via open()'d file descriptor.
- int fd
- unsigned int mode
- contains octal flags (base 8)
- int
fchmodat
Changes permissions on file, e.g.:
CHECK_NE(-1, fchmodat(AT_FDCWD, "foo/bar.txt", 0644)); CHECK_NE(-1, fchmodat(AT_FDCWD, "o/default/program.com", 0755)); CHECK_NE(-1, fchmodat(AT_FDCWD, "privatefolder/", 0700));
- int dirfd
- const char* path
- must exist
- unsigned int mode
- contains octal flags (base 8)
- int flags
- can have
AT_SYMLINK_NOFOLLOW
- int
dirfd
or path
use zip file system
fchown
Changes owner and/or group of file, via open()'d descriptor.
- int fd
- unsigned int uid
- is user id, or -1u to not change
- unsigned int gid
- is group id, or -1u to not change
- int
- 0 on success, or -1 w/ errno
fchownat
Changes owner and/or group of path.
- int dirfd
- is open()'d relative-to directory, or AT_FDCWD, etc.
- const char* path
- unsigned int uid
- is user id, or -1 to not change
- unsigned int gid
- is group id, or -1 to not change
- int flags
- can have AT_SYMLINK_NOFOLLOW, etc.
- int
- 0 on success, or -1 w/ errno
dirfd
or path
use zip file system
fclose
Closes standard i/o stream and its underlying thing.
- struct FILE* f
- is the file object
- int
- 0 on success or -1 on error, which can be a trick for differentiating between EOF and real errors during previous i/o calls, without needing to call ferror()
fcntl
Does things with file descriptor, e.g.
CHECK_NE(-1, fcntl(fd, F_SETFD, FD_CLOEXEC));This function lets you duplicate file descriptors without running into an edge case where they take over stdio handles:
CHECK_GE((newfd = fcntl(oldfd, F_DUPFD, 3)), 3); CHECK_GE((newfd = fcntl(oldfd, F_DUPFD_CLOEXEC, 3)), 3);This function implements file record locking, which lets independent processes (and on Linux 3.15+, threads too!) lock arbitrary ranges associated with a file. See
test/libc/calls/lock_test.c
and other
locking related tests in that folder.
On Windows, the Cosmopolitan Libc polyfill for POSIX advisory locks
only implements enough of its nuances to support SQLite's needs. Some
possibilities, e.g. punching holes in lock, will raise ENOTSUP
.
- int fd
- is the file descriptor
- int cmd
- can be one of:
F_GETFD
getsFD_CLOEXEC
status offd
F_SETFDsets
FD_CLOEXECstatus of
argfile descriptor
F_GETFLreturns file descriptor status flags
F_SETFLsets file descriptor status flags
F_DUPFDis like dup() but
argis a minimum result, e.g. 3
F_DUPFD_CLOEXECditto but sets
O_CLOEXECon returned fd
F_SETLKfor record locking where
argis
struct flock *ditto but waits for lock (SQLite avoids this)
F_GETLKto retrieve information about a record lock
F_OFD_SETLKfor better non-blocking lock (Linux 3.15+ only)
F_OFD_SETLKWfor better blocking lock (Linux 3.15+ only)
F_OFD_GETLKfor better lock querying (Linux 3.15+ only)
F_FULLFSYNCon MacOS for fsync() with release barrier
F_BARRIERFSYNCon MacOS for fsync() with even more barriers
F_SETNOSIGPIPEon MacOS and NetBSD to control
SIGPIPEon MacOS and NetBSD to control
SIGPIPEon MacOS and NetBSD where arg is
char[PATH_MAX]on NetBSD to get max open file descriptor
F_NOCACHEon MacOS to toggle data caching
F_GETPIPE_SZon Linux to get pipe size
F_SETPIPE_SZon Linux to set pipe size
F_NOTIFYraise
SIGIOupon
fdevents in
arg(Linux only) -
DN_ACCESSfor file access -
DN_MODIFYfor file modifications -
DN_CREATEfor file creations -
DN_DELETEfor file deletions -
DN_RENAMEfor file renames -
DN_ATTRIBfor file attribute changes -
DN_MULTISHOTbitwise or for realtime signals (non-coalesced)
- ...
- int
- 0 on success, or -1 w/ errno
fd
isn't a valid open file descriptor
cmd
is unknown or unsupported by os
cmd
is invalid or unsupported by os
stdio
or flock
promise
F_SETLKW
would have exceeded RLIMIT_LOCKS
cmd
is F_SETOWN
and we weren't authorized
cmd
is F_SETOWN
and process group not found
cmd
was F_SETLKW
and waiting would deadlock
cmd
is F_DUPFD
or F_DUPFD_CLOEXEC
and
RLIMIT_NOFILE
would be exceeded
cmd
is F_SETLKW
or F_OFD_SETLKW
fdatasync
Blocks until kernel flushes non-metadata buffers for fd to disk.
- int fd
- int
- 0 on success, or -1 w/ errno
fdopen
Allocates stream object for already-opened file descriptor.
- int fd
- existing file descriptor or -1 for plain old buffer
- const char* mode
- is passed to fopenflags()
- struct FILE*
- new stream or NULL w/ errno
fdopendir
Creates directory object for file descriptor.
- int fd
- gets owned by this function, if it succeeds
- struct dirstream*
- new directory object, which must be freed by closedir(), or NULL w/ errno
feclearexcept
Clears floating point exception status, e.g.
feclearexcept(FE_ALL_EXCEPT);
- excepts
- may bitwise-or the following:
FE_INVALID
FE_DIVBYZERO
FE_OVERFLOW
FE_UNDERFLOW
FE_INEXACT
FE_ALL_EXCEPT
(all of the above)
- 0 on success, or nonzero on error
feholdexcept
Saves floating-point environment and clears current exceptions.
- void** envp
- int
feof
Returns true if stream is in end-of-file state.
- struct FILE* f
- is file object stream pointer
- int
feof_unlocked
Returns true if stream is in end-of-file state.
- struct FILE* f
- is file object stream pointer
- int
ferror
Returns nonzero if stream is in error state.
- struct FILE* f
- is file stream pointer
- int
- non-zero if and only if it's an error state
ferror_unlocked
Returns nonzero if stream is in error state.
- struct FILE* f
- is file stream pointer
- int
- non-zero w/ errno only if
f
is in error state
fesetround
Sets rounding mode.
This configures the x87 FPU as well as SSE.
- int r
- int
- 0 on success, or -1 on error
fetestexcept
- excepts
- may bitwise-or the following:
FE_INVALID
FE_DIVBYZERO
FE_OVERFLOW
FE_UNDERFLOW
FE_INEXACT
FE_ALL_EXCEPT
(all of the above)
- mask of which exception status codes are currently set, or zero if there aren't any floating point exceptions
feupdateenv
Restores floating point environment and raises exceptions.
- void** envp
- int
fexecve
Executes binary executable at file descriptor.
This is only supported on Linux and FreeBSD. APE binaries are supported. Zipos is supported. Zipos fds or FD_CLOEXEC APE fds or fds that fail fexecve with ENOEXEC are copied to a new memfd (with in-memory APE to ELF conversion) and fexecve is (re)attempted.
- int fd
- is opened executable and current file position is ignored
- char** argv
- char** envp
- int
- doesn't return on success, otherwise -1 w/ errno
fd
isn't an assimilated ELF executable
fflush
Blocks until data from stream buffer is written out.
- struct FILE* f
- is the stream handle, or 0 for all streams
- int
- is 0 on success or -1 on error
fflush_unlocked
Blocks until data from stream buffer is written out.
- struct FILE* f
- is the stream handle, or 0 for all streams
- int
- is 0 on success or -1 on error
fgetc
Reads byte from stream.
- struct FILE* f
- is non-null file object stream pointer
- int
- byte in range 0..255, or -1 w/ errno
fgetc_unlocked
Reads byte from stream.
- struct FILE* f
- is file object stream pointer
- int
- byte in range 0..255, or -1 w/ errno
fgetln
Retrieves line from stream, e.g.
char *line; while ((line = _chomp(fgetln(stdin, 0)))) { printf("%s\n", line); }The returned memory is owned by the stream. It'll be reused when fgetln() is called again. It's free()'d upon fclose() / fflush()
When reading from the console on Windows in ICANON
mode, the
returned line will end with \r\n
rather than \n
.
- struct FILE* stream
- specifies non-null open input stream
- unsigned long* len
- optionally receives byte length of line
- char*
- nul-terminated line string, including the
\n
character unless a line happened before EOF without\n
, otherwise it returnsNULL
and feof() and ferror() can examine the state
fgets
Reads line from stream.
This function is similar to getline() except it'll truncate lines exceeding size. The line ending marker is included and may be removed using _chomp().
When reading from the console on Windows in ICANON
mode, the
returned line will end with \r\n
rather than \n
.
- char* s
- is output buffer
- int size
- is capacity of s
- struct FILE* f
- is non-null file object stream pointer
- char*
- s on success, NULL on error, or NULL if EOF happens when zero characters have been read
fgets_unlocked
Reads line from stream.
This function is similar to getline() except it'll truncate lines exceeding size. The line ending marker is included and may be removed using _chomp().
- char* s
- is output buffer
- int size
- is capacity of s
- struct FILE* f
- is non-null file object stream pointer
- char*
- s on success, NULL on error, or NULL if EOF happens when zero characters have been read
fgetwc
Reads UTF-8 character from stream.
- struct FILE* f
- is non-null file object stream pointer
- unsigned int
- wide character or -1 on EOF or error
fgetwc_unlocked
Reads UTF-8 character from stream.
- struct FILE* f
- unsigned int
- wide character or -1 on EOF or error
fgetws
Reads UTF-8 content from stream into UTF-32 buffer.
This function is similar to getline() except it'll truncate lines exceeding size. The line ending marker is included and may be removed using _chomp().
- int* s
- is is nul-terminated string that's non-null
- int size
- is byte length of
s
- struct FILE* f
- is file stream object pointer
- int*
fgetws_unlocked
Reads UTF-8 content from stream into UTF-32 buffer.
This function is similar to getline() except it'll truncate lines exceeding size. The line ending marker is included and may be removed using _chomp().
- int* s
- is is nul-terminated string that's non-null
- int size
- is byte length of
s
- struct FILE* f
- is file stream object pointer
- int*
fileexists
Returns true if file exists at path.
This function is equivalent to:
struct stat st; return stat(path, &st) != -1;Please note that things which aren't strictly files, e.g. directories or sockets, could be considered files for the purposes of this function. The stat() function may be used to differentiate them.
- const char* path
- _Bool
fileno
Returns file descriptor associated with stream.
- struct FILE* f
- is file stream object pointer
- int
- fd on success or -1 w/ errno;
fileno_unlocked
Returns file descriptor associated with stream.
- struct FILE* f
- is file stream object pointer
- int
- fd on success or -1 w/ errno;
FindClose
Finds more files in directory.
- long hFindFile
- int
FindComBinary
Returns path of binary without debug information, or null.
- const char*
- path to non-debug binary, or -1 w/ errno
FindContentType
Returns Content-Type for file extension.
- const char* p
- unsigned long n
- const char*
FindDebugBinary
Returns path of binary with the debug information, or null.
- const char*
- path to debug binary, or NULL
FindElfSectionByName
Returns ELF section header for section with name.
- struct Elf64_Ehdr* elf
- points to the start of the executable image data
- unsigned long mapsize
- is the number of bytes past
elf
we can access - char* shdrstrtab
- const char* name
- struct Elf64_Shdr*
- pointer to section header within image, or null
FindFirstFile
Finds first file in directory.
- const unsigned short* lpFileName
- struct NtWin32FindData* out_lpFindFileData
- long
FindNextFile
Finds more files in directory.
- long hFindFile
- struct NtWin32FindData* out_lpFindFileData
- int
__flbf
Returns nonzero if stream is line buffered.
- struct FILE* f
- int
flock
Acquires lock on file.
Please note multiple file descriptors means multiple locks.
- int fd
- int op
- can have LOCK_{SH,EX,NB,UN} for shared, exclusive, non-blocking, and unlocking
- int
- 0 on success, or -1 w/ errno
flockfile
Acquires reentrant lock on stdio object, blocking if needed.
- struct FILE* f
- void
flogf
Writes formatted message w/ timestamp to log.
- unsigned int level
- const char* file
- int line
- struct FILE* f
- const char* fmt
- ...
- const char* file
- void
FlushFileBuffers
Flushes buffers of specified file to disk.
This provides a stronger degree of assurance and blocking for things to be sent to a physical medium, but it's not guaranteed unless your file is opened in a direct non-caching mode. One main advantage here seems to be coherency.
- long hFile
- int
FlushViewOfFile
Syncs memory created by MapViewOfFileEx().
This doesn't wait until the pages are written out to the physical medium. This doesn't update timestamps or file/dir metadata.
- void* lpBaseAddress
- unsigned long dwNumberOfBytesToFlush
- int
fma
Performs fused multiply add.
- double x
- double y
- double z
- double y
- double
๐ฅ * ๐ฆ + ๐ง
rounded as one ternary operation
fmaf
Performs fused multiply add.
- float x
- float y
- float z
- float y
- float
๐ฅ * ๐ฆ + ๐ง
with a single rounding error
fmax
Returns maximum of two doubles.
If one argument is NAN then the other is returned. This function is designed to do the right thing with signed zeroes.
- double x
- double y
- double
fmaxf
Returns maximum of two floats.
If one argument is NAN then the other is returned. This function is designed to do the right thing with signed zeroes.
- float x
- float y
- float
fmaxl
Returns maximum of two long doubles.
If one argument is NAN then the other is returned. This function is designed to do the right thing with signed zeroes.
- long double x
- long double y
- long double
fmemopen
Opens buffer as stream.
- void* buf
- becomes owned by this function, and is allocated if NULL
- unsigned long size
- const char* mode
- struct FILE*
- new stream or NULL w/ errno
buf
is NULL and we failed to allocate it
buf
is NULL and malloc() wasn't linked
buf
is NULL when +
isn't in mode
fmin
Returns minimum of two doubles.
If one argument is NAN then the other is returned. This function is designed to do the right thing with signed zeroes.
- double x
- double y
- double
fminl
Returns minimum of two long doubles.
If one argument is NAN then the other is returned. This function is designed to do the right thing with signed zeroes.
- long double x
- long double y
- long double
fmod
Does (๐ฅ rem ๐ฆ) w/ round()-style rounding.
- double x
- double y
- double
- remainder โ (-|๐ฆ|,|๐ฆ|) in %xmm0
fmodl
Does (๐ฅ rem ๐ฆ) w/ round()-style rounding.
- long double x
- long double y
- long double
- remainder โ (-|๐ฆ|,|๐ฆ|) in %xmm0
fnmatch
Matches filename.
*
for wildcard?
for single character[abc]
to match character within set[!abc]
to match character not within set\*\?\[\]
for escaping above special syntax
- const char* pat
- const char* str
- int flags
- const char* str
- int
FoldHeader
Collapses repeating headers onto a single line.
- struct HttpMessage* msg
- char* b
- int h
- unsigned long* z
- char* b
- char*
fopen
Opens file as stream object.
- const char* pathname
- is a utf-8 ideally relative filename
- const char* mode
- is the string mode/flag DSL see fopenflags()
- struct FILE*
- new object to be free'd by fclose() or NULL w/ errno
fork
Creates new process.
- int
- 0 to child, child pid to parent, or -1 w/ errno
RLIMIT_NPROC
was exceeded or system lacked resources
__FormatBinary64
Converts unsigned 64-bit integer to binary string.
- char* p
- needs at least 67 bytes
- unsigned long x
- char z
- is 0 for DIGITS, 1 for 0bDIGITS, 2 for 0bDIGITS if โ 0
- char*
- pointer to nul byte
__FormatFlex64
Formats integer using decimal or hexadecimal.
This formats as int64 signed decimal. However it's a:
- positive number
- with population count of 1
- and a magnitude of at least 256
- char* p
- long x
- char z
- long x
- char*
__FormatHex64
Converts unsigned 64-bit integer to hex string.
- char* p
- needs at least 19 bytes
- unsigned long x
- char z
- is 0 for DIGITS, 1 for 0xDIGITS, 2 for 0xDIGITS if โ 0
- char*
- pointer to nul byte
FormatHttpDateTime
Formats HTTP timestamp, e.g.
Sun, 04 Oct 2020 19:50:10 GMT
This function is the same as:
strftime(p, 30, "%a, %d %b %Y %H:%M:%S %Z", tm)Except this function goes 10x faster:
FormatHttpDateTime l: 25๐ 8๐๐ strftime l: 709๐ 229๐๐
- char* p
- struct tm* tm
- must be zulu see gmtime_r() and nowl()
- char*
__FormatInt32
Converts signed 32-bit integer to string.
- char* p
- needs at least 12 bytes
- int x
- char*
- pointer to nul byte
__FormatInt64
Converts signed 64-bit integer to string.
- char* p
- needs at least 21 bytes
- long x
- char*
- pointer to nul byte
__FormatInt64Thousands
Converts 64-bit integer to string w/ commas.
- char* p
- needs at least 27 bytes
- long x
- char*
- pointer to nul byte
__FormatOctal32
Converts unsigned 32-bit integer to octal string.
- char* p
- needs at least 12 bytes
- unsigned int x
- _Bool z
- ensures it starts with zero
- char*
- pointer to nul byte
__FormatOctal64
Converts unsigned 64-bit integer to octal string.
- char* p
- needs at least 24 bytes
- unsigned long x
- _Bool z
- ensures it starts with zero
- char*
- pointer to nul byte
__FormatUint32
Converts unsigned 32-bit integer to string.
- char* p
- needs at least 12 bytes
- unsigned int x
- char*
- pointer to nul byte
__FormatUint64
Converts unsigned 64-bit integer to string.
- char* p
- needs at least 21 bytes
- unsigned long x
- char*
- pointer to nul byte
__FormatUint64Thousands
Converts unsigned 64-bit integer to string w/ commas.
- char* p
- needs at least 27 bytes
- unsigned long x
- char*
- pointer to nul byte
fprintf
Formats and writes text to stream.
- struct FILE* f
- const char* fmt
- ...
- const char* fmt
- int
fprintf_unlocked
Formats and writes text to stream.
- struct FILE* f
- const char* fmt
- ...
- const char* fmt
- int
fpurge
Discards contents of stream buffer.
- struct FILE* f
- int
fputc
Writes byte to stream.
- int c
- is byte to buffer or write, which is masked
- struct FILE* f
- int
- c as unsigned char if written or -1 w/ errno
fputc_unlocked
Writes byte to stream.
- int c
- is byte to buffer or write, which is masked
- struct FILE* f
- int
- c as unsigned char if written or -1 w/ errno
fputs
Writes string to stream.
Writing stops at the NUL-terminator, which isn't included in output. This function blocks until the full string is written, unless an unrecoverable error happens.
- const char* s
- is a NUL-terminated string that's non-NULL
- struct FILE* f
- is an open stream
- int
- bytes written, or -1 w/ errno
fputs_unlocked
Writes string to stream.
Writing stops at the NUL-terminator, which isn't included in output. This function blocks until the full string is written, unless an unrecoverable error happens.
- const char* s
- is a NUL-terminated string that's non-NULL
- struct FILE* f
- is an open stream
- int
- bytes written, or -1 w/ errno
fputwc
Writes wide character to stream.
- int wc
- has wide character
- struct FILE* f
- is file object stream pointer
- unsigned int
- wide character if written or -1 w/ errno
fputwc_unlocked
Writes wide character to stream.
- int wc
- has wide character
- struct FILE* f
- is file object stream pointer
- unsigned int
- wide character if written or -1 w/ errno
fputws
Writes wide character string to stream.
Writing stops at the NUL-terminator, which isn't included in output. This function blocks until the full string is written, unless an unrecoverable error happens.
- const int* s
- is a NUL-terminated string that's non-NULL
- struct FILE* f
- is an open stream
- int
- strlen(s), or -1 w/ errno
fputws_unlocked
Writes wide character string to stream.
Writing stops at the NUL-terminator, which isn't included in output. This function blocks until the full string is written, unless an unrecoverable error happens.
- const int* s
- is a NUL-terminated string that's non-NULL
- struct FILE* f
- is an open stream
- int
- strlen(s), or -1 w/ errno
fread
Reads data from stream.
- void* buf
- unsigned long stride
- specifies the size of individual items
- unsigned long count
- is the number of strides to fetch
- struct FILE* f
- unsigned long
- count on success, [0,count) on eof, or 0 on error or count==0
fread_unlocked
Reads data from stream.
- void* buf
- unsigned long stride
- specifies the size of individual items
- unsigned long count
- is the number of strides to fetch
- struct FILE* f
- unsigned long
- count on success, [0,count) on eof, or 0 on error or count==0
free
Free memory returned by malloc() & co.
Releases the chunk of memory pointed to by p, that had been previously allocated using malloc or a related routine such as realloc. It has no effect if p is null.
- void* p
- is allocation address, which may be NULL
- void
freeaddrinfo
Frees addresses returned by getaddrinfo().
- struct addrinfo* ai
- void
FreeHostsTxt
Frees HOSTS.TXT data structure populated by ParseHostsTxt().
- struct ht** ht
- void
FreeResolvConf
Frees resolv.conf data structure populated by ParseResolvConf().
- struct rv** rvp
- void
freopen
Overwrites existing stream.
This function can be used in two ways. The first is sort of a mutating assignment. The second behavior, if pathname is NULL, is just changing the mode of an already open file descriptor.
- const char* pathname
- is the file to open or NULL
- const char* mode
- is the mode string flags, see fopenflags()
- struct FILE* stream
- is the existing allocated stream memory, which is flushed and closed if already open
- struct FILE*
- stream object if successful, or NULL w/ errno
fscanf
Decodes data from stream.
To read a line of data from a well-formed trustworthy file:
int x, y; char text[256]; fscanf(f, "%d %d %s\n", &x, &y, text);Please note that this function is brittle by default, which makes it a good fit for yolo coding. With some toil it can be used in a way that makes it reasonably hardened although getline() may be better.
- struct FILE* stream
- const char* fmt
- ...
- const char* fmt
- int
fseeko
Repositions open file stream.
This function flushes the buffer (unless it's currently in the EOF state) and then calls lseek() on the underlying file. If the stream is in the EOF state, this function can be used to restore it without needing to reopen the file.
- struct FILE* f
- is a non-null stream handle
- long offset
- is the byte delta
- int whence
- can be SEET_SET, SEEK_CUR, or SEEK_END
- int
fseeko_unlocked
Repositions open file stream.
This function flushes the buffer (unless it's currently in the EOF state) and then calls lseek() on the underlying file. If the stream is in the EOF state, this function can be used to restore it without needing to reopen the file.
- struct FILE* f
- is a non-null stream handle
- long offset
- is the byte delta
- int whence
- can be SEET_SET, SEEK_CUR, or SEEK_END
- int
__fsetlocking
Does nothing and returns FSETLOCKING_INTERNAL
.
- struct FILE* f
- int type
- int
fstat
Returns information about file, via open()'d descriptor.
- int fd
- struct stat* st
- int
- 0 on success or -1 w/ errno
fd
isn't a valid file descriptor
fstatat
Returns information about thing.
- int dirfd
- is normally AT_FDCWD but if it's an open directory and file is a relative path, then file becomes relative to dirfd
- const char* path
- struct stat* st
- is where result is stored
- int flags
- can have AT_SYMLINK_NOFOLLOW
- int
- 0 on success, or -1 w/ errno
fstatfs
Returns information about filesystem.
- int fd
- struct statfs* sf
- int
- 0 on success, or -1 w/ errno
fstatvfs
Returns information about filesystem.
- int fd
- struct statvfs* sv
- int
- 0 on success, or -1 w/ errno
fsum
Adds doubles in array.
- const double* p
- unsigned long n
- double
fsync
Blocks until kernel flushes buffers for fd to disk.
- int fd
- int
- 0 on success, or -1 w/ errno
ftello
Returns current position of stream.
- struct FILE* f
- long
ftok
Convert pathname and a project ID to System V IPC key.
- const char* path
- int id
- int
__ftrace
Function tracing enabled state.
After ftrace_install() has been called, the logging of C function
calls may be controlled by changing this variable. If __ftrace
is
greater than zero, functions are logged. Otherwise, they aren't.
By convention, functions wishing to disable function tracing for a short time period should say:
void foo() { ftrace_enabled(-1); bar(); ftrace_enabled(+1); }This way you still have some flexibility to force function tracing, by setting
__ftrace
to a higher number like 2
or 200
. Even
though under normal circumstances, __ftrace
should only be either
zero or one.
- int
ftrace_enabled
Changes function call logging state for current thread.
- int delta
- is added to enabled state
- int
- enabled state before
delta
was applied
ftrace_init
Enables plaintext function tracing if --ftrace
flag is passed.
The --ftrace
CLI arg is removed before main() is called. This code
is intended for diagnostic purposes and assumes binaries are
trustworthy and stack isn't corrupted. Logging plain text allows
program structure to easily be visualized and hotspots identified w/
sed | sort | uniq -c | sort
. A compressed trace can be made by
appending --ftrace 2>&1 | gzip -4 >trace.gz
to the CLI arguments.
- int
ftracer
Prints name of function being called.
Whenever a function is called, ftrace_hook() will be called from the function prologue which saves the parameter registers and calls this function, which is responsible for logging the function call.
- void
ftruncate
Changes size of open file.
If the file size is increased, the extended area shall appear as if it were zero-filled. If your file size is decreased, the extra data shall be lost.
This function never changes the file position. This is true even if ftruncate() causes the position to become beyond the end of file in which case, the rules described in the lseek() documentation apply.
Some operating systems implement an optimization, where length
is
treated as a logical size and the requested physical space won't be
allocated until non-zero values get written into it. Our tests show
this happens on Linux (usually with 4096 byte granularity), FreeBSD
(which favors 512-byte granularity), and MacOS (prefers 4096 bytes)
however Windows, OpenBSD, and NetBSD always reserve physical space.
This may be inspected using fstat() and consulting stat::st_blocks.
- int fd
- must be open for writing
- long length
- may be greater than current current file size
- int
- 0 on success, or -1 w/ errno
length
is negative
length
is too huge
fd
is a zip file descriptor
fd
isn't an open file descriptor
fd
is a non-file, e.g. pipe, socket
fd
wasn't opened in a writeable mode
ftrylockfile
Tries to acquire reentrant stdio object lock.
- struct FILE* f
- int
- 0 on success, or non-zero if another thread owns the lock
ftw
Walks file tree.
- const char* dirpath
- int(*)() fn
- int fd_limit
- int(*)() fn
- int
- 0 on success, -1 on error, or non-zero
fn
result
futimens
Changes access/modified time on open file, the modern way.
XNU only has microsecond (1e-6) accuracy. Windows only has hectonanosecond (1e-7) accuracy. RHEL5 (Linux c. 2007) doesn't support this system call.
- int fd
- is file descriptor of file whose timestamps will change
- struct __ts* ts
- is {access, modified} timestamps, or null for current time
- int
- 0 on success, or -1 w/ errno
fd
is on the zip filesystem
flags
had an unrecognized value
fattr
promise
ts
specifies a nanosecond value that's out of range
fd
isn't an open file descriptor
ts
memory was invalid
futimes
Sets atime/mtime on file descriptor.
- int fd
- struct __tv* tv
- int
- 0 on success, or -1 w/ errno
fd
is on zip filesystem
fd
isn't an open file descriptor
fattr
promise
tv
specifies a microsecond value that's out of range
futimesat
Changes last accessed/modified times on file.
- int dirfd
- const char* pathname
- struct __tv* tv
- const char* pathname
- int
- 0 on success or -1 w/ errno
fwrite
Writes data to stream.
- void* data
- unsigned long stride
- specifies the size of individual items
- unsigned long count
- is the number of strides to write
- struct FILE* f
- unsigned long
- count on success, [0,count) on EOF, 0 on error or count==0
fwrite_unlocked
Writes data to stream.
- void* data
- unsigned long stride
- specifies the size of individual items
- unsigned long count
- is the number of strides to write
- struct FILE* f
- unsigned long
- count on success, [0,count) on EOF, 0 on error or count==0
__g_Qfmt_p
Converts quadruple-precision floating-point number to string.
- char* buf
- void* V
- int ndig
- unsigned long bufsize
- int nik
- void* V
- char*
_gc
Frees memory when function returns.
This garbage collector overwrites the return address on the stack so that the RET instruction calls a trampoline which calls free(). It's loosely analogous to Go's defer keyword rather than a true cycle gc.
const char *s = _gc(strdup("hello")); puts(s);This macro is equivalent to:
_defer(free, ptr)
- void* thing
- void*
__gc
Invokes deferred function calls.
This offers behavior similar to std::unique_ptr. Functions overwrite their return addresses jumping here, and pushing exactly one entry on the shadow stack below. Functions may repeat that process multiple times, in which case the body of this gadget loops and unwinds as a natural consequence.
- rax,rdx,xmm0,xmm1,st0,st1
- is return value
_gclongjmp
Jumps up stack to previous setjmp() invocation.
This is the same as longjmp() but also unwinds the stack to free memory, etc. that was registered using gc() or defer(). If GC isn't linked, this behaves the same as longjmp().
- rdi
- points to the jmp_buf which must be the same stack
- esi
- is returned by setjmp() invocation (coerced nonzero)
gdbexec
Attaches GDB temporarily, to do something like print a variable.
- const char* cmd
- int
GenerateConsoleCtrlEvent
Sends signal to process group that shares console w/ calling process.
- unsigned int dwCtrlEvent
- can be kNtCtrlCEvent or kNtCtrlBreakEvent
- unsigned int dwProcessGroupId
- int
get_current_dir_name
Returns current working directory.
If the PWD
environment variable is set, and it seems legit, then
that'll be returned.
- char*
- pointer that must be free()'d, or NULL w/ errno
__get_symbol
Returns low index into symbol table for address.
- struct SymbolTable* t
- if null will be auto-populated only if already open
- long a
- int
- index or -1 if nothing found
__get_virtual
Returns pointer to page table entry for page at virtual address. Additional page tables are allocated if needed as a side-effect.
- struct mman* mm
- unsigned long* t
- long vaddr
- _Bool maketables
- unsigned long* t
- unsigned long*
getaddrinfo
Resolves address for internet name.
- const char* name
- is either an ip string or a utf-8 hostname
- const char* service
- is the port number as a string
- struct addrinfo* hints
- may be passed to specialize behavior (optional)
- struct addrinfo** res
- receives a pointer that must be freed with freeaddrinfo(), and won't be modified if non-zero is returned
- int
- 0 on success or EAI_xxx value
_getauxval
Returns auxiliary value better.
- unsigned long at
- is
AT_...
search key
- struct AuxiliaryValue
- true if value was found
getauxval
Returns auxiliary value.
- unsigned long key
- unsigned long
- auxiliary value or 0 if
key
not found
_getcachesize
Returns CPU cache size.
- int type
- 1=data, 2=instruction, 3=unified
- int level
- starts at 1
- unsigned int
- size in bytes, or 0 if unknown
GetCallerName
Returns name of function that called caller function.
- struct StackFrame* bp
- const char*
getchar
Reads byte from stdin.
- int
- byte in range 0..255, or -1 w/ errno
getcontext
Gets machine state.
This function goes 14x slower if sigaction() has ever been used to
install a signal handling function. If you don't care about signal
safety and just want fast fibers, then you may override the global
variable __interruptible
to disable the sigprocmask() calls, for
pure userspace context switching.
- 0 on success, or -1 w/ errno
_getcpucount
Returns number of CPUs in system.
This is the same as the standard interface:
sysconf(_SC_NPROCESSORS_ONLN);Except this function isn't a bloated diamond dependency.
On Intel systems with HyperThreading this will return the number of cores multiplied by two.
- int
- cpu count or 0 if it couldn't be determined
getcwd
Returns current working directory, e.g.
const char *dirname = gc(getcwd(0,0)); // if malloc is linked const char *dirname = getcwd(alloca(PATH_MAX),PATH_MAX);
- char* buf
- is where UTF-8 NUL-terminated path string gets written, which may be NULL to ask this function to malloc a buffer
- unsigned long size
- is number of bytes available in buf, e.g. PATH_MAX+1, which may be 0 if buf is NULL
- char*
- buf containing system-normative path or NULL w/ errno
getdelim
Reads string from stream, e.g.
char *line = NULL; size_t linesize = 0; while (getdelim(&line, &linesize, '\n', stdin) > 0) { _chomp(line); printf("%s\n", line); } free(line);
- char** s
- is the caller's buffer (in/out) which is extended or allocated automatically, also NUL-terminated is guaranteed
- unsigned long* n
- is the capacity of s (in/out)
- int delim
- is the stop char (and NUL is implicitly too)
- struct FILE* f
- long
- number of bytes read >0, including delim, excluding NUL, or -1 w/ errno on EOF or error; see ferror() and feof()
getdelim_unlocked
Reads string from unlocked stream.
- char** s
- unsigned long* n
- int delim
- struct FILE* f
- unsigned long* n
- long
getdomainname
Returns domain of current host.
For example, if the fully-qualified hostname is "host.domain.example" then this SHOULD return "domain.example" however, it might not be the case; it depends on how the host machine is configured.
The nul / mutation semantics are tricky. Here is some safe copypasta:
char domain[254]; if (getdomainname(domain, sizeof(domain))) { strcpy(domain, "(none)"); }On Linux this is the same as
/proc/sys/kernel/domainname
. However,
we turn the weird "(none)"
string into empty string.
- char* name
- receives output name, which is guaranteed to be complete and have a nul-terminator if this function return zero
- unsigned long len
- is size of
name
consider usingDNS_NAME_MAX + 1
(254)
- int
- 0 on success, or -1 w/ errno
len
is negative
name
is an invalid address
len
in
which case this error is raised and the buffer is modified, with
as many bytes of hostname as possible excluding a nul-terminator
GetDosArgv
- const unsigned short* cmdline
- char* buf
- unsigned long size
- char** argv
- unsigned long max
- char* buf
- int
GetDosEnviron
- const unsigned short* env
- char* buf
- unsigned long size
- char** envp
- unsigned long max
- char* buf
- int
getdtablesize
Gets file descriptor table size.
- int
- current limit on the number of open files per process
getegid
Returns effective group ID of calling process.
- unsigned int
- group id
GetElfProgramHeaderAddress
Returns program header at elf.phdr[i]
.
- struct Elf64_Ehdr* elf
- points to the start of the executable image
- unsigned long mapsize
- is the number of bytes past
elf
we can access - unsigned short i
- is the program header index, starting at zero
- struct Elf64_Phdr*
- program header pointer, or null on error
GetElfSectionAddress
Returns pointer to ELF section file content.
This function computes elf + sh_offset
with safety checks.
- struct Elf64_Ehdr* elf
- points to the start of the executable image data
- unsigned long mapsize
- is the number of bytes of
elf
we can access - struct Elf64_Shdr* shdr
- is from GetElfSectionHeaderAddress(), or null
- void*
- pointer to section data within image, or null if
shdr
was null, or- content wasn't contained within
[elf,elf+mapsize)
, or - an arithmetic overflow occurred
GetElfSectionHeaderAddress
Returns section header object at elf.section[i]
.
- struct Elf64_Ehdr* elf
- points to the start of the executable image data
- unsigned long mapsize
- is the number of bytes past
elf
we can access - unsigned short i
- is the index of the section header
- struct Elf64_Shdr*
- pointer to section header within image, or null if
i
was a magic number, i.e.i >= SHN_LORESERVE
, ore_shoff
was zero (image has no section headers), ore_shentsize
had fewer than the mandatory 60 bytes, or- section header wasn't contained by
[elf,elf+mapsize)
, or - an arithmetic overflow occurred
GetElfSectionName
- struct Elf64_Ehdr* elf
- unsigned long mapsize
- struct Elf64_Shdr* shdr
- unsigned long mapsize
- const char*
GetElfSectionNameStringTable
Returns section name string table.
- struct Elf64_Ehdr* elf
- points to the start of the executable image
- unsigned long mapsize
- is the number of bytes past
elf
we can access
- char*
- double-nul terminated string list, or null on error
GetElfSegmentAddress
Returns pointer to ELF segment file content.
This function computes elf + p_offset
with safety checks.
- struct Elf64_Ehdr* elf
- points to the start of the executable image data
- unsigned long mapsize
- is the number of bytes of
elf
we can access - struct Elf64_Phdr* phdr
- is from GetElfProgramHeaderAddress(), or null
- void*
- pointer to segment data within image, or null if
phdr
was null, orp_filesz
was zero, or- content wasn't contained within
[elf,elf+mapsize)
, or - an arithmetic overflow occurred
GetElfString
Returns strtab + i
from elf string table.
- struct Elf64_Ehdr* elf
- points to the start of the executable image data
- unsigned long mapsize
- is the number of bytes past
elf
we can access - const char* strtab
- is double-nul string list from GetElfStringTable()
which may be null, in which case only the
!i
name is valid - unsigned int i
- is byte index into strtab where needed string starts or zero (no name) in which case empty string is always returned as a pointer to the read-only string literal, rather than in the elf image, since the elf spec permits an empty or absent string table section
- const char*
- a const nul-terminated string pointer, otherwise null if
i
was nonzero andstrtab
was null, orstrtab+i
wasn't inside[elf,elf+mapsize)
, or- a nul byte wasn't present within
[strtab+i,elf+mapsize)
, or - an arithmetic overflow occurred
GetElfStringTable
Returns pointer to elf string table.
- struct Elf64_Ehdr* elf
- points to the start of the executable image data
- unsigned long mapsize
- is the number of bytes past
elf
we can access - const char* section_name
- is usually
".strtab"
,".dynstr"
, or null
- char*
- pointer to string table within
elf
image, which should normally be a sequence of NUL-terminated strings whose first string is the empty string; otherwise NULL is returned, when either: (1)section_name
is not found, (2) it did not have theSHT_STRTAB
section type, (3) the section size was zero noting that the ELF spec does consider that legal, or lastly (4) an overflow or boundary violation occurred
GetElfSymbols
Returns pointer to array of elf symbols.
This is a shortcut composing GetElfSymbolTable() and GetElfSectionAddress(), that can be used as follows:
Elf64_Xword i, n; Elf64_Sym *st = GetElfSymbols(map, size, SHT_SYMTAB, &n); for (i = 0; st && i < n; ++i) { // st[i] holds a symbol }The above code will iterate over the relocatable and/or statically-linked symbols defined by an ELF image.
- struct Elf64_Ehdr* elf
- points to the start of the executable image data
- unsigned long mapsize
- is the number of bytes past
elf
we can access - int section_type
- is usually
SHT_SYMTAB
orSHT_DYNSYM
- unsigned long* out_count
- optionally receives number of symbols
- struct Elf64_Sym*
- pointer to array of elf symbol array, otherwise null
GetElfSymbolTable
Returns pointer to the elf section header for a symbol table.
The easiest way to get the symbol table is:
Elf64_Xword i, n; Elf64_Sym *st = GetElfSymbols(map, size, SHT_SYMTAB, &n); for (i = 0; st && i < n; ++i) { // st[i] holds a symbol }This API is more verbose than the GetElfSymbols() shortcut, however calling this the long way makes tricks like the following possible:
Elf64_Xword i, n; Elf64_Shdr *sh = GetElfSymbolTable(map, size, SHT_SYMTAB, &n); Elf64_Sym *st = GetElfSectionAddress(map, size, sh); if (st) { for (i = sh->sh_info; i < n; ++i) { // st[i] holds a non-local symbol } }Our code here only cares about
STB_GLOBAL
and STB_WEAK
symbols
however SHT_SYMTAB
usually has countless STB_LOCAL
entries too
that must be skipped over. The trick is that the ELF spec requires
local symbols be ordered before global symbols, and that the index
dividing the two be stored to sh_info
. So, if we start iterating
there, then we've cleverly avoided possibly dozens of page faults!
- struct Elf64_Ehdr* elf
- points to the start of the executable image data
- unsigned long mapsize
- is the number of bytes past
elf
we can access - int section_type
- is usually
SHT_SYMTAB
orSHT_DYNSYM
- unsigned long* out_count
- optionally receives number of symbols
- struct Elf64_Shdr*
- pointer to symbol table section header, otherwise null
getentropy
Returns random seeding bytes, the XNU/OpenBSD way.
- void* p
- unsigned long n
- int
- 0 on success, or -1 w/ errno
n
bytes at p
aren't valid memory
getenv
Returns value of environment variable, or NULL if not found.
Environment variables can store empty string on Unix but not Windows.
- const char* s
- char*
- pointer to value of
environ
entry, or null if not found
geteuid
Returns effective user ID of calling process.
- unsigned int
- user id
GetExitCodeProcess
Obtains exit code for process.
- long hProcess
- unsigned int* lpExitCode
- int
GetFileAttributes
Gets file info on the New Technology.
- const unsigned short* lpPathName
- unsigned int
- handle, or -1u on failure
getgid
Returns real group id of process.
This never fails. On Windows, which doesn't really have this concept, we return a deterministic value that's likely to work.
- unsigned int
- group id (always successful)
getgrgid_r
- unsigned int gid
- struct gr* gr
- char* buf
- unsigned long size
- struct gr** res
- struct gr* gr
- int
getgrnam_r
- const char* name
- struct gr* gr
- char* buf
- unsigned long size
- struct gr** res
- struct gr* gr
- int
getgroups
Gets list of supplementary group IDs
- int size
- maximum number of items that can be stored in list
- unsigned int* list
- buffer to store output gid_t
- int
- -1 w/ EFAULT
GetHostIps
Returns IP addresses of system.
Normally return values will look like {0x7f000001, 0x0a0a0a7c, 0}
which means the same thing as {"127.0.0.1", "10.10.10.124", 0}
.
Returned IPs will IPv4 anycast addresses bound to network interfaces
which come in a NULL-terminated array with no particular ordering.
uint32_t *ip, *ips = GetIps(); for (ip = ips; *ip; ++ip) { printf("%hhu.%hhu.%hhu.%hhu\n", *ip >> 24, *ip >> 16, *ip >> 8, *ip); }This function supports Windows, Linux, XNU, FreeBSD, NetBSD, OpenBSD.
- unsigned int*
- null-terminated ip array on success, or null w/ errno
gethostname
Returns name of current host.
For example, if the fully-qualified hostname is "host.domain.example" then this SHOULD return "host" however that might not be the case; it depends on how the host machine is configured. It's fair to say if it has a dot, it's a FQDN, otherwise it's a node.
The nul / mutation semantics are tricky. Here is some safe copypasta:
char host[254]; if (gethostname(host, sizeof(host))) { strcpy(host, "localhost"); }On Linux this is the same as
/proc/sys/kernel/hostname
.
- char* name
- receives output name, which is guaranteed to be complete and have a nul-terminator if this function return zero
- unsigned long len
- is size of
name
consider usingDNS_NAME_MAX + 1
(254)
- int
- 0 on success, or -1 w/ errno
len
is negative
name
is an invalid address
len
in
which case this error is raised and the buffer is modified, with
as many bytes of hostname as possible excluding a nul-terminator
GetHostsTxt
Returns hosts.txt map.
- struct HostsTxt*
GetHttpHeader
Returns small number for HTTP header, or -1 if not found.
- const char* str
- unsigned long len
- int
GetHttpMethod
Converts HTTP method string into internal index
- const char* str
- unsigned long len
- if -1 implies strlen
- int
- small number for HTTP method, or 0 if not found.
GetHttpReason
Returns string describing HTTP reason phrase.
- int code
- const char*
GetInterpreterExecutableName
Returns path of executable interpreter.
Unlike program_executable_name
which is designed to figure out the
absolute path of the first argument passed to execve()
, what we do
here is probe things like /proc
and sysctl()
to figure out if we
were launched by something like ape-loader
, and then we return its
path. If we can't determine that path, possibly because we're on XNU
or OpenBSD, then we return -1 with an error code.
- char* p
- receives utf8 output
- unsigned long n
- is byte size of res buffer
- char*
- p on success or null w/ errno if out of buf or error
getitimer
Retrieves last setitimer() value, correcting for remaining time.
- int which
- can be ITIMER_REAL, ITIMER_VIRTUAL, etc.
- struct itimerval* curvalue
- int
- 0 on success or -1 w/ errno
getline
Reads line from stream, e.g.
char *line = NULL; size_t linesize = 0; while (getline(&line, &linesize, stdin) > 0) { _chomp(line); printf("%s\n", line); } free(line);This function delegates to getdelim(), which provides further documentation. Concerning lines, please note the \n or \r\n are included in results, and can be removed with _chomp().
When reading from the console on Windows in ICANON
mode, the
returned line will end with \r\n
rather than \n
.
- char** linebuf
- is the caller's buffer (in/out) which is extended automatically. *line may be NULL but only if *capacity is 0; NUL-termination is guaranteed FTMP
- unsigned long* capacity
- struct FILE* f
- long
- number of bytes read, including delim, excluding NUL, or -1 w/ errno on EOF or error; see ferror() and feof()
getloadavg
Returns system load average.
- double* a
- should be array of 3 doubles
- int n
- should be 3
- int
- number of items placed in
a
or -1 w/ errno
getnameinfo
Resolves name/service for socket address.
- struct sockaddr* addr
- unsigned int addrlen
- char* name
- unsigned int namelen
- char* service
- unsigned int servicelen
- int flags
- unsigned int addrlen
- int
- 0 on success or EAI_xxx value
GetNtNameServers
Extracts DNS nameserver IPs from Windows Registry.
- struct ResolvConf* resolv
- points to a ResolvConf object, which should be zero initialized by the caller; or if it already contains items, this function will append
- int
- number of nameservers appended, or -1 w/ errno
GetNtOpenFlags
- int flags
- int mode
- unsigned int* out_perm
- unsigned int* out_share
- unsigned int* out_disp
- unsigned int* out_attr
- int mode
- int
__getntsyspath
Obtains WIN32 magic path, e.g. GetTempPathA.
- rax
- is address of ANSI path provider function
- rdi
- is output buffer
- rdx
- is output buffer size in bytes that's >0
- eax is string length w/ NUL that's โค edx
- rdi is rdi+edx
__getopt
Parses argc/argv argument vector, e.g.
while ((opt = getopt(argc, argv, "hvx:")) != -1) { switch (opt) { case 'x': x = atoi(optarg); break; case 'v': ++verbose; break; case 'h': PrintUsage(EXIT_SUCCESS, stdout); default: PrintUsage(EX_USAGE, stderr); } }
- int nargc
- char** nargv
- const char* ostr
- char** nargv
- int
getopt_long
- int nargc
- char** nargv
- const char* options
- struct option* long_options
- int* idx
- char** nargv
- int
getopt_long_only
- int nargc
- char** nargv
- const char* options
- struct option* long_options
- int* idx
- char** nargv
- int
getpagesize
Returns granularity of memory manager.
- int
getpeername
Returns details about remote end of connected socket.
- int fd
- struct sa* out_addr
- unsigned int* inout_addrsize
- struct sa* out_addr
- int
- 0 on success or -1 w/ errno
getpgrp
Returns process group id of calling process.
This function is equivalent to getpgid(0)
.
- int
getpid
Returns process id.
This function does not need to issue a system call. The PID is
tracked by a global variable which is updated at fork(). The only
exception is when the process is vfork()'d in which case a system
call shall be issued. This optimization helps make functions like
_rand64() fork-safe, however it could lead to race conditions in
programs that mix fork() with threads. In that case, apps should
consider using sys_getpid().ax
instead to force a system call.
On Linux, and only Linux, getpid() is guaranteed to equal gettid() for the main thread.
- int
- process id (always successful)
getppid
Returns parent process id.
- int
- parent process id (always successful)
getpriority
Returns nice value of thing.
Since -1 might be a valid return value for this API, it's necessary
to clear errno
beforehand and see if it changed, in order to truly
determine if an error happened.
On Windows, there's only six priority classes. We define them as -16 (realtime), -10 (high), -5 (above), 0 (normal), 5 (below), 15 (idle) which are the only values that'll roundtrip getpriority/setpriority.
- int which
- can be one of:
PRIO_PROCESS
is supported universallyPRIO_PGRP
is supported on unixPRIO_USER
is supported on unix
- unsigned int who
- is the pid, pgid, or uid (0 means current)
- int
- value โ [-NZERO,NZERO) or -1 w/ errno
which
was invalid or unsupported
GetProcAddressModule
Returns address of function in a DLL that's already loaded.
- const char* module
- const char* symbol
- void*
getpwnam_r
- const char* name
- struct pw* pw
- char* buf
- unsigned long size
- struct pw** res
- struct pw* pw
- int
getpwuid_r
- unsigned int uid
- struct pw* pw
- char* buf
- unsigned long size
- struct pw** res
- struct pw* pw
- int
getrandom
Returns cryptographic random data.
This random number seed generator obtains information from:
- RtlGenRandom() on Windows
- getentropy() on XNU and OpenBSD
- getrandom() on Linux, FreeBSD, and NetBSD
- sysctl(KERN_ARND) on older versions of FreeBSD and NetBSD
f
is zero and n
is no more than 256,
noting that kernels are a bit vague with their promises here, and
if you're willing to trade some performance for a more assurances
that EINTR won't happen, then either consider using getentropy(),
or using the SA_RESTART
flag on your signal handlers.
Unlike getentropy() you may specify an n
greater than 256. When
larger amounts are specified, the caller must be prepared for the
case where fewer than n
bytes are returned. In that case, it is
likely that a signal delivery occured. Cancellations in mask mode
also need to be suppressed while processing the bytes beyond 256.
On BSD OSes, this entire process is uninterruptible so be careful
when using large sizes if interruptibility is needed.
Unlike getentropy() this function is a cancellation point. But it shouldn't be a problem, unless you're using masked mode, in which case extra care must be taken to consider the result.
It's recommended that f
be set to zero, although it may include
the following flags:
GRND_NONBLOCK
when you want to elevate the insecurity of your random dataGRND_RANDOM
if you want to have the best possible chance your program will freeze and the system operator is paged to address the outage by driving to the data center and jiggling the mouse
- void* p
- unsigned long n
- unsigned int f
- unsigned long n
- long
f
is invalid
n
bytes at p
aren't valid memory
getresgid
Gets real, effective, and "saved" group ids.
- unsigned int* real
- receives real user id, or null to do nothing
- unsigned int* effective
- receives effective user id, or null to do nothing
- unsigned int* saved
- receives saved user id, or null to do nothing
- int
- 0 on success or -1 w/ errno
getresuid
Gets real, effective, and "saved" user ids.
- unsigned int* real
- receives real user id, or null to do nothing
- unsigned int* effective
- receives effective user id, or null to do nothing
- unsigned int* saved
- receives saved user id, or null to do nothing
- int
- 0 on success or -1 w/ errno
getrlimit
Gets resource limit for current process.
- int resource
- can be RLIMIT_{CPU,FSIZE,DATA,STACK,CORE,RSS,etc.}
- struct rlimit* rlim
- receives result, modified only on success
- int
- 0 on success or -1 w/ errno
getrusage
Returns resource usage statistics.
- int who
- can be RUSAGE_{SELF,CHILDREN,THREAD}
- struct rusage* usage
- int
- 0 on success, or -1 w/ errno
GetSiCodeName
Returns symbolic name for siginfo::si_code value.
- int sig
- int si_code
- const char*
getsid
Creates session and sets the process group id.
- int pid
- int
getsockname
Returns details about network interface kernel granted socket.
- int fd
- struct sa* out_addr
- unsigned int* inout_addrsize
- struct sa* out_addr
- int
- 0 on success or -1 w/ errno
getsockopt
Retrieves socket setting.
- int fd
- int level
- can be SOL_SOCKET, IPPROTO_TCP, etc.
- int optname
- can be SO_{REUSE{PORT,ADDR},KEEPALIVE,etc.} etc.
- void* out_opt_optval
- unsigned int* out_optlen
- int
- 0 on success, or -1 w/ errno
out_optlen
is invalid somehow
fd
is valid but not a socket
fd
isn't valid
GetSymbolTable
Returns symbol table singleton.
This uses multiple strategies to find the symbol table. The first strategy, depends on whether or not the following is linked:
__static_yoink("__zipos_get");In that case, the symbol table may be read from
/zip/.symtab
which
is generated by o//tool/build/symtab.com
. The second strategy is to
look for the concomitant .com.dbg
executable, which may very well
be the one currently executing, or it could be placed in the same
folder as your .com
binary, or lastly, it could be explicitly
specified via the COMDBG
environment variable.
Function tracing is disabled throughout the duration of this call. Backtraces and other core runtime functionality depend on this.
- struct SymbolTable*
- symbol table, or NULL if not found
gettid
Returns current thread id.
On Linux, and Linux only, this is guaranteed to be equal to getpid() if this is the main thread. On NetBSD, gettid() for the main thread is always 1.
- int
- thread id greater than zero or -1 w/ errno
gettimeofday
Returns system wall time in microseconds, e.g.
int64_t t; char p[20]; struct tm tm; struct timeval tv; gettimeofday(&tv, 0); t = tv.tv_sec; gmtime_r(&t, &tm); iso8601(p, &tm); printf("%s\n", p);
- struct it_value* tv
- points to timeval that receives result if non-NULL
- struct timezone* tz
- receives UTC timezone if non-NULL
- int
tv
or tz
isn't valid memory
__gettimeofday_get
Returns pointer to fastest gettimeofday().
- _Bool* opt_out_isfast
- struct ad(*)()
getuid
Returns real user id of process.
This never fails. On Windows, which doesn't really have this concept, we return a deterministic value that's likely to work.
- unsigned int
- user id (always successful)
getwchar
Reads UTF-8 character from stream.
- unsigned int
- wide character or -1 on EOF or error
getwchar_unlocked
Reads UTF-8 character from stream.
- unsigned int
- wide character or -1 on EOF or error
getx86processormodel
Identifies microarchitecture of host processor.
- short key
- can be kX86ProcessorModelKey for host info
- struct X86ProcessorModel*
GetZipCdirComment
Returns comment of zip central directory.
- const unsigned char* eocd
- void*
GetZipCdirCommentSize
Returns comment of zip central directory.
- const unsigned char* eocd
- unsigned long
GetZipCdirOffset
Returns offset of zip central directory.
- const unsigned char* eocd
- unsigned long
GetZipCdirRecords
Returns number of records in zip central directory.
- const unsigned char* eocd
- unsigned long
GetZipCdirSize
Returns size of zip central directory.
- const unsigned char* eocd
- unsigned long
GetZipCfileCompressedSize
Returns compressed size in bytes from zip central directory header.
- const unsigned char* z
- unsigned long
GetZipCfileMode
Returns st_mode from ZIP central directory record.
- const unsigned char* p
- int
GetZipCfileOffset
Returns offset of local file header.
- const unsigned char* z
- unsigned long
GetZipCfileTimestamps
Extracts modified/access/creation timestamps from zip entry.
- const unsigned char* cf
- is pointer to central directory header for file
- ANONYMOUS-STRUCT* mtim
- optionally receives last modified timestamp
- ANONYMOUS-STRUCT* atim
- optionally receives modified timestamp
- ANONYMOUS-STRUCT* ctim
- optionally receives creation timestamp
- int gmtoff
- is seconds adjustment for legacy dos timestamps
- void
GetZipCfileUncompressedSize
Returns uncompressed size in bytes from zip central directory header.
- const unsigned char* z
- unsigned long
GetZipEocd
Locates End Of Central Directory record in ZIP file.
The ZIP spec says this header can be anywhere in the last 64kb. We search it backwards for the ZIP-64 "PKโ โข" magic number. If that's not found, then we search again for the original "PKโฃโ " magnum. The caller needs to check the first four bytes of the returned value to determine whether to use ZIP_CDIR_xxx() or ZIP_CDIR64_xxx() macros.
- void* f
- points to file memory
- unsigned long n
- is byte size of file
- int* e
- may receive error code when null is returned
- void*
- pointer to EOCD64 or EOCD, otherwise null
GetZipLfileCompressedSize
Returns compressed size in bytes from zip local file header.
- const unsigned char* z
- unsigned long
GetZipLfileUncompressedSize
Returns uncompressed size in bytes from zip local file header.
- const unsigned char* z
- unsigned long
glob
Finds pathnames matching pattern.
For example:
glob_t g = {.gl_offs = 2}; glob("*.*", GLOB_DOOFFS, NULL, &g); glob("../.*", GLOB_DOOFFS | GLOB_APPEND, NULL, &g); g.gl_pathv[0] = "ls"; g.gl_pathv[1] = "-l"; execvp("ls", &g.gl_pathv[0]); globfree(g);
- const char* pat
- can have star wildcard see fnmatch()
- int flags
- int(*)() errfunc
- struct glob_t* g
- int(*)() errfunc
- will receive matching entries and needs globfree()
- int
- 0 on success or GLOB_NOMATCH, GLOB_NOSPACE on OOM, or GLOB_ABORTED on read error
GoodSocket
Returns new socket with modern goodness enabled.
- int family
- int type
- int protocol
- _Bool isserver
- struct __tv* timeout
- int type
- int
grantpt
Grants access to subordinate pseudoteletypewriter.
- int fd
- int
- 0 on success, or -1 w/ errno
gzbuffer
Sets internal buffer size used by this library's functions. The default buffer size is 8192 bytes. This function must be called after gzopen() or gzdopen(), and before any other calls that read or write the file. The buffer memory allocation is always deferred to the first read or write. Three times that size in buffer space is allocated. A larger buffer size of, for example, 64K or 128K bytes will noticeably increase the speed of decompression (reading).
The new buffer size also affects the maximum length for gzprintf().
- int
- Z_OK on success, or -1 on failure, such as being called too late.
gzclearerr
Clears the error and end-of-file flags for file. This is analogous to the clearerr() function in stdio. This is useful for continuing to read a gzip file that is being written concurrently.
- void
gzclose
Flushes all pending output if necessary, closes the compressed file and deallocates the (de)compression state. Note that once file is closed, you cannot call gzerror with file, since its structures have been deallocated. gzclose must not be called more than once on the same file, just as free must not be called more than once on the same allocation.
- int
- Z_STREAM_ERROR if file is not valid, Z_ERRNO on a file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the last read ended in the middle of a gzip stream, or Z_OK on success.
gzclose_r
Same as gzclose(), but gzclose_r() is only for use when reading, and gzclose_w() is only for use when writing or appending. The advantage to using these instead of gzclose() is that they avoid linking in zlib compression or decompression code that is not used when only reading or only writing respectively. If gzclose() is used, then both compression and decompression code will be included the application when linking to a static zlib library.
- int
gzdirect
Returns true (1) if file is being copied directly while reading, or false (0) if file is a gzip stream being decompressed.
If the input file is empty, gzdirect() will return true, since the input does not contain a gzip stream.
If gzdirect() is used immediately after gzopen() or gzdopen() it will cause buffers to be allocated to allow reading the file to determine if it is a gzip file. Therefore if gzbuffer() is used, it should be called before gzdirect().
When writing, gzdirect() returns true (1) if transparent writing was requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: gzdirect() is not needed when writing. Transparent writing must be explicitly requested, so the application already knows the answer. When linking statically, using gzdirect() will include all of the zlib code for gzip file reading and decompression, which may not be desired.)
- int
gzdopen
Associates gzFile with the file descriptor.
File descriptors are obtained from calls like open, dup, creat, pipe or fileno (if the file has been previously opened with fopen). The mode parameter is as in gzopen.
The next call of gzclose on the returned gzFile will also close the file descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, mode);. The duplicated descriptor should be saved to avoid a leak, since gzdopen does not close fd if it fails. If you are using fileno() to get the file descriptor from a FILE *, then you will have to use dup() to avoid double-close()ing the file descriptor. Both gzclose() and fclose() will close the associated file descriptor, so they need to have different file descriptors.
- struct gzFile_s*
- Z_OK if there was insufficient memory to allocate the gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided), or if fd is -1. The file descriptor is not used until the next gz* read, write, seek, or close operation, so gzdopen will not detect if fd is invalid (unless fd is -1).
gzeof
Returns true (1) if the end-of-file indicator has been set while reading, false (0) otherwise. Note that the end-of-file indicator is set only if the read tried to go past the end of the input, but came up short. Therefore, just like feof(), gzeof() may return false even if there is no more data to read, in the event that the last read request was for the exact number of bytes remaining in the input file. This will happen if the input file size is an exact multiple of the buffer size.
If gzeof() returns true, then the read functions will return no more data, unless the end-of-file indicator is reset by gzclearerr() and the input file has grown since the previous end of file was detected.
- int
gzerror
Returns the error message for the last error which occurred on the given compressed file. errnum is set to zlib error number. If an error occurred in the file system and not in the compression library, errnum is set to Z_ERRNO and the application may consult errno to get the exact error code.
The application must not modify the returned string. Future calls to this function may invalidate the previously returned string. If file is closed, then the string previously returned by gzerror will no longer be available.
gzerror() should be used to distinguish errors from end-of-file for those functions above that do not distinguish those cases in their return values.
- const char*
gzflush
Flushes all pending output into the compressed file. The parameter flush is as in the deflate() function. The return value is the zlib error number (see function gzerror below). gzflush is only permitted when writing.
If the flush parameter is Z_FINISH, the remaining data is written and the gzip stream is completed in the output. If gzwrite() is called again, a new gzip stream will be started in the output. gzread() is able to read such concatenated gzip streams.
gzflush should be called only when strictly necessary because it will degrade compression if called too often.
- int
gzfread
Read up to nitems items of size size from file to buf, otherwise operating as gzread() does. This duplicates the interface of stdio's fread(), with size_t request and return types. If the library defines size_t, then size_t is identical to size_t. If not, then size_t is an unsigned integer type that can contain a pointer.
gzfread() returns the number of full items read of size size, or zero if the end of the file was reached and a full item could not be read, or if there was an error. gzerror() must be consulted if zero is returned in order to determine if there was an error. If the multiplication of size and nitems overflows, i.e. the product does not fit in a size_t, then nothing is read, zero is returned, and the error state is set to Z_STREAM_ERROR.
In the event that the end of file is reached and only a partial item is available at the end, i.e. the remaining uncompressed data length is not a multiple of size, then the final partial item is nevetheless read into buf and the end-of-file flag is set. The length of the partial item read is not provided, but could be inferred from the result of gztell(). This behavior is the same as the behavior of fread() implementations in common libraries, but it prevents the direct use of gzfread() to read a concurrently written file, reseting and retrying on end-of-file, when size is not 1.
- unsigned long
gzfwrite
Writes nitems items of size size from buf to file, duplicating the interface of stdio's fwrite(), with size_t request and return types. If the library defines size_t, then size_t is identical to size_t. If not, then size_t is an unsigned integer type that can contain a pointer.
gzfwrite() returns the number of full items written of size size, or zero if there was an error. If the multiplication of size and nitems overflows, i.e. the product does not fit in a size_t, then nothing is written, zero is returned, and the error state is set to Z_STREAM_ERROR.
- unsigned long
gzgetc
Reads one byte from the compressed file. gzgetc returns this byte or -1 in case of end of file or error. This is implemented as a macro for speed. As such, it does not do all of the checking the other functions do. I.e. it does not check to see if file is NULL, nor whether the structure file points to has been clobbered or not.
- int
gzgets
Reads bytes from the compressed file until len-1 characters are read, or a newline character is read and transferred to buf, or an end-of-file condition is encountered. If any characters are read or if len == 1, the string is terminated with a null character. If no characters are read due to an end-of-file or len < 1, then the buffer is left untouched.
- char*
- buf which is a null-terminated string, or it returns NULL for end-of-file or in case of error. If there was an error, the contents at buf are indeterminate.
gzoffset
Returns current offset in the file being read or written. This offset includes the count of bytes that precede the gzip stream, for example when appending or when using gzdopen() for reading. When reading, the offset does not include as yet unused buffered input. This information can be used for a progress indicator. On error, gzoffset() returns -1.
- long
gzopen
Opens a gzip (.gz) file for reading or writing.
The mode parameter is as in fopen ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression as in "wb9F". (See the description of deflateInit2 for more information about the strategy parameter.) 'T' will request transparent writing or appending with no compression and not using the gzip format.
"a" can be used instead of "w" to request that the gzip stream that will be written be appended to the file. "+" will result in an error, since reading and writing to the same gzip file is not supported. The addition of "x" when writing will create the file exclusively, which fails if the file already exists. On systems that support it, the addition of "e" when reading or writing will set the flag to close the file on an execve() call.
These functions, as well as gzip, will read and decode a sequence of gzip streams in a file. The append function of gzopen() can be used to create such a file. (Also see gzflush() for another way to do this.) When appending, gzopen does not test whether the file begins with a gzip stream, nor does it look for the end of the gzip streams to begin appending. gzopen will simply append a gzip stream to the existing file.
gzopen can be used to read a file which is not in gzip format; in this case gzread will directly read from the file without decompression. When reading, this will be detected automatically by looking for the magic two- byte gzip header.
- struct gzFile_s*
- Z_OK if the file could not be opened, if there was insufficient memory to allocate the gzFile state, or if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). errno can be checked to determine if the reason gzopen failed was that the file could not be opened.
gzprintf
Converts, formats, and writes the arguments to the compressed file under control of the format string, as in fprintf. gzprintf returns the number of uncompressed bytes actually written, or a negative zlib error code in case of error. The number of uncompressed bytes written is limited to 8191, or one less than the buffer size given to gzbuffer(). The caller should assure that this limit is not exceeded. If it is exceeded, then gzprintf() will return an error (0) with nothing written. In this case, there may also be a buffer overflow with unpredictable consequences, which is possible only if zlib was compiled with the insecure functions sprintf() or vsprintf() because the secure snprintf() or vsnprintf() functions were not available. This can be determined using zlibCompileFlags().
- ...
- int
gzputc
Writes character converted to an unsigned char into compressed file.
- int
- value that was written, or -1 on error
gzputs
Writes the given null-terminated string to the compressed file, excluding the terminating null character.
- int
- Z_OK number of characters written, or -1 in case of error.
gzread
Reads given number of uncompressed bytes from the compressed file. If the input file is not in gzip format, gzread copies the given number of bytes into the buffer directly from the file.
After reaching the end of a gzip stream in the input, gzread will continue to read, looking for another gzip stream. Any number of gzip streams may be concatenated in the input file, and will all be decompressed by gzread(). If something other than a gzip stream is encountered after a gzip stream, that remaining trailing garbage is ignored (and no error is returned).
gzread can be used to read a gzip file that is being concurrently written. Upon reaching the end of the input, gzread will return with the available data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then gzclearerr can be used to clear the end of file indicator in order to permit gzread to be tried again. Z_OK indicates that a gzip stream was completed on the last gzread. Z_BUF_ERROR indicates that the input file ended in the middle of a gzip stream. Note that gzread does not return -1 in the event of an incomplete gzip stream. This error is deferred until gzclose(), which will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip stream. Alternatively, gzerror can be used before gzclose to detect this case.
- int
- Z_OK number of uncompressed bytes actually read, less than len for end of file, or -1 for error. If len is too large to fit in an int, then nothing is read, -1 is returned, and the error state is set to Z_STREAM_ERROR.
gzrewind
Rewinds file.
This function is supported only for reading.
- int
gzseek
Sets starting position for the next gzread or gzwrite on the given compressed file. The offset represents a number of bytes in the uncompressed data stream. The whence parameter is defined as in lseek(2); the value SEEK_END is not supported.
If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position.
- long
- resulting offset location as measured in bytes from the beginning of the uncompressed stream, or -1 in case of error, in particular if the file is opened for writing and the new starting position would be before the current position.
gzsetparams
Dynamically update the compression level or strategy. See the description of deflateInit2 for the meaning of these parameters. Previously provided data is flushed before the parameter change.
- int
- Z_OK if success, Z_STREAM_ERROR if the file was not opened for writing, Z_ERRNO if there is an error writing the flushed data, or Z_MEM_ERROR if there is a memory allocation error.
gztell
Returns starting position for the next gzread or gzwrite on the given compressed file. This position represents a number of bytes in the uncompressed data stream, and is zero when starting, even if appending or reading a gzip stream from the middle of a file using gzdopen().
- long
gzungetc
Pushes one character back onto the stream to be read as the first character on the next read. At least one character of push-back is allowed. gzungetc() returns the character pushed, or -1 on failure. gzungetc() will fail if c is -1, and may fail if a character has been pushed but not read yet. If gzungetc is used immediately after gzopen or gzdopen, at least the output buffer size of pushed characters is allowed. (See gzbuffer above.) The pushed character will be discarded if the stream is repositioned with gzseek() or gzrewind().
- int
gzwrite
Writes given number of uncompressed bytes into the compressed file. gzwrite returns the number of uncompressed bytes written or 0 in case of error.
- int
h_errno
Error number global for gethostbyname*(), gethostbyaddr*(), etc.
- int
HasControlCodes
Returns true if C0 or C1 control codes are present
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- int f
- can have kControlWs, kControlC0, kControlC1 to forbid
- long
- index of first forbidden character or -1
HeaderHas
Returns true if standard header has substring.
- struct HttpMessage* m
- is message parsed by ParseHttpMessage
- const char* b
- is buffer that ParseHttpMessage parsed
- int h
- is known header, e.g. kHttpAcceptEncoding
- const char* s
- should not contain comma
- unsigned long n
- is byte length of s where -1 implies strlen
- _Bool
- true if substring present
heapsort
Sorts array.
Runs in O (N lg N), both average and worst. While heapsort is faster than the worst case of quicksort, the BSD quicksort does median selection so that the chance of finding a data set that will trigger the worst case is nonexistent. Heapsort's only advantage over quicksort is that it requires little additional memory.
- void* vbase
- is base of array
- unsigned long nmemb
- is item count
- unsigned long size
- is item width
- int(*)() compar
- is a callback returning <0, 0, or >0
- int
heapsort_r
Sorts array w/ optional callback argument.
- void* vbase
- is base of array
- unsigned long nmemb
- is item count
- unsigned long size
- is item width
- int(*)() compar
- is a callback returning <0, 0, or >0
- void* z
- will optionally be passed as the third argument to cmp
- int
herror
Prints h_errno
description to stderr.
- const char* s
- void
hexpcpy
Turns data into lowercase hex.
This routine always writes a nul terminator, even if n
is zero.
There's no failure condition for this function.
- char* s
- must have
n*2+1
bytes - void* p
- must have
n
bytes - unsigned long n
- is byte length of p
- char*
- pointer to nul byte in
s
hextoint
Converts ASCII hexadecimal character to integer case-insensitively.
- int c
- int
- integer or 0 if c โ [0-9A-Fa-f]
HighwayHash64
Computes Highway Hash.
highwayhash64 n=0 121 nanoseconds highwayhash64 n=8 16 ns/byte 59,865 kb/s highwayhash64 n=31 4 ns/byte 222 mb/s highwayhash64 n=32 3 ns/byte 248 mb/s highwayhash64 n=63 2 ns/byte 387 mb/s highwayhash64 n=64 2 ns/byte 422 mb/s highwayhash64 n=128 1 ns/byte 644 mb/s highwayhash64 n=256 1 ns/byte 875 mb/s highwayhash64 n=22851 721 ps/byte 1,354 mb/s
- void* data
- unsigned long size
- const unsigned long* key
- unsigned long size
- unsigned long
__hilbert
Generates Hilbert space-filling curve.
- long n
- long y
- long x
- long y
- long
__hook
Rewrites code in memory to hook function calls.
On x86_64 you need the compiler flag:
-fpatchable-function-entry=11,9On Aarch64 you need the compiler flag:
-fpatchable-function-entry=7,6This function can currently only be called once.
- void* dest
- is the address of the target function, which all hookable functions shall be reprogrammed to call from their epilogues; and must be sufficiently close in memory to the the program image, in order to meet ISA displacement requirements
- struct SymbolTable* st
- can be obtained using
GetSymbolTable()
- int
hstrerror
Turns h_errno
value into string.
- int err
- const char*
iconv
- void* cd
- char** in
- unsigned long* inb
- char** out
- unsigned long* outb
- char** in
- unsigned long
IndentLines
Inserts spaces before lines.
- const char* p
- is input value
- unsigned long n
- if -1 implies strlen
- unsigned long* z
- if non-NULL receives output length
- unsigned long j
- is number of spaces to use
- char*
- allocated NUL-terminated buffer, or NULL w/ errno
inet_addr
Converts dotted IPv4 address string to network order binary.
- const char* s
- unsigned int
inet_aton
Converts dotted IPv4 address string to network order binary.
- const char* s0
- ANONYMOUS-STRUCT* dest
- int
inet_ntop
Formats internet address to string.
- int af
- can be AF_INET or AF_INET6
- void* src
- is the binary-encoded address, e.g. &addr->sin_addr
- char* dst
- is the output string buffer
- unsigned int size
- needs to be 16+ for IPv4 and 46+ for IPv6
- const char*
- dst on success or NULL w/ errno
inet_pton
Converts internet address string to binary.
- int af
- can be AF_INET or AF_INET6
- const char* src
- is the ASCII-encoded address
- void* dst
- is where the binary-encoded net-order address goes
- int
- 1 on success, 0 on src malformed, or -1 w/ errno
__inflate
Decompresses raw deflate data.
This uses puff by default since it has a 2kb footprint. If zlib proper is linked, then we favor that instead, since it's faster.
- void* out
- unsigned long outsize
- needs to be known ahead of time by some other means
- void* in
- unsigned long insize
- int
- 0 on success or nonzero on failure
inflate
inflate decompresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush.
The detailed semantics are as follows. inflate performs one or both of the following actions:
- Decompress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), then next_in and avail_in are updated accordingly, and processing will resume at this point for the next call of inflate().
- Generate more output starting at next_out and update next_out and avail_out accordingly. inflate() provides as much output as possible, until there is no more input data or no more space in the output buffer (see below about the flush parameter).
The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much output as possible to the output buffer. Z_BLOCK requests that inflate() stop if and when it gets to the next deflate block boundary. When decoding the zlib or gzip format, this will cause inflate() to return immediately after the header and before the first block. When doing a raw inflate, inflate() will go ahead and process the first block, and will return when it gets to the end of that block, or when it runs out of data.
The Z_BLOCK option assists in appending to or combining deflate streams. To assist in this, on return inflate() always sets strm->data_type to the number of unused bits in the last byte taken from strm->next_in, plus 64 if inflate() is currently decoding the last block in the deflate stream, plus 128 if inflate() returned immediately after decoding an end-of-block code or decoding the complete header up to just before the first byte of the deflate stream. The end-of-block will not be indicated until all of the uncompressed data from that block has been written to strm->next_out. The number of unused bits may in general be greater than seven, except when bit 7 of data_type is set, in which case the number of unused bits will be less than eight. data_type is set as noted here every time inflate() returns for all flush options, and so can be used to determine the amount of currently consumed input in bits.
The Z_TREES option behaves as Z_BLOCK does, but it also returns when the end of each deflate block header is reached, before any actual data in that block is decoded. This allows the caller to determine the length of the deflate block header for later use in random access within a deflate block. 256 is added to the value of strm->data_type when inflate() returns immediately after reaching the end of the deflate block header.
inflate() should normally be called until it returns Z_STREAM_END or an error. However if all decompression is to be performed in a single step (a single call of inflate), the parameter flush should be set to Z_FINISH. In this case all pending input is processed and all pending output is flushed; avail_out must be large enough to hold all of the uncompressed data for the operation to complete. (The size of the uncompressed data may have been saved by the compressor for this purpose.) The use of Z_FINISH is not required to perform an inflation in one step. However it may be used to inform inflate that a faster approach can be used for the single inflate() call. Z_FINISH also informs inflate to not maintain a sliding window if the stream completes, which reduces inflate's memory footprint. If the stream does not complete, either because not all of the stream is provided or not enough output space is provided, then a sliding window will be allocated and inflate() can be called again to continue the operation as if Z_NO_FLUSH had been used.
In this implementation, inflate() always flushes as much output as possible to the output buffer, and always uses the faster approach on the first call. So the effects of the flush parameter in this implementation are on the return value of inflate() as noted below, when inflate() returns early when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of memory for a sliding window when Z_FINISH is used.
If a preset dictionary is needed after this call (see inflateSetDictionary below), inflate sets strm->adler to the Adler-32 checksum of the dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise it sets strm->adler to the Adler-32 checksum of all output produced so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described below. At the end of the stream, inflate() checks that its computed Adler-32 checksum is equal to that saved by the compressor and returns Z_STREAM_END only if the checksum is correct.
inflate() can decompress and check either zlib-wrapped or gzip-wrapped deflate data. The header type is detected automatically, if requested when initializing with inflateInit2(). Any information contained in the gzip header is not retained unless inflateGetHeader() is used. When processing gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output produced so far. The CRC-32 is checked against the gzip trailer, as is the uncompressed length, modulo 2^32.
- int
- Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if the end of the compressed data has been reached and all uncompressed output has been produced, Z_NEED_DICT if a preset dictionary is needed at this point, Z_DATA_ERROR if the input data was corrupted (input stream not conforming to the zlib format or incorrect check value, in which case strm->msg points to a string with a more specific error), Z_STREAM_ERROR if the stream structure was inconsistent (for example next_in or next_out was Z_NULL, or the state was inadvertently written over by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if no progress was possible or if there was not enough room in the output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and inflate() can be called again with more input and more output space to continue decompressing. If Z_DATA_ERROR is returned, the application may then call inflateSync() to look for a good compression block if a partial recovery of the data is to be attempted.
inflateBack
inflateBack() does a raw inflate with a single call using a call-back interface for input and output. This is potentially more efficient than inflate() for file i/o applications, in that it avoids copying between the output and the sliding window by simply making the window itself the output buffer. inflate() can be faster on modern CPUs when used with large buffers. inflateBack() trusts the application to not change the output buffer passed by the output function, at least until inflateBack() returns.
inflateBackInit() must be called first to allocate the internal state and to initialize the state with the user-provided window buffer. inflateBack() may then be used multiple times to inflate a complete, raw deflate stream with each call. inflateBackEnd() is then called to free the allocated state.
A raw deflate stream is one with no zlib or gzip header or trailer. This routine would normally be used in a utility that reads zip or gzip files and writes out uncompressed files. The utility would decode the header and process the trailer on its own, hence this routine expects only the raw deflate stream to decompress. This is different from the default behavior of inflate(), which expects a zlib header and trailer around the deflate stream.
inflateBack() uses two subroutines supplied by the caller that are then called by inflateBack() for input and output. inflateBack() calls those routines until it reads a complete deflate stream and writes out all of the uncompressed data, or until it encounters an error. The function's parameters and return types are defined above in the in_func and out_func typedefs. inflateBack() will call in(in_desc, &buf) which should return the number of bytes of provided input, and a pointer to that input in buf. If there is no input available, in() must return zero -- buf is ignored in that case -- and inflateBack() will return a buffer error. inflateBack() will call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() should return zero on success, or non-zero on failure. If out() returns non-zero, inflateBack() will return with an error. Neither in() nor out() are permitted to change the contents of the window provided to inflateBackInit(), which is also the buffer that out() uses to write from. The length written by out() will be at most the window size. Any non-zero amount of input may be provided by in().
For convenience, inflateBack() can be provided input on the first call by setting strm->next_in and strm->avail_in. If that input is exhausted, then in() will be called. Therefore strm->next_in must be initialized before calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in must also be initialized, and then if strm->avail_in is not zero, input will initially be taken from strm->next_in[0 .. strm->avail_in - 1].
The in_desc and out_desc parameters of inflateBack() is passed as the first parameter of in() and out() respectively when they are called. These descriptors can be optionally used to pass any information that the caller- supplied in() and out() functions need to do their job.
On return, inflateBack() will set strm->next_in and strm->avail_in to pass back any unused input that was provided by the last in() call. The return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR if in() or out() returned an error, Z_DATA_ERROR if there was a format error in the deflate stream (in which case strm->msg is set to indicate the nature of the error), or Z_STREAM_ERROR if the stream was not properly initialized. In the case of Z_BUF_ERROR, an input or output error can be distinguished using strm->next_in which will be Z_NULL only if in() returned an error. If strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning non-zero. (in() will always be called before out(), so strm->next_in is assured to be defined if out() returns non-zero.) Note that inflateBack() cannot return Z_OK.
- int
inflateBackEnd
All memory allocated by inflateBackInit() is freed.
- int
- Z_OK on success, or Z_STREAM_ERROR if the stream state was inconsistent.
inflateBackInit
Initialize internal stream state for decompression using inflateBack() calls. The fields zalloc, zfree and opaque in strm must be initialized before the call. If zalloc and zfree are Z_NULL, then the default library- derived memory allocation routines are used. windowBits is the base two logarithm of the window size, in the range 8..15. window is a caller supplied buffer of that size. Except for special applications where it is assured that deflate was used with small window sizes, windowBits must be 15 and a 32K byte window must be supplied to be able to decompress general deflate streams.
See inflateBack() for the usage of these routines.
- int
- Z_OK on success, Z_STREAM_ERROR if any of the parameters are invalid, or Z_MEM_ERROR if the internal state could not be allocated.
inflateCopy
Sets the destination stream as a complete copy of the source stream.
This function can be useful when randomly accessing a large stream. The first pass through the stream can periodically record the inflate state, allowing restarting inflate at those points when randomly accessing the stream.
- int
- Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and destination.
inflateEnd
All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output.
- int
- Z_OK or Z_STREAM_ERROR if stream state inconsistent
inflateGetDictionary
Returns the sliding dictionary being maintained by inflate. dictLength is set to the number of bytes in the dictionary, and that many bytes are copied to dictionary. dictionary must have enough space, where 32768 bytes is always enough. If inflateGetDictionary() is called with dictionary equal to Z_NULL, then only the dictionary length is returned, and nothing is copied. Similary, if dictLength is Z_NULL, then it is not set.
- int
- Z_OK on success, or Z_STREAM_ERROR if the stream state is inconsistent.
inflateGetHeader
inflateGetHeader() requests that gzip header information be stored in the provided gz_header structure. inflateGetHeader() may be called after inflateInit2() or inflateReset(), and before the first call of inflate(). As inflate() processes the gzip stream, head->done is zero until the header is completed, at which time head->done is set to one. If a zlib stream is being decoded, then head->done is set to -1 to indicate that there will be no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be used to force inflate() to return immediately after header processing is complete and before any actual data is decompressed.
The text, time, xflags, and os fields are filled in with the gzip header contents. hcrc is set to true if there is a header CRC. (The header CRC was valid if done is set to one.) If extra is not Z_NULL, then extra_max contains the maximum number of bytes to write to extra. Once done is true, extra_len contains the actual extra field length, and extra contains the extra field, or that field truncated if extra_max is less than extra_len. If name is not Z_NULL, then up to name_max characters are written there, terminated with a zero unless the length is greater than name_max. If comment is not Z_NULL, then up to comm_max characters are written there, terminated with a zero unless the length is greater than comm_max. When any of extra, name, or comment are not Z_NULL and the respective field is not present in the header, then that field is set to Z_NULL to signal its absence. This allows the use of deflateSetHeader() with the returned structure to duplicate the header. However if those fields are set to allocated memory, then the application will need to save those pointers elsewhere so that they can be eventually freed.
If inflateGetHeader is not used, then the header information is simply discarded. The header is always checked for validity, including the header CRC if present. inflateReset() will reset the process to discard the header information. The application would need to call inflateGetHeader() again to retrieve the header from the next gzip stream.
- int
- Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent.
inflateInit
Initializes the internal stream state for decompression. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. In the current version of inflate, the provided input is not read or consumed. The allocation of a sliding window will be deferred to the first call of inflate (if the decompression does not complete on the first call). If zalloc and zfree are set to Z_NULL, inflateInit updates them to use default allocation functions.
- int
- Z_OK if success, Z_MEM_ERROR if there was not enough memory, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit does not perform any decompression. Actual decompression will be done by inflate(). So next_in, and avail_in, next_out, and avail_out are unused and unchanged. The current implementation of inflateInit() does not process any header information -- that is deferred until inflate() is called.
inflateInit2
This is another version of inflateInit with an extra parameter. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller.
The windowBits parameter is the base two logarithm of the maximum window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. The default value is 15 if inflateInit is used instead. windowBits must be greater than or equal to the windowBits value provided to deflateInit2() while compressing, or it must be equal to 15 if deflateInit2() was not used. If a compressed stream with a larger window size is given as input, inflate() will return with the error code Z_DATA_ERROR instead of trying to allocate a larger window.
windowBits can also be zero to request that inflate use the window size in the zlib header of the compressed stream.
windowBits can also be -8..-15 for raw inflate. In this case, -windowBits determines the window size. inflate() will then process raw deflate data, not looking for a zlib or gzip header, not generating a check value, and not looking for any check values for comparison at the end of the stream. This is for use with other formats that use the deflate compressed data format such as zip. Those formats provide their own check values. If a custom format is developed using the raw deflate format for compressed data, it is recommended that a check value such as an Adler-32 or a CRC-32 be applied to the uncompressed data as is done in the zlib, gzip, and zip formats. For most applications, the zlib format should be used as is. Note that comments above on the use in deflateInit2() applies to the magnitude of windowBits.
windowBits can also be greater than 15 for optional gzip decoding. Add 32 to windowBits to enable zlib and gzip decoding with automatic header detection, or add 16 to decode only the gzip format (the zlib format will return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see below), inflate() will not automatically decode concatenated gzip streams. inflate() will return Z_STREAM_END at the end of the gzip stream. The state would need to be reset to continue decoding a subsequent gzip stream.
- int
- Z_OK if success, Z_MEM_ERROR if there was not enough memory, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit2 does not perform any decompression apart from possibly reading the zlib header if present: actual decompression will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unused and unchanged.) The current implementation of inflateInit2() does not process any header information -- that is deferred until inflate() is called.
inflateMark
Returns two values, one in the lower 16 bits of the return value, and the other in the remaining upper bits, obtained by shifting the return value down 16 bits. If the upper value is -1 and the lower value is zero, then inflate() is currently decoding information outside of a block. If the upper value is -1 and the lower value is non-zero, then inflate is in the middle of a stored block, with the lower value equaling the number of bytes from the input remaining to copy. If the upper value is not -1, then it is the number of bits back from the current bit position in the input of the code (literal or length/distance pair) currently being processed. In that case the lower value is the number of bytes already emitted for that code.
A code is being processed if inflate is waiting for more input to complete decoding of the code, or if it has completed decoding but is waiting for more output space to write the literal or match data.
inflateMark() is used to mark locations in the input data for random access, which may be at bit positions, and to note those cases where the output of a code may span boundaries of random access blocks. The current location in the input stream can be determined from avail_in and data_type as noted in the description for the Z_BLOCK flush parameter for inflate.
- long
- the value noted above, or -65536 if the provided source stream state was inconsistent.
inflatePrime
This function inserts bits in the inflate input stream. The intent is that this function is used to start inflating at a bit position in the middle of a byte. The provided bits will be used before any bytes are used from next_in. This function should only be used with raw inflate, and should be used before the first inflate() call after inflateInit2() or inflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the input.
If bits is negative, then the input stream bit buffer is emptied. Then inflatePrime() can be called again to put bits in the buffer. This is used to clear out bits leftover after feeding inflate a block description prior to feeding inflate codes.
- int
- Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent.
inflateReset
This function is equivalent to inflateEnd followed by inflateInit, but does not free and reallocate the internal decompression state. The stream will keep attributes that may have been set by inflateInit2.
- int
- Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL).
inflateReset2
This function is the same as inflateReset, but it also permits changing the wrap and window size requests. The windowBits parameter is interpreted the same as it is for inflateInit2. If the window size is changed, then the memory allocated for the window is freed, and the window will be reallocated by inflate() if needed.
- int
- Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL), or if the windowBits parameter is invalid.
inflateSetDictionary
Initializes the decompression dictionary from the given uncompressed byte sequence. This function must be called immediately after a call of inflate, if that call returned Z_NEED_DICT. The dictionary chosen by the compressor can be determined from the Adler-32 value returned by that call of inflate. The compressor and decompressor must use exactly the same dictionary (see deflateSetDictionary). For raw inflate, this function can be called at any time to set the dictionary. If the provided dictionary is smaller than the window and there is already data in the window, then the provided dictionary will amend what's there. The application must insure that the dictionary that was used for compression is provided.
- int
- Z_OK if success, Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the expected one (incorrect Adler-32 value). inflateSetDictionary does not perform any decompression: this will be done by subsequent calls of inflate().
inflateSync
Skips invalid compressed data until a possible full flush point (see above for the description of deflate with Z_FULL_FLUSH) can be found, or until all available input is skipped. No output is provided.
inflateSync searches for a 00 00 FF FF pattern in the compressed data. All full flush points have this pattern, but not all occurrences of this pattern are full flush points.
- int
- Z_OK if a possible full flush point has been found, Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the success case, the application may save the current current value of total_in which indicates where valid compressed data was found. In the error case, the application may repeatedly call inflateSync, providing more input each time, until success or end of the input data.
_init
Decentralized function for process initialization.
Modules may inject cheap data structure initialization code into this function using the .init.start and .init.end macros. That code can use the LODS and STOS instructions to initialize memory that's restricted to read-only after initialization by PIRO.
This is fast, since the linker is able to roll-up initialization for large codebases comprised of many modules, into a perfectly linear order. It also enables a common pattern we use, which we call โReferencing Is Initializationโ (RII).
C/C++ code should favor using ordinary constructors, since under normal circumstances the compiler will clobber RDI and RSI which are granted special meanings within this function.
- r12
- is argc (still callee saved)
- r13
- is argv (still callee saved)
- r14
- is envp (still callee saved)
- r15
- is envp (still callee saved)
__init_bss_start
Decentralized section for unpacked data structures.
Data in this section becomes read-only after initialization.
__init_rodata_start
Decentralized section for packed data structures & initializers.
initstate
- unsigned int seed
- char* state
- unsigned long size
- char* state
- char*
int128toarray_radix10
Converts signed 128-bit integer to string.
- __int128 i
- char* a
- needs at least 41 bytes
- unsigned long
- bytes written w/o nul
_intsort
Tiny and reasonably fast sorting for ints.
- int* A
- unsigned long n
- void
__invert_memory_area
Identity maps an area of physical memory to its negative address.
- struct mman* mm
- unsigned long* pml4t
- unsigned long ps
- unsigned long size
- unsigned long pte_flags
- unsigned long* pml4t
- unsigned long*
ioctl
Performs special i/o operation on file descriptor.
- int fd
- unsigned long request
- can be any of:
FIONREAD
takes anint *
and returns how many bytes of input are available on a terminal or socket, waiting to be read. On Windows this currently won't work for console file descriptors.TIOCGWINSZ
populatesstruct winsize *
with the dimensions of your teletypewriter. It's an alias for tcgetwinsize().TIOCSWINSZ
with the dimensions of your teletypewriter tostruct winsize *
. It's an alias for tcsetwinsize().TIOCOUTQ
takes anint *
and returns the number of bytes in the terminal's output buffer. Only available on UNIX.TIOCSTI
takes aconst char *
and may be used to fake input to a tty. This API isn't available on OpenBSD. Only available on UNIX.TIOCNOTTY
takes anint tty_fd
arg and makes it the controlling terminal of the calling process, which should have called setsid() beforehand.TIOCNOTTY
to give up the controlling terminal. Only available on UNIX.TIOCNXCL
to give up exclusive mode on terminal. Only available on UNIX.SIOCGIFCONF
takes an struct ifconf object of a given size, whose arg isstruct ifconf *
. It implements the Linux style and modifies the following: - ifc_len: set it to the number of valid ifreq structuresrepresentingthe interfaces
- ifc_ifcu.ifcu_req: sets the name of the interface for eachinterface
The ifc_len is an input/output parameter: set it to the total size of the ifcu_buf (ifcu_req) buffer on input.SIOCGIFNETMASK
populates astruct ifconf *
record with the network interface mask. This data structure should be obtained by callingSIOCGIFCONF
.SIOCGIFBRDADDR
populates astruct ifconf *
record with the network broadcast addr. This data structure should be obtained by callingSIOCGIFCONF
.FIONBIO
isn't polyfilled; usefcntl(F_SETFL, O_NONBLOCK)
FIOCLEX
isn't polyfilled; usefcntl(F_SETFD, FD_CLOEXEC)
FIONCLEX
isn't polyfilled; usefcntl(F_SETFD, 0)
TCGETS
isn't polyfilled; use tcgetattr()TCSETS
isn't polyfilled; use tcsetattr()TCSETSW
isn't polyfilled; use tcsetattr()TCSETSF
isn't polyfilled; use tcsetattr()TCXONC
isn't polyfilled; use tcflow()TCSBRK
isn't polyfilled; use tcdrain()TCFLSH
isn't polyfilled; use tcflush()TIOCGPTN
isn't polyfilled; use ptsname()TIOCGSID
isn't polyfilled; use tcgetsid()TCSBRK
isn't polyfilled; use tcsendbreak()TCSBRK
isn't polyfilled; use tcsendbreak()TIOCSPGRP
isn't polyfilled; use tcsetpgrp()TIOCSPTLCK
isn't polyfilled; use unlockpt()
- ...
- int
__iovec2nt
Converts I/O vector from System Five to WIN32 ABI.
- struct ProviderSpecific* iovnt
- struct iovec* iov
- unsigned long iovlen
- struct iovec* iov
- unsigned long
- effective iovlen
is_cpp_mangled_gnu3
- const char* org
- _Bool
- Return 0 at false.
Test string heads with "_Z" or "_GLOBAL__I_".
_isabspath
Returns true if pathname is considered absolute.
/home/jart/foo.txt
is absoluteC:/Users/jart/foo.txt
is absolute on WindowsC:\Users\jart\foo.txt
is absolute on Windows\??\C:\Users\jart\foo.txt
is absolute on Windows\\.\C:\Users\jart\foo.txt
is absolute on Windows/Users/jart/foo.txt
is effectively absolute on Windows\Users\jart\foo.txt
is effectively absolute on Windows
- const char* path
- _Bool
IsAcceptableHost
Returns true if host seems legit.
This function may be called after ParseUrl() or ParseHost() has already handled things like percent encoding. There's currently no support for IPv6 and IPv7.
Here's examples of permitted inputs:
- ""
- 1.2.3.4
- 1.2.3.4.arpa
- localservice
- hello.example
- _hello.example
- -hello.example
- hi-there.example
- ::1
- 1.2.3
- 1.2.3.4.5
- .hi.example
- hi..example
- const char* s
- unsigned long n
- if -1 implies strlen
- _Bool
IsAcceptablePath
Returns true if path seems legit.
- The substring "//" is disallowed.
- We won't serve hidden files (segment starts with '.').
The only exception is
/.well-known/
. - We won't serve paths with segments equal to "." or "..".
- const char* data
- unsigned long size
- if -1 implies strlen
- _Bool
IsAcceptablePort
Returns true if port seems legit.
Here's examples of permitted inputs:
- ""
- 0
- 65535
- -1
- 65536
- https
- const char* s
- unsigned long n
- if -1 implies strlen
- _Bool
isalnum
Returns nonzero if c is lower, alpha, or digit.
- int c
- int
IsAnonymousIp
Returns true if IPv4 address is anonymous proxy provider.
- unsigned int x
- _Bool
IsApnicIp
Returns true if IPv4 address is managed by APNIC.
- unsigned int x
- _Bool
IsArinIp
Returns true if IPv4 address is managed by ARIN.
- unsigned int x
- _Bool
isatty
Tells if file descriptor is a terminal.
- int fd
- is file descriptor
- int
- 1 if is terminal, otherwise 0 w/ errno
ischardev
Returns true if file descriptor is backed by character i/o.
This function is equivalent to:
struct stat st; return stat(path, &st) != -1 && S_ISCHR(st.st_mode);Except faster and with fewer dependencies.
- int fd
- int
IsCloudflareIp
Returns true if x
is Cloudflare IPv4 address.
- unsigned int x
- _Bool
iscntrl
Returns nonzero if c is C0 ASCII control code or DEL.
- int c
- int
IsDebuggerPresent
Determines if gdb, strace, windbg, etc. is controlling process.
- _Bool force
- int
- non-zero if attached, otherwise 0
isdirectory
Returns true if file exists and is a directory.
This function is equivalent to:
struct stat st; return fstatat(AT_FDCWD, path, &st, AT_SYMLINK_NOFOLLOW) != -1 && S_ISDIR(st.st_mode);Except faster, with fewer dependencies, and less errno clobbering.
- const char* path
- _Bool
isdirectory_nt
Returns true if file exists and is a directory on Windows NT.
- const char* path
- _Bool
_isdirsep
Returns true if character is directory separator slash.
- int c
- _Bool
IsDodIp
Returns true if IP is owned by the U.S. Department of Defense.
- unsigned int x
- _Bool
IsElf64Binary
Returns true if elf
is a 64-bit elf executable.
- struct Elf64_Ehdr* elf
- points to the start of the executable image
- unsigned long mapsize
- is the number of bytes past
elf
we can access
- _Bool
- true if elf header looks legit
isexecutable
Returns true if file exists and is executable.
- const char* path
- _Bool
isgraph
Returns nonzero if c is printable ascii that isn't space.
- int c
- int
_isheap
Returns true if address isn't stack and was malloc'd or mmap'd.
- void* p
- _Bool
islower
Returns nonzero if c is lowercase alpha ascii character.
- int c
- int
IsMimeType
Returns true if content-type ๐ก has mime-type ๐ .
- const char* t
- unsigned long n
- const char* s
- unsigned long n
- _Bool
IsMulticastIp
Returns true if IPv4 address is used for multicast.
- unsigned int x
- _Bool
__iso8601
Converts timestamp to ISO-8601 formatted string.
For example:
char *GetZuluTime(void) { char *p; struct tm tm; struct timespec ts; static _Thread_local int64_t last; static _Thread_local char str[21]; clock_gettime(0, &ts); if (ts.tv_sec != last) { gmtime_r(&ts.tv_sec, &tm); last = ts.tv_sec; stpcpy(iso8601(str, &tm), "Z"); } return str; }Will return timestamps that look like:
2020-01-01T13:14:15ZThe generated timestamp is always exactly 19 characters long. It is also always nul terminated too.
This function defines no failure conditions. The results of passing timestamp values outside of the appropriate intervals is undefined.
- char* p
- is buffer with at least 20 bytes
- struct tm* tm
- has valid gmtime_r() or localtime_r() output
- char*
- pointer to nul terminator within
p
, cf. stpcpy()
__iso8601us
Converts timestamp to ISO-8601 formatted string.
For example:
char *GetTimestamp(void) { struct timespec ts; static _Thread_local struct tm tm; static _Thread_local int64_t last; static _Thread_local char str[27]; clock_gettime(0, &ts); if (ts.tv_sec != last) { localtime_r(&ts.tv_sec, &tm); last = ts.tv_sec; } iso8601us(str, &tm, ts.tv_nsec); return str; }Will return timestamps that look like:
2020-01-01T13:14:15.123456The generated timestamp is always exactly 26 characters long. It is also always nul terminated too.
This function defines no failure conditions. The results of passing timestamp, or nanosecond values outside their appropriate intervals is undefined.
This goes 19x faster than strftime().
iso8601 l: 21c 7ns iso8601us l: 39c 13ns strftime l: 779c 252ns
- char* p
- is buffer with at least 20 bytes
- struct tm* tm
- has valid gmtime_r() or localtime_r() output
- long ns
- is nanosecond value associated with timestamp
- char*
- pointer to nul terminator within
p
, cf. stpcpy()
isprint
Returns nonzero if c is printable ascii including space.
- int c
- int
IsPrivateIp
Returns true if IPv4 address is intended for private networks.
- unsigned int x
- _Bool
IsPublicIp
Returns true if IPv4 address is Globally Reachable.
We intentionally omit TEST-NET here which can be used to simulate public Internet traffic using non-Internet IPs.
- unsigned int x
- _Bool
- true 92.4499% of the time
ispunct
Returns nonzero if c โ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
- int c
- int
IsReasonablePath
Returns true if path doesn't contain "." or ".." segments.
- const char* data
- unsigned long size
- if -1 implies strlen
- _Bool
isregularfile
Returns true if file exists and is a regular file.
This function is equivalent to:
return fstatat(AT_FDCWD, path, &st, AT_SYMLINK_NOFOLLOW) != -1 && S_ISREG(st.st_mode);Except faster, with fewer dependencies, and less errno clobbering.
- const char* path
- _Bool
isregularfile_nt
Returns true if file exists and is a regular file on Windows NT.
- const char* path
- _Bool
IsRipeIp
Returns true if IPv4 address is managed by RIPE NCC.
- unsigned int x
- _Bool
issetugid
Determines if process is tainted.
This function returns 1 if process was launched as a result of an execve() call on a binary that had the setuid or setgid bits set. FreeBSD defines tainted as including processes that changed their effective user / group ids at some point.
- int
- always successful, 1 if yes, 0 if no
isspace
Returns nonzero if c is space, \t, \r, \n, \f, or \v.
- int c
- int
issymlink
Returns true if file exists and is a symbolic link.
This function is equivalent to:
struct stat st; return fstatat(AT_FDCWD, path, &st, AT_SYMLINK_NOFOLLOW) != -1 && S_ISLNK(st.st_mode);Except faster and with fewer dependencies.
- const char* path
- _Bool
issymlink_nt
Returns true if file exists and is a symbolic link on Windows NT.
- const char* path
- _Bool
IsTestnetIp
Returns true if IPv4 address is intended for documentation.
- unsigned int x
- _Bool
_istext
Returns true if buffer is most likely plaintext.
- void* data
- unsigned long size
- _Bool
isupper
Returns nonzero if c is uppercase alpha ascii character.
- int c
- int
_isutf8
Returns true if text is utf-8.
_isutf8 n=0 1 nanoseconds _isutf8 n=5 661 ps/byte 1,476 mb/s _isutf8 ascii n=22851 26 ps/byte 35 GB/s _isutf8 unicode n=3193 543 ps/byte 1,795 mb/sThis function considers all ASCII characters including NUL to be valid UTF-8. The conditions for something not being valid are:
- Incorrect sequencing of 0300 (FIRST) and 0200 (CONT) chars
- Thompson-Pike varint sequence not encodable as UTF-16
- Overlong UTF-8 encoding
- void* data
- unsigned long size
- if -1 implies strlen
- _Bool
IsValidCookieValue
Returns true if string is a valid cookie value (any ASCII excluding control char, whitespace, double quotes, comma, semicolon, and backslash).
- const char* s
- unsigned long n
- if -1 implies strlen
- _Bool
IsValidHttpToken
Returns true if string is ASCII without delimiters.
- const char* s
- unsigned long n
- if -1 implies strlen
- _Bool
iswalnum
Returns nonzero if c is lower, alpha, or digit.
- unsigned int c
- int
iswalpha
Returns nonzero if c is alphabetical.
- unsigned int c
- int
iswblank
Returns nonzero if c is space or tab.
- unsigned int c
- int
iswcntrl
Returns nonzero if c is C0 or C1 control code.
- unsigned int c
- int
iswctype
Returns nonzero if c has property.
- unsigned int c
- unsigned int t
- is number returned by wctype
- int
iswdigit
Returns nonzero if c is decimal digit.
- unsigned int c
- int
iswgraph
Returns nonzero if c is printable and not a space.
- unsigned int c
- int
iswlower
Returns nonzero if c is lowercase letter.
- unsigned int c
- int
__isworker
Indicates if current execution context is a worker task.
Setting this to true on things like the forked process of a web server is a good idea since it'll ask the C runtime to not pull magical stunts like attaching GDB to the process on crash.
- _Bool
iswprint
Returns nonzero if c is printable.
- unsigned int c
- int
iswpunct
Returns nonzero if c is punctuation mark.
- unsigned int c
- int
iswseparator
Returns nonzero if ๐ isn't alphanumeric.
Line reading interfaces generally define this operation as UNICODE characters that aren't in the letter category (Lu, Ll, Lt, Lm, Lo) and aren't in the number categorie (Nd, Nl, No). We also add a few other things like blocks and emoji (So).
- unsigned int c
- int
iswspace
Returns nonzero if c is space character.
We define this as invisible characters which move the cursor. That
means \t\r\n\f\v
and unicodes whose category begins with Z
but
not ogham since it's not invisible and non-breaking spaces neither
since they're not invisible to emacs users.
- unsigned int c
- int
iswupper
Returns nonzero if c is uppercase letter.
- unsigned int c
- int
iswxdigit
Returns nonzero if c is ascii hex digit.
- unsigned int c
- int
IsZipEocd32
Determines if ZIP EOCD record seems legit.
- const unsigned char* p
- unsigned long n
- unsigned long i
- unsigned long n
- int
IsZipEocd64
Returns kZipOk if zip64 end of central directory header seems legit.
- const unsigned char* p
- unsigned long n
- unsigned long i
- unsigned long n
- int
_jmpstack
Switches stack.
- rdi
- is new rsp, passed as malloc(size) + size
- rsi
- is function to call in new stack space
- rdx,rcx,r8,r9
- get passed as args to rsi
_join
Waits for thread created by _spawn() to terminate.
This will free your thread's stack and tls memory too.
- struct ths* th
- int
__kappendf
Appends formatted string to buffer w/ kprintf, e.g.
char *b = 0; kappendf(&b, "hello %d\n", 123); free(b);
- char** b
- const char* fmt
- ...
- const char* fmt
- long
- bytes appended or -1 if
ENOMEM
kCp437
ibm cp437 unicode table w/ string literal safety
โโโโโโโ โโโ โโโ โโโโโโโโโโ โโโโโโโโ โโโ โโโโโโโ โโ โโโโโโโโโโโโ โ โโโโโโโโโ โโโโโโโโโโโโ โโโ โโโ โโโ โโโโโโโโ โโโโโโโโโ โโ โโ โโโโโโโ โโโโโโโโโโ โ โโโโโโ โโโโโโโ โโโ โโ โโโ โโโโโ โโโโโโโ โโโโโโโโโ โโ โโโโโโโโโโ โโโโโโ โโโโโ โโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโ โ โโโโโ โโโโโโ โโ โโโโโโโโโโ โโโ โโโโโโโโ โโโโ โโโโโ โโโโโโโ โ โโโ โโโโโโโโโโโ โโโโโ โโโโโ โโโโโโโโโโโ โโโ โโโโโโ โโโโ โโโโโโ โโโ โโ โ โ โ โโโโ โโโโโโโ โโ โโ โ โ โโโโโโโโโโโโโโ โโ โ โ โโ โโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโโโ โโโ โโโโโโโโโโโโ โโโโโโโโโโโโ โโโ โโโ โโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโ โ โโ โโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโ โโโ โโโโ โโ โโโโโโโโโโโโโโโโโโโโโ โโโโ โโโโ โโโโโโโโโโโโ โโโโโ โ โโโโ โโโ โโโโโโโโโโโโโโโโโโโโ โโโโ โโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโ โโโโโโโโโ โโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโ โ โโโ โโโ โโโ โโโโโโโโ โโโ โโ โ โโโ โโโ โโโ โโโ โ โ โ โ โ โโ โ โโโ โ โ โ โโ โ โ โโโ โโโ โโโโโโ โโโ โ โ โ โ โ โโโ โ โ โโโ โโโ โโโ THERE WILL BE BLOCKS march 01 2017
kCpuids
Globally precomputed CPUID.
This module lets us check CPUID in 0.06ns rather than 51.00ns. If every piece of native software linked this module, then the world would be a much better place; since all the alternatives are quite toilsome.
kHttpRepeatable
Set of standard comma-separate HTTP headers that may span lines.
These headers may specified on multiple lines, e.g.
Allow: GET Allow: POSTIs the same as:
Allow: GET, POSTStandard headers that aren't part of this set will be overwritten in the event that they're specified multiple times. For example,
Content-Type: application/octet-stream Content-Type: text/plain; charset=utf-8Is the same as:
Content-Type: text/plain; charset=utf-8This set exists to optimize header lookups and parsing. The existence of standard headers that aren't in this set is an O(1) operation. The repeatable headers in this list require an O(1) operation if they are not present, otherwise the extended headers list needs to be crawled.
Please note non-standard headers exist, e.g. Cookie, that may span multiple lines, even though they're not comma-delimited. For those headers we simply don't add them to the perfect hash table.
- _Bool[93]
grep '[A-Z][a-z]*".*":"' rfc2616
grep ':.*#' rfc2616
kill
Sends signal to process.
The impact of this action can be terminating the process, or interrupting it to request something happen.
- int pid
- can be: >0 signals one process by id =0 signals all processes in current process group -1 signals all processes possible (except init) <-1 signals all processes in -pid process group
- int sig
- can be: >0 can be SIGINT, SIGTERM, SIGKILL, SIGUSR1, etc. =0 checks both if pid exists and we can signal it
- int
- 0 if something was accomplished, or -1 w/ errno
pid
couldn't be found
proc
promised
sig
is invalid or unsupported
kmalloc
Allocates permanent memory.
The code malloc() depends upon uses this function to allocate memory. The returned memory can't be freed, and leak detection is impossible. This function panics when memory isn't available.
Memory returned by this function is aligned on the word size, and as such, kmalloc() shouldn't be used for vector operations.
- unsigned long size
- void*
- zero-initialized memory on success, or null w/ errno
kNtSystemDirectory
RII constant holding 'C:/WINDOWS/SYSTEM32' directory.
kNtWindowsDirectory
RII constant holding 'C:/WINDOWS' directory.
kNtWsaData
Information about underlying Windows Sockets implementation.
Cosmopolitan automatically calls __yoink() on this symbol when its Berkeley Socket wrappers are linked. The latest version of Winsock was introduced alongside x64, so this should never fail.
- struct kNtWsaData
__kprintf
Privileged printf().
This function is intended for crash reporting. It's designed to be as unbreakable as possible, so that error messages can always be printed even when the rest of the runtime is broken. As such, it has continue on error semantics, doesn't support buffering between invocations and floating point is not supported. Output is also truncated if the line gets too long, but care is taken to preserve your newline characters. Your errno and GetLastError() state will not be clobbered, and ftrace and other runtime magic won't be invoked, since all the runtime magic depends on this function.
Directives:
%[FLAGS][WIDTH|*][.[PRECISION|*]][TYPE]SPECIFIERSpecifiers:
c
charo
octalb
binarys
stringt
symbolp
pointerd
decimaln
newlineu
unsignedr
carriagem
strerrorG
strsignalX
uppercaseT
timestampx
hexadecimalP
PID (or TID if TLS is enabled)
hhh
boolhh
char or cp437h
short or char16_tl
long or wchar_tll
long long
0
zero padding-
flip alignment!
bypass memory safety,
thousands grouping w/ comma'
thousands grouping w/ apostrophe_
thousands grouping w/ underscore+
plus leftpad if positive (aligns w/ negatives)#
represent value with literal syntax, e.g. 0x, 0b, quotes^
uppercasing w/ towupper() if linked, otherwise toupper()
%m
formats error (if strerror_wr if is linked)%m
formats errno number (if strerror_wr isn't linked)% m
formats error with leading space if errno isn't zero%lm
means favor WSAGetLastError() over GetLastError() if linked
%t
will work. You
can do that by calling GetSymbolTable()
. If that hasn't happened it
will print &hexnumber
instead.
- const char* fmt
- ...
- void
__ksnprintf
Privileged snprintf().
- char* b
- is buffer, and guaranteed a NUL-terminator if
n>0
- unsigned long n
- is number of bytes available in buffer
- const char* fmt
- ...
- unsigned long
- length of output excluding NUL, which may exceed
n
kStartTsc
Timestamp of process start.
- unsigned long
kTmpPath
RII constant holding temporary file directory.
The order of precedence is:
- $TMPDIR/
- GetTempPath()
- /tmp/
kTmpPath
won't be longer than PATH_MAX / 2
.
- char[1024]
__kvappendf
Appends formatted string to buffer.
This is an alternative to vappendf() that uses the kprintf() formatting facility. This has some advantages in terms of performance, code size, and memory safety. There's also disadvantages, such as lack of floating-point directives.
- char** b
- const char* f
- struct __va_list* v
- const char* f
- long
__kvprintf
Privileged vprintf.
- const char* fmt
- struct __va_list* v
- void
__kvsnprintf
Privileged vsnprintf().
- char* b
- is buffer, and guaranteed a NUL-terminator if
n>0
- unsigned long n
- is number of bytes available in buffer
- const char* fmt
- struct __va_list* v
- unsigned long
- length of output excluding NUL, which may exceed
n
kXedChipFeatures
Mapping of enum XedChip -> bitset<enum XedIsaSet>.
See related APIs, e.g. xed_isa_set_is_valid_for_chip().
This information can be reproduced by building Xed and running the C preprocessor on xed-chip-features-table.c (see xed-chips.txt) which turns several thousand lines of non-evolving code into fifty. For example, 0x2800000ul was calculated as: 1UL<<(XED_ISA_SET_I86-64) | 1UL<<(XED_ISA_SET_LAHF-64).
- const unsigned long[3][53]
kXedErrorNames
Xed error code names.
puts(IndexDoubleNulString(kXedErrorNames, xedd->op.error));
- const char[338]
l64a
Converts 32-bit integer to base64, the posix way.
- long x
- char*
landlock_add_rule
Adds new rule to Landlock ruleset.
- int fd
- enum rule_type rule_type
- void* rule_attr
- unsigned int flags
- enum rule_type rule_type
- int
fd
is not a file descriptor for current thread, or
member of rule_attr
is not a file descriptor as expected
fd
is not a ruleset file descriptor, or a member
of rule_attr
is not the expected file descriptor type
fd
has no write access to the underlying ruleset
rule_attr
inconsistency
landlock_create_ruleset
Create new Landlock filesystem sandboxing ruleset.
You may also use this function to query the current ABI version:
landlock_create_ruleset(0, 0, LANDLOCK_CREATE_RULESET_VERSION);
- struct landlock_ruleset_attr* attr
- unsigned long size
- unsigned int flags
- unsigned long size
- int
- close exec file descriptor for new ruleset
landlock_restrict_self
Enforces Landlock ruleset on calling thread.
- int fd
- unsigned int flags
- int
fd
isn't file descriptor for the current thread
fd
is not a ruleset file descriptor
fd
has no read access to underlying ruleset, or
current thread is not running with no_new_privs, or it doesnโt
have CAP_SYS_ADMIN in its namespace
lchmod
Changes mode of pathname, w/o dereferencing symlinks.
- const char* pathname
- unsigned int mode
- int
- 0 on success, or -1 w/ errno
lchown
Changes owner and/or group of pathname, w/o dereferencing symlinks.
- const char* pathname
- unsigned int uid
- is user id, or -1u to not change
- unsigned int gid
- is group id, or -1u to not change
- int
- 0 on success, or -1 w/ errno
ldiv
Divides integers yielding numerator and denominator.
- long num
- long den
- struct retval
__LengthInt64
Returns len(str(x))
where x is a signed 64-bit integer.
- long x
- unsigned int
__LengthInt64Thousands
Returns decimal string length of int64 w/ thousands separators.
- long x
- unsigned int
__LengthUint64
Returns len(str(x))
where x is an unsigned 64-bit integer.
- unsigned long x
- unsigned int
__LengthUint64Thousands
Returns decimal string length of uint64 w/ thousands separators.
- unsigned long x
- unsigned int
lgammaf_r
Returns natural logarithm of absolute value of Gamma function.
- float x
- int* signgamp
- float
link
Creates hard filesystem link.
This allows two names to point to the same file data on disk. They can only be differentiated by examining the inode number.
- const char* existingpath
- const char* newpath
- int
- 0 on success, or -1 w/ errno
linkat
Creates hard filesystem link.
This allows two names to point to the same file data on disk. They can only be differentiated by examining the inode number.
- int olddirfd
- const char* oldpath
- int newdirfd
- const char* newpath
- int flags
- const char* oldpath
- can have AT_EMPTY_PATH or AT_SYMLINK_NOFOLLOW
- int
- 0 on success, or -1 w/ errno
listen
Asks system to accept incoming connections on socket.
The socket() and bind() functions need to be called beforehand. Once this function is called, accept() is used to wait for connections. Using this on connectionless sockets will allow it to receive packets on a designated address.
- int fd
- int backlog
- <= SOMAXCONN
- int
- 0 on success or -1 w/ errno
LoadZipArgs
Replaces argument list with /zip/.args
contents if it exists.
Your .args
file should have one argument per line.
If the special argument ...
is *not* encountered, then the
replacement will only happen if *no* CLI args are specified.
If the special argument ...
*is* encountered, then it'll be
replaced with whatever CLI args were specified by the user.
- int* argc
- char*** argv
- int
- 0 on success, or -1 if not found w/o errno clobber
LockFileEx
Locks file on the New Technology.
- long hFile
- unsigned int dwFlags
- unsigned int dwReserved
- unsigned int nNumberOfBytesToLockLow
- unsigned int nNumberOfBytesToLockHigh
- struct inout_lpOverlapped* lpOverlapped
- unsigned int dwFlags
- int
- handle, or -1 on failure
login_tty
Prepares terminal for login.
- int fd
- int
- 0 on success, or -1 w/ errno
LogKprintfToFile
Redirects kprintf(), --strace
, etc. output to file.
- const char* path
- is filename to append to; if null is specified then this file logging facility will be disabled; when the empty string is specified, then the default path shall be used
- int
- 0 on success, or -1 w/ errno
longerjmp
Loads previously saved processor state.
- rdi
- points to the jmp_buf
- rsi
- is returned by setlongerjmp() invocation
longjmp
Loads previously saved processor state.
- rdi
- points to the jmp_buf
- esi
- is returned by setjmp() invocation (coerced nonzero)
_longjmp
Loads previously saved processor state.
- rdi
- points to the jmp_buf
- esi
- is returned by setjmp() invocation (coerced nonzero)
_longsort
Sorting algorithm for longs that doesn't take long.
"What disorder is this? Give me my long sort!" -Lord Capulet
- long* A
- unsigned long n
- void
LookupProtoByName
Opens and searches /etc/protocols to find number for a given name.
- const char* protoname
- is a NULL-terminated string
- char* buf
- is a buffer to store the official name of the protocol
- unsigned long bufsize
- is the size of buf
- const char* filepath
- is the location of protocols file
(if NULL, uses /etc/protocols)
- int
- -1 on error, or
positive protocol number
LookupProtoByNumber
Opens and searches /etc/protocols to find name for a given number.
The format of /etc/protocols is like this:
# comment # NAME PROTOCOL ALIASES ip 0 IP icmp 1 ICMP
- const int protonum
- is the protocol number
- char* buf
- is a buffer to store the official name of the protocol
- unsigned long bufsize
- is the size of buf
- const char* path
- is the location of the protocols file, which may be NULL to use the system-wide default
- int
- 0 on success, -1 on error
LookupServicesByName
Opens and searches /etc/services to find port for a given name.
- const char* servname
- is a NULL-terminated string
- char* servproto
- is a NULL-terminated string (eg "tcp", "udp")
(if servproto is an empty string, if is filled with the first matching protocol)
- unsigned long servprotolen
- the size of servproto
- char* buf
- is a buffer to store the official name of the service
(if NULL, the official name is not stored)
- unsigned long bufsize
- is the size of buf
- const char* path
- is the location of services file
(if NULL, uses /etc/services)
- int
- -1 on error, or positive port number
LookupServicesByPort
Opens and searches /etc/services to find name for a given port.
The format of /etc/services is like this:
# comment # NAME PORT/PROTOCOL ALIASES ftp 21/tcp fsp 21/udp fspd ssh 22/tcp
- const int servport
- is the port number
- char* servproto
- is a NULL-terminated string (eg "tcp", "udp")
(if servproto is an empty string, if is filled with the first matching protocol)
- unsigned long servprotolen
- the size of servproto
- char* buf
- is a buffer to store the official name of the service
- unsigned long bufsize
- is the size of buf
- const char* path
- is the location of the services file, which may be NULL to use the system-wide default
- int
- 0 on success, -1 on error
lrint
Rounds to integer in current rounding mode.
The floating-point exception FE_INEXACT
is raised if the result is
different from the input.
- double x
- long
lrintf
Rounds to integer in current rounding mode.
The floating-point exception FE_INEXACT
is raised if the result is
different from the input.
- float x
- long
lrintl
Rounds to integer in current rounding mode.
The floating-point exception FE_INEXACT
is raised if the result is
different from the input.
- long double x
- long
lseek
Changes current position of file descriptor, e.g.
int fd = open("hello.bin", O_RDONLY); lseek(fd, 100, SEEK_SET); // set position to 100th byte read(fd, buf, 8); // read bytes 100 through 107This function may be used to inspect the current position:
int64_t pos = lseek(fd, 0, SEEK_CUR);You may seek past the end of file. If a write happens afterwards then the gap leading up to it will be filled with zeroes. Please note that lseek() by itself will not extend the physical medium.
If dup() is used then the current position will be shared across multiple file descriptors. If you seek in one it will implicitly seek the other too.
The current position of a file descriptor is shared between both processes and threads. For example, if an fd is inherited across fork(), and both the child and parent want to read from it, then changes made by one are observable to the other.
The pread() and pwrite() functions obfuscate the need for having global shared file position state. Consider using them, since it helps avoid the gotchas of this interface described above.
This function is supported by all OSes within our support vector and our unit tests demonstrate the behaviors described above are consistent across platforms.
- int fd
- is a number returned by open()
- long offset
- is 0-indexed byte count w.r.t.
whence
- int whence
- can be one of:
SEEK_SET
: Sets the file position tooffset
[default]SEEK_CUR
: Sets the file position toposition + offset
SEEK_END
: Sets the file position tofilesize + offset
- long
- new position relative to beginning, or -1 w/ errno
fd
is a pipe, socket, or fifo
fd
isn't an open file descriptor
whence
isn't valid
lstat
Returns information about file, w/o traversing symlinks.
- const char* pathname
- struct stat* st
- int
lutimes
Changes file timestamps, the legacy way.
- const char* filename
- struct __tv* tv
- int
lz4cpy
Decompresses LZ4 block.
This is a 103 byte implementation of the LZ4 algorithm. Please note LZ4 files are comprised of multiple frames, which may be decoded together using the wrapper function lz4decode().
- void* dest
- void* blockdata
- unsigned long blocksize
- void* blockdata
- void*
lz4decode
Decompresses LZ4 file.
We assume (1) the file is mmap()'d or was copied into into memory beforehand; and (2) folks handling untrustworthy data shall place 64kb of guard pages on the ends of each buffer, see mapanon(). We don't intend to support XXHASH; we recommend folks needing checks against data corruption consider crc32c(), or gzip since it's the best at file recovery. Dictionaries are supported; by convention, they are passed in the โค64kb bytes preceding src.
- void* dest
- void* src
- void*
- pointer to end of decoded data, similar to mempcpy()
lz4len
Returns the uncompressed content size for a compressed LZ4 block, without actually decompressing it.
- void* blockdata
- unsigned long blocksize
- unsigned long
madvise
Drops hints to O/S about intended access patterns of mmap()'d memory.
- void* addr
- unsigned long length
- int advice
- unsigned long length
- can be MADV_WILLNEED, MADV_SEQUENTIAL, MADV_FREE, etc.
- int
- 0 on success, or -1 w/ errno
__magicu_get
Precomputes magic numbers for unsigned division by constant.
The returned divisor may be passed to __magic_div() to perform unsigned integer division way faster than normal division e.g.
assert(77 / 7 == __magicu_div(77, __magicu_get(7)));
- unsigned int d
- is intended divisor, which must not be zero
- struct magu
- magic divisor (never zero)
makecontext
Creates coroutine gadget, e.g.
ucontext_t uc; getcontext(&uc); uc.uc_link = 0; uc.uc_stack.ss_sp = NewCosmoStack(); uc.uc_stack.ss_size = GetStackSize(); makecontext(&uc, exit, 1, 42); setcontext(&uc);Is equivalent to:
exit(42);The safest way to allocate stack memory is to use NewCosmoStack() and GetStackSize(), which will mmap() a fresh region of memory per a link time configuration, mprotect() some guard pages at the bottom, poison them if ASAN is in play, and then tell the OS that it's stack memory. If that's overkill for your use case, then you could potentially pass stacks as small as 1024 bytes; however they need to come from a stack allocation Cosmo granted to your main process and threads. It needn't be aligned, since this function takes care of that automatically. The address selected shall be
uc_stack.ss_ip + uc_stack.ss_size
and all
the action happens beneath that address.
On AMD64 and ARM64 you may pass up to six long
integer args, and up
to six vectors (e.g. double, floats, __m128i, uint8x16_t). Thou shall
not call code created by Microsoft compilers, even though this should
work perfectly fine on Windows, as it is written in the System V ABI,
which specifies your parameters are always being passed in registers.
- struct ucontext_t* uc
- stores processor state; the caller must have:
- initialized it using
getcontext(uc)
- allocated new values for
uc->uc_stack
- specified a successor context in
uc->uc_link
- initialized it using
- void(*)() func
- is the function to call when
uc
is activated; whenfunc
returns, control is passed touc->uc_link
, which if null will result in pthread_exit() being called - int argc
- is effectively ignored (see notes above)
- ...
- void
makedirs
Creates directory and parent components.
This function is similar to mkdir() except it iteratively creates parent directories and it won't fail if the directory already exists.
- const char* path
- is a UTF-8 string, preferably relative w/ forward slashes
- unsigned int mode
- can be, for example, 0755
- int
- 0 on success or -1 w/ errno
path
existed as non-directory
path
length exceeds PATH_MAX
path
exists longer than NAME_MAX
path
path
is an empty string
path
malloc
Allocates uninitialized memory.
Returns a pointer to a newly allocated chunk of at least n bytes, or null if no space is available, in which case errno is set to ENOMEM on ANSI C systems.
If n is zero, malloc returns a minimum-sized chunk. (The minimum size
is 32 bytes on 64bit systems.) It should be assumed that zero bytes
are possible access, since that'll be enforced by MODE=asan
.
Note that size_t is an unsigned type, so calls with arguments that would be negative if signed are interpreted as requests for huge amounts of space, which will often fail. The maximum supported value of n differs across systems, but is in all cases less than the maximum representable value of a size_t.
- unsigned long n
- void*
- new memory, or NULL w/ errno
malloc_trim
Releases freed memory back to system.
- unsigned long n
- specifies bytes of memory to leave available
- int
- 1 if it actually released any memory, else 0
malloc_usable_size
Returns the number of bytes you can actually use in an allocated chunk, which may be more than you requested (although often not) due to alignment and minimum size constraints.
You can use this many bytes without worrying about overwriting other allocated objects. This is not a particularly great programming practice. malloc_usable_size can be more useful in debugging and assertions, for example:
p = malloc(n) assert(malloc_usable_size(p) >= 256)
- void* p
- is address of allocation
- unsigned long
- total number of bytes
__map_phdrs
Maps APE-defined ELF program headers into memory and clears BSS.
- struct mman* mm
- unsigned long* pml4t
- unsigned long b
- unsigned long top
- unsigned long* pml4t
- void
_mapanon
Helper function for allocating anonymous mapping.
This function is equivalent to:
mmap(NULL, mapsize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);If mmap() fails, possibly because the parent process did this:
if (!vfork()) { setrlimit(RLIMIT_AS, &(struct rlimit){maxbytes, maxbytes}); execv(prog, (char *const[]){prog, 0}); } wait(0);Then this function will call:
__oom_hook(size);If it's linked. The LIBC_TESTLIB library provides an implementation, which can be installed as follows:
int main() { InstallQuotaHandlers(); // ... }That is performed automatically for unit test executables.
- unsigned long size
- void*
- memory map address on success, or null w/ errno
MapViewOfFileEx
Maps view of file mapping into memory on the New Technology.
- long hFileMappingObject
- was returned by CreateFileMapping()
- unsigned int dwDesiredAccess
- has kNtFileMap... flags
- unsigned int dwFileOffsetHigh
- unsigned int dwFileOffsetLow
- unsigned long dwNumberOfBytesToMap
- void* opt_lpDesiredBaseAddress
- unsigned int dwFileOffsetLow
- may be NULL to let o/s choose
- void*
- base address, or NULL on failure
MapViewOfFileExNuma
Maps view of file mapping into memory on the New Technology.
- long hFileMappingObject
- was returned by CreateFileMapping()
- unsigned int dwDesiredAccess
- has kNtFileMap... flags
- unsigned int dwFileOffsetHigh
- unsigned int dwFileOffsetLow
- unsigned long dwNumberOfBytesToMap
- void* opt_lpDesiredBaseAddress
- unsigned int dwFileOffsetLow
- may be NULL to let o/s choose
- unsigned int nndDesiredNumaNode
- void*
- base address, or NULL on failure
mbrlen
- const char* s
- unsigned long n
- unsigned int* t
- unsigned long n
- unsigned long
mbrtoc16
- unsigned short* pc16
- const char* s
- unsigned long n
- unsigned int* ps
- const char* s
- unsigned long
mbrtoc32
- unsigned int* pc32
- const char* s
- unsigned long n
- unsigned int* ps
- const char* s
- unsigned long
mbrtowc
- int* wc
- const char* src
- unsigned long n
- unsigned int* st
- const char* src
- unsigned long
mbsnrtowcs
- int* wcs
- const char** src
- unsigned long n
- unsigned long wn
- unsigned int* st
- const char** src
- unsigned long
mbsrtowcs
- int* ws
- const char** src
- unsigned long wn
- unsigned int* st
- const char** src
- unsigned long
mbstowcs
- int* pwc
- const char* s
- unsigned long wn
- const char* s
- unsigned long
MeasureEntropy
Returns Shannon entropy of array.
This gives you an idea of the density of information. Cryptographic random should be in the ballpark of 7.9 whereas plaintext will be more like 4.5.
- const char* p
- is treated as binary octets
- unsigned long n
- should be at least 1000
- double
- number between 0 and 8
memalign
Allocates aligned memory.
Returns a pointer to a newly allocated chunk of n bytes, aligned in accord with the alignment argument. The alignment argument shall be rounded up to the nearest two power and higher 2 powers may be used if the allocator imposes a minimum alignment requirement.
- unsigned long align
- is alignment in bytes, coerced to 1+ w/ 2-power roundup
- unsigned long bytes
- is number of bytes needed, coerced to 1+
- void*
- rax is memory address, or NULL w/ errno
memcasecmp
Compares memory case-insensitively.
memcasecmp n=0 992 picoseconds memcasecmp n=1 1 ns/byte 590 mb/s memcasecmp n=2 1 ns/byte 843 mb/s memcasecmp n=3 1 ns/byte 885 mb/s memcasecmp n=4 1 ns/byte 843 mb/s memcasecmp n=5 1 ns/byte 820 mb/s memcasecmp n=6 1 ns/byte 770 mb/s memcasecmp n=7 1 ns/byte 765 mb/s memcasecmp n=8 206 ps/byte 4,724 mb/s memcasecmp n=9 220 ps/byte 4,428 mb/s memcasecmp n=15 617 ps/byte 1,581 mb/s memcasecmp n=16 124 ps/byte 7,873 mb/s memcasecmp n=17 155 ps/byte 6,274 mb/s memcasecmp n=31 341 ps/byte 2,860 mb/s memcasecmp n=32 82 ps/byte 11,810 mb/s memcasecmp n=33 100 ps/byte 9,743 mb/s memcasecmp n=80 53 ps/byte 18,169 mb/s memcasecmp n=128 49 ps/byte 19,890 mb/s memcasecmp n=256 45 ps/byte 21,595 mb/s memcasecmp n=16384 42 ps/byte 22,721 mb/s memcasecmp n=32768 40 ps/byte 24,266 mb/s memcasecmp n=131072 40 ps/byte 24,337 mb/s
- void* p
- void* q
- unsigned long n
- void* q
- int
- is <0, 0, or >0 based on uint8_t comparison
memccpy
Copies at most N bytes from SRC to DST until ๐ is encountered.
This is little-known C Standard Library approach, dating back to the Fourth Edition of System Five, for copying a C strings to fixed-width buffers, with added generality.
For example, strictly:
char buf[16]; CHECK_NOTNULL(memccpy(buf, s, '\0', sizeof(buf)));Or unstrictly:
if (!memccpy(buf, s, '\0', sizeof(buf))) strcpy(buf, "?");Are usually more sensible than the following:
char cstrbuf[16]; snprintf(cstrbuf, sizeof(cstrbuf), "%s", CSTR);
- void* dst
- void* src
- int c
- void* src
- is search character and is masked with 255
- unsigned long n
- void*
- DST + idx(c) + 1, or NULL if ๐ โ ๐ โโคโคโโโ
memchr
Returns pointer to first instance of character.
- void* s
- is memory to search
- int c
- is search byte which is masked with 255
- unsigned long n
- is byte length of p
- void*
- is pointer to first instance of c or NULL if not found
memchr16
Returns pointer to first instance of character in range.
- void* s
- int c
- unsigned long n
- int c
- void*
memcmp
Compares memory byte by byte.
memcmp n=0 992 picoseconds memcmp n=1 1 ns/byte 738 mb/s memcmp n=2 661 ps/byte 1,476 mb/s memcmp n=3 551 ps/byte 1,771 mb/s memcmp n=4 248 ps/byte 3,936 mb/s memcmp n=5 198 ps/byte 4,920 mb/s memcmp n=6 165 ps/byte 5,904 mb/s memcmp n=7 141 ps/byte 6,889 mb/s memcmp n=8 124 ps/byte 7,873 mb/s memcmp n=9 110 ps/byte 8,857 mb/s memcmp n=15 44 ps/byte 22,143 mb/s memcmp n=16 41 ps/byte 23,619 mb/s memcmp n=17 77 ps/byte 12,547 mb/s memcmp n=31 42 ps/byte 22,881 mb/s memcmp n=32 41 ps/byte 23,619 mb/s memcmp n=33 60 ps/byte 16,238 mb/s memcmp n=80 53 ps/byte 18,169 mb/s memcmp n=128 38 ps/byte 25,194 mb/s memcmp n=256 32 ps/byte 30,233 mb/s memcmp n=16384 27 ps/byte 35,885 mb/s memcmp n=32768 29 ps/byte 32,851 mb/s memcmp n=131072 33 ps/byte 28,983 mb/s
- void* a
- void* b
- unsigned long n
- void* b
- int
- an integer that's (1) equal to zero if
a
is equal tob
, (2) less than zero ifa
is less thanb
, or (3) greater than zero ifa
is greater thanb
memfd_create
Creates anonymous file.
- const char* name
- is used for the
/proc/self/fd/FD
symlink - unsigned int flags
- can have
MFD_CLOEXEC
,MFD_ALLOW_SEALING
- int
memfrob
Memfrob implements a crypto algorithm proven to be unbreakable, without meeting its requirements concerning secrecy or length.
- void* buf
- unsigned long size
- void*
memjmpinit
Initializes jump table for memset() and memcpy().
- !ZF
- if required cpu vector extensions are available
- rdi
- is address of 64-bit jump table
- rsi
- is address of 8-bit jump initializers
- rdx
- is address of indirect branch
- ecx
- is size of jump table
memmem
Searches for fixed-length substring in memory region.
- void* haystack
- is the region of memory to be searched
- unsigned long haystacklen
- is its character count
- void* needle
- contains the memory for which we're searching
- unsigned long needlelen
- is its character count
- void*
- pointer to first result or NULL if not found
memmove
Copies memory.
memmove n=0 661 picoseconds memmove n=1 661 ps/byte 1,476 mb/s memmove n=2 330 ps/byte 2,952 mb/s memmove n=3 330 ps/byte 2,952 mb/s memmove n=4 165 ps/byte 5,904 mb/s memmove n=7 141 ps/byte 6,888 mb/s memmove n=8 82 ps/byte 11 GB/s memmove n=15 44 ps/byte 21 GB/s memmove n=16 41 ps/byte 23 GB/s memmove n=31 32 ps/byte 29 GB/s memmove n=32 31 ps/byte 30 GB/s memmove n=63 21 ps/byte 45 GB/s memmove n=64 15 ps/byte 61 GB/s memmove n=127 13 ps/byte 73 GB/s memmove n=128 31 ps/byte 30 GB/s memmove n=255 20 ps/byte 45 GB/s memmove n=256 19 ps/byte 49 GB/s memmove n=511 16 ps/byte 56 GB/s memmove n=512 17 ps/byte 54 GB/s memmove n=1023 18 ps/byte 52 GB/s memmove n=1024 13 ps/byte 72 GB/s memmove n=2047 9 ps/byte 96 GB/s memmove n=2048 9 ps/byte 98 GB/s memmove n=4095 8 ps/byte 112 GB/s memmove n=4096 8 ps/byte 109 GB/s memmove n=8191 7 ps/byte 124 GB/s memmove n=8192 7 ps/byte 125 GB/s memmove n=16383 7 ps/byte 134 GB/s memmove n=16384 7 ps/byte 134 GB/s memmove n=32767 13 ps/byte 72 GB/s memmove n=32768 13 ps/byte 72 GB/s memmove n=65535 13 ps/byte 68 GB/s memmove n=65536 14 ps/byte 67 GB/s memmove n=131071 14 ps/byte 65 GB/s memmove n=131072 14 ps/byte 64 GB/s memmove n=262143 15 ps/byte 63 GB/s memmove n=262144 15 ps/byte 63 GB/s memmove n=524287 15 ps/byte 61 GB/s memmove n=524288 15 ps/byte 61 GB/s memmove n=1048575 15 ps/byte 61 GB/s memmove n=1048576 15 ps/byte 61 GB/s memmove n=2097151 19 ps/byte 48 GB/s memmove n=2097152 27 ps/byte 35 GB/s memmove n=4194303 28 ps/byte 33 GB/s memmove n=4194304 28 ps/byte 33 GB/s memmove n=8388607 28 ps/byte 33 GB/s memmove n=8388608 28 ps/byte 33 GB/sDST and SRC may overlap.
- void* dst
- is destination
- void* src
- is memory to copy
- unsigned long n
- is number of bytes to copy
- void*
- dst
memrchr
Returns pointer to first instance of character.
- void* s
- is memory to search
- int c
- is search byte which is masked with 255
- unsigned long n
- is byte length of p
- void*
- is pointer to first instance of c or NULL if not found
memrchr16
Returns pointer to first instance of character.
- void* s
- is memory to search
- int c
- is search byte which is masked with 65535
- unsigned long n
- is number of char16_t elements in
s
- void*
- is pointer to first instance of c or NULL if not found
memset
Sets memory.
memset n=0 992 picoseconds memset n=1 992 ps/byte 984 mb/s memset n=2 330 ps/byte 2,952 mb/s memset n=3 330 ps/byte 2,952 mb/s memset n=4 165 ps/byte 5,904 mb/s memset n=7 94 ps/byte 10,333 mb/s memset n=8 124 ps/byte 7,872 mb/s memset n=15 66 ps/byte 14,761 mb/s memset n=16 62 ps/byte 15,745 mb/s memset n=31 32 ps/byte 30,506 mb/s memset n=32 20 ps/byte 47,236 mb/s memset n=63 26 ps/byte 37,198 mb/s memset n=64 20 ps/byte 47,236 mb/s memset n=127 23 ps/byte 41,660 mb/s memset n=128 12 ps/byte 75,578 mb/s memset n=255 18 ps/byte 53,773 mb/s memset n=256 12 ps/byte 75,578 mb/s memset n=511 17 ps/byte 55,874 mb/s memset n=512 12 ps/byte 75,578 mb/s memset n=1023 16 ps/byte 58,080 mb/s memset n=1024 11 ps/byte 86,375 mb/s memset n=2047 9 ps/byte 101 gb/s memset n=2048 8 ps/byte 107 gb/s memset n=4095 8 ps/byte 113 gb/s memset n=4096 8 ps/byte 114 gb/s memset n=8191 7 ps/byte 126 gb/s memset n=8192 7 ps/byte 126 gb/s memset n=16383 7 ps/byte 133 gb/s memset n=16384 7 ps/byte 131 gb/s memset n=32767 14 ps/byte 69,246 mb/s memset n=32768 6 ps/byte 138 gb/s memset n=65535 15 ps/byte 62,756 mb/s memset n=65536 15 ps/byte 62,982 mb/s memset n=131071 18 ps/byte 52,834 mb/s memset n=131072 15 ps/byte 62,023 mb/s memset n=262143 15 ps/byte 61,169 mb/s memset n=262144 16 ps/byte 61,011 mb/s memset n=524287 16 ps/byte 60,633 mb/s memset n=524288 16 ps/byte 57,902 mb/s memset n=1048575 16 ps/byte 60,405 mb/s memset n=1048576 16 ps/byte 58,754 mb/s memset n=2097151 16 ps/byte 59,329 mb/s memset n=2097152 16 ps/byte 58,729 mb/s memset n=4194303 16 ps/byte 59,329 mb/s memset n=4194304 16 ps/byte 59,262 mb/s memset n=8388607 16 ps/byte 59,530 mb/s memset n=8388608 16 ps/byte 60,205 mb/s
- void* p
- is memory address
- int c
- is masked with 255 and used as repeated byte
- unsigned long n
- is byte length
- void*
- p
memset16
Sets wide memory.
- unsigned short* p
- unsigned short c
- unsigned long n
- unsigned short c
- unsigned short*
mergesort
Sorts array.
- void* base
- unsigned long nmemb
- is item count
- unsigned long size
- is item width
- int(*)() cmp
- is a callback returning <0, 0, or >0
- int
mergesort_r
Sorts array w/ optional callback argument.
- void* base
- is base of array
- unsigned long nmemb
- is item count
- unsigned long size
- is item width
- int(*)() cmp
- is a callback returning <0, 0, or >0
- void* z
- will optionally be passed as the third argument to cmp
- int
MetalPrintf
Prints string to serial port.
This only supports %d and %s. It'll will work even if .rodata hasn't been loaded into memory yet.
- const char* fmt
- ...
- void
mincore
Tells you which pages are resident in memory.
- void* addr
- unsigned long length
- unsigned char* vec
- unsigned long length
- int
mkdir
Creates directory a.k.a. folder.
mkdir o โ 0 mkdir o/yo/yo/yo โ -1 w/ ENOENT if o/yo is file โ -1 w/ ENOTDIR if o/yo/yo/yo is dir โ -1 w/ EEXIST if o/yo/yo/yo is file โ -1 w/ EEXIST
- const char* path
- is a UTF-8 string, preferably relative w/ forward slashes
- unsigned int mode
- can be, for example, 0755
- int
- 0 on success or -1 w/ errno
path
existed as non-directory
path
length exceeds PATH_MAX
path
exists longer than NAME_MAX
path
path
didn't exist
path
is an empty string
path
mkdirat
Creates directory a.k.a. folder.
- int dirfd
- is normally
AT_FDCWD
but if it's an open directory and path is relative, then path becomes relative to dirfd - const char* path
- is a UTF-8 string, preferably relative w/ forward slashes
- unsigned int mode
- is permissions bits, which is usually 0755
- int
- 0 on success, or -1 w/ errno
path
is relative and dirfd
isn't AT_FDCWD
or valid
path
existed as non-directory
path
length exceeds PATH_MAX
path
exists longer than NAME_MAX
path
path
didn't exist
path
is an empty string
path
mkdtemp
Creates temporary directory, e.g.
char path[PATH_MAX]; snprintf(path, sizeof(path), "%s%s.XXXXXX", kTmpPath, program_invocation_short_name); printf("%s\n", mkdtemp(path)); rmdir(path);
- char* template
- must end with XXXXXX which is replaced with nondeterministic base36 random data
- char*
- pointer to template on success, or NULL w/ errno
mkfifo
Creates named pipe.
- const char* pathname
- unsigned int mode
- is octal, e.g. 0600 for owner-only read/write
- int
- 0 on success, or -1 w/ errno
mknod
Creates filesystem inode.
- const char* path
- unsigned int mode
- is octal mode, e.g. 0600; needs to be or'd with one of: S_IFDIR: directory S_IFIFO: named pipe S_IFREG: regular file S_IFSOCK: named socket S_IFBLK: block device (root has authorization) S_IFCHR: character device (root has authorization)
- unsigned long dev
- it's complicated
- int
- 0 on success, or -1 w/ errno
mkntenvblock
Copies sorted environment variable block for Windows.
This is designed to meet the requirements of CreateProcess().
- unsigned short* envvars
- receives sorted double-NUL terminated string list
- char** envp
- is an a NULL-terminated array of UTF-8 strings
- const char* extravar
- is a VAR=val string we consider part of envp or NULL
- char* buf
- int
- 0 on success, or -1 w/ errno
__mkntpath2
Copies path for Windows NT.
This function does the following chores:
- Converting UTF-8 to UTF-16
- Replacing forward-slashes with backslashes
- Fixing drive letter paths, e.g.
/c/
โc:\
- Add
\\?\
prefix for paths exceeding 260 chars - Remapping well-known paths, e.g.
/dev/null
โNUL
- const char* path
- unsigned short* path16
- is shortened so caller can prefix, e.g. \\.\pipe\, and due to a plethora of special-cases throughout the Win32 API
- int flags
- is used by open()
- int
- short count excluding NUL on success, or -1 w/ errno
mkostemps
Delegates to mkotempsm() w/ owner-only non-execute access.
- char* template
- int suffixlen
- unsigned int flags
- int suffixlen
- int
mkostempsm
Opens unique temporary file.
The substring XXXXXX is replaced with a pseudorandom number that's seeded automatically and grants 30 bits of randomness to each value. Retries are made in the unlikely event of collisions.
- char* template
- is a pathname relative to current directory by default, that needs to have "XXXXXX" at the end of the string
- int suffixlen
- may be nonzero to permit characters after the XXXXXX
- unsigned int flags
- can have O_APPEND, O_CLOEXEC, etc.
- int mode
- is conventionally 0600, for owner-only non-exec access
- int
- exclusive open file descriptor for generated pathname, or -1 w/ errno
mkostempsmi
- char* tpl
- int slen
- unsigned int flags
- unsigned long* rando
- int mode
- int(*)() openit
- int slen
- int
mkstemp
Creates temporary file name and file descriptor.
The best way to construct your path template is:
char path[PATH_MAX+1]; strlcat(path, kTmpDir, sizeof(path)); strlcat(path, "sauce.XXXXXX", sizeof(path));This usage pattern makes mkstemp() equivalent to tmpfd():
int fd; fd = mkstemp(path); unlink(path);This usage pattern makes mkstemp() equivalent to mktemp():
close(mkstemp(path)); puts(path);
- char* template
- is mutated to replace last six X's with rng
- int
- open file descriptor r + w exclusive or -1 w/ errno
template
didn't end with XXXXXX
mktemp
Generates temporary filename.
char tmp[14] = "/tmp/hiXXXXXX"; puts(mkstemp(tmp));
- char* template
- is mutated to replace last six X's with rng
- char*
- pointer to mutated
template
, or 0 w/ errno
template
didn't end with XXXXXX
_mktls
Allocates thread-local storage memory for new thread.
- struct CosmoTib** out_tib
- char*
- buffer that must be released with free()
mlock
Locks virtual memory interval into RAM, preventing it from swapping.
- void* addr
- unsigned long len
- int
- 0 on success, or -1 w/ errno
mmap
Creates virtual memory, e.g.
char *m; m = mmap(NULL, FRAMESIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); munmap(m, FRAMESIZE);
- void* addr
- should be 0 to let your memory manager choose address; unless MAP_FIXED or MAP_FIXED_NOREPLACE are specified in flags in which case this function will do precicely as you ask, even if p=0 (in which you need -fno-delete-null-pointer-checks); it needs to be 64kb aligned because it's a wise choice that sadly needs to be made mandatory because of Windows although you can use __sys_mmap() to circumvent it on System Five in which case runtime support services, e.g. asan memory safety, could break
- unsigned long size
- must be >0 otherwise EINVAL is raised
- int prot
- can have PROT_READ/PROT_WRITE/PROT_EXEC/PROT_NONE/etc.
- int flags
- should have one of the following masked by
MAP_TYPE
MAP_FILE
in which caseMAP_ANONYMOUS
shouldn't be usedMAP_PRIVATE
for copy-on-write behavior of writeable pagesMAP_SHARED
to create shared memory between processesMAP_STACK
to create a grows-down alloc, where a guard page is automatically protected at the bottom, sized as AT_PAGESZ
flags
may optionally bitwise or any of the following:MAP_ANONYMOUS
in which casefd
andoff
are ignoredMAP_FIXED
in which caseaddr
becomes more than a hintMAP_FIXED_NOREPLACE
to protect existing mappings; this is always polyfilled by mmap() which tracks its own memory and removed before passing to the kernel, in order to support old versions; if you believe mappings exist which only the kernel knows, then this flag may be passed to sys_mmap() on Linux 4.17+ and FreeBSD (where it has multiple bits)MAP_CONCEAL
is FreeBSD/NetBSD/OpenBSD-onlyMAP_NORESERVE
is Linux/XNU/NetBSD-onlyMAP_POPULATE
is Linux/FreeBSD-onlyMAP_NONBLOCK
is Linux-onlyMAP_NOSYNC
is FreeBSD-onlyMAP_INHERIT
is NetBSD-onlyMAP_LOCKED
is Linux-only
- int fd
- is an open()'d file descriptor, whose contents shall be made available w/ automatic reading at the chosen address
- long off
- specifies absolute byte index of fd's file for mapping, should be zero if MAP_ANONYMOUS is specified, which SHOULD be aligned to FRAMESIZE
- void*
- virtual base address of new mapping, or MAP_FAILED w/ errno
modf
Returns fractional part of ๐ฅ.
- double x
- double* iptr
- double
__morph_begin
Begins code morphing executable.
The following example
#include <cosmo.h> #include <stdlib.h> privileged int main() { // privileged code is unmodifiable ShowCrashReports(); // print report if trapped __morph_begin(0); // make executable code R+W *(char *)exit = 0xCC; // turn exit() into an INT3 trap __morph_end(); // make executable code R+X exit(0); // won't actually exit }shows how the exit() function can be recompiled at runtime to become an int3 (x86-64) debugger trap. What makes it tricky is Cosmopolitan maintains a R^X invariant, in order to support OpenBSD. So when code wants to modify some part of the executable image in memory the vast majority of the code stops being executable during that time, unless it's been linked into a special privileged section of the binary. It is only possible to code morph from privileged functions. Privileged functions are also only allowed to call other privileged functions.
- void
mount
Mounts file system.
The following flags may be specified:
MS_RDONLY
(mount read-only)MS_NOSUID
(don't honor S_ISUID bit)MS_NODEV
(disallow special files)MS_NOEXEC
(disallow program execution)MS_SYNCHRONOUS
(writes are synced at once)MS_NOATIME
(do not update access times)MS_REMOUNT
(tune existing mounting)
MNT_ASYNC
(xnu, freebsd, openbsd, netbsd)MNT_RELOAD
(xnu, freebsd, openbsd, netbsd)MS_STRICTATIME
(linux, xnu)MS_RELATIME
(linux, netbsd)MNT_SNAPSHOT
(xnu, freebsd)MS_MANDLOCK
(linux)MS_DIRSYNC
(linux)MS_NODIRATIME
(linux)MS_BIND
(linux)MS_MOVE
(linux)MS_REC
(linux)MS_SILENT
(linux)MS_POSIXACL
(linux)MS_UNBINDABLE
(linux)MS_PRIVATE
(linux)MS_SLAVE
(linux)MS_SHARED
(linux)MS_KERNMOUNT
(linux)MS_I_VERSION
(linux)MS_LAZYTIME
(linux)MS_ACTIVE
(linux)MS_NOUSER
(linux)MS_RMT
_MASK (linux)MNT_SUIDDIR
(freebsd)MNT_NOCLUSTERR
(freebsd)MNT_NOCLUSTERW
(freebsd)
type
parameter:
"nfs"
"vfat"
"tmpfs"
"iso8601"
- const char* source
- const char* target
- const char* type
- unsigned long flags
- void* data
- const char* target
- int
MoveFileEx
Deletes existing empty directory.
- const unsigned short* lpExistingFileName
- const unsigned short* lpNewFileName
- int dwFlags
- const unsigned short* lpNewFileName
- int
mprotect
Modifies restrictions on virtual memory address range.
- void* addr
- needs to be 4kb aligned
- unsigned long size
- int prot
- can have PROT_{NONE,READ,WRITE,EXEC,GROWSDOWN,GROWSUP}
- int
- 0 on success, or -1 w/ errno
msync
Synchronize memory mapping changes to disk.
Without this, there's no guarantee memory is written back to disk. Particularly on RHEL5, OpenBSD, and Windows NT.
- void* addr
- needs to be 4096-byte page aligned
- unsigned long size
- int flags
- needs MS_ASYNC or MS_SYNC and can have MS_INVALIDATE
- int
- 0 on success or -1 w/ errno
_mt19937
Generates random integer on [0, 2^64)-interval.
This uses the Mersenne Twister pseudorandom number generator.
- unsigned long
Mul4x4Adx
Computes 512-bit product of 256-bit and 256-bit numbers.
Instructions: 88 Total Cycles: 36 Total uOps: 120 uOps Per Cycle: 3.33 IPC: 2.44 Block RThroughput: 20.0
- rdi
- receives 8 quadword result
- rsi
- is left hand side which must have 4 quadwords
- rdx
- is right hand side which must have 4 quadwords
Mul6x6Adx
Computes 768-bit product of 384-bit and 384-bit numbers.
Instructions: 152 Total Cycles: 65 Total uOps: 260 uOps Per Cycle: 4.00 IPC: 2.34 Block RThroughput: 43.3
- rdi
- receives 8 quadword result
- rsi
- is left hand side which must have 4 quadwords
- rdx
- is right hand side which must have 4 quadwords
Mul8x8Adx
Computes 1024-bit product of 512-bit and 512-bit numbers.
Instructions: 260 Total Cycles: 98 Total uOps: 452 uOps Per Cycle: 4.61 IPC: 2.65 Block RThroughput: 75.3
- rdi
- receives 16 quadword result
- rsi
- is left hand side which must have 8 quadwords
- rdx
- is right hand side which must have 8 quadwords
__mulvdi3
Returns ๐ฅ*๐ฆ, aborting on overflow.
- long x
- long y
- long
__mulvsi3
Returns ๐ฅ*๐ฆ, aborting on overflow.
- int x
- int y
- int
__mulvti3
Returns ๐ฅ*๐ฆ, aborting on overflow.
- __int128 x
- __int128 y
- __int128
munlock
Unlocks virtual memory interval from RAM, to permit swapping.
- void* addr
- unsigned long len
- int
- 0 on success, or -1 w/ errno
munmap
Releases memory pages.
- void* p
- is the beginning of the memory region to unmap
- unsigned long n
- is the number of bytes to be unmapped
- int
- 0 on success, or -1 w/ errno
n == 0
n
isn't 48-bit
p+(n-1)
isn't 48-bit
p
isn't 65536-byte aligned
_nanos
Returns nanoseconds since UNIX epoch.
- int timer
- __int128
nanosleep
Sleeps for relative amount of time.
- struct __ts* req
- is the duration of time we should sleep
- struct __ts* rem
- if non-null will be updated with the remainder of unslept
time when -1 w/
EINTR
is returned otherwiserem
is undefined
- int
- 0 on success, or -1 w/ errno
req->tv_nsec โ [0,1000000000)
rem
is updated
req
is NULL or req
/ rem
is a bad pointer
__negvdi2
Returns -๐ฅ on overflow.
- long x
- long
__negvsi2
Returns -๐ฅ, aborting on overflow.
- int x
- int
__negvti2
Returns -๐ฅ, aborting on overflow.
- __int128 x
- __int128
NewCosmoStack
Allocates stack.
The size of your returned stack is always GetStackSize().
The bottom 4096 bytes of your stack can't be used, since it's always reserved for a read-only guard page. With ASAN it'll be poisoned too.
The top 16 bytes of a stack can't be used due to openbsd:stackbound and those bytes are also poisoned under ASAN build modes.
- void*
- stack bottom address on success, or null w/ errno
newlocale
- int catmask
- const char* locale
- struct __locale_struct* base
- const char* locale
- struct __locale_struct*
nftw
Walks file tree.
- const char* dirpath
- int(*)() fn
- int fd_limit
- int flags
- int(*)() fn
- int
- 0 on success, -1 on error, or non-zero
fn
result
nice
Changes process priority.
- int delta
- is added to current priority w/ clamping
- int
- new priority, or -1 w/ errno
__nocolor
Indicates if ANSI terminal colors are inappropriate.
Normally this variable should be false. We only set it to true if
we're running on an old version of Windows or the environment
variable TERM
is set to dumb
.
We think colors should be the norm, since most software is usually
too conservative about removing them. Rather than using isatty
consider using sed for instances where color must be removed:
sed 's/\x1b\[[;[:digit:]]*m//g' <color.txt >uncolor.txtFor some reason, important software is configured by default in many operating systems, to not only disable colors, but utf-8 too! Here's an example of how a wrapper script can fix that for
less
.
#!/bin/sh LESSCHARSET=UTF-8 exec /usr/bin/less -RS "$@"Thank you for using colors!
- _Bool
__nosync
Tunes sync system call availability.
If this value is set to 0x5453455454534146, then the system calls sync(), fsync(), and fdatasync() system calls will do nothing and return success. This is intended to be used for things like making things like Python unit tests go faster because fsync is extremely slow and using tmpfs requires root privileges.
- unsigned long
nsync_counter_wait
- struct nsync_counter_s_* c
- struct abs_deadline abs_deadline
- unsigned int
nsync_counter_waitable_funcs
- struct nsync_counter_waitable_funcs
nsync_cv_wait_with_deadline
- struct no_children_cv* pcv
- struct note_mu* pmu
- struct abs_deadline abs_deadline
- struct nsync_note_s_* cancel_note
- struct note_mu* pmu
- int
nsync_cv_wait_with_deadline_generic
- struct no_children_cv* pcv
- void* pmu
- void(*)() lock
- void(*)() unlock
- struct abs_deadline abs_deadline
- struct nsync_note_s_* cancel_note
- void* pmu
- int
nsync_mu_wait
- struct note_mu* mu
- int(*)() condition
- void* condition_arg
- int(*)() condition_arg_eq
- int(*)() condition
- void
nsync_mu_wait_with_deadline
- struct note_mu* mu
- int(*)() condition
- void* condition_arg
- int(*)() condition_arg_eq
- struct abs_deadline abs_deadline
- struct nsync_note_s_* cancel_note
- int(*)() condition
- int
nsync_note_new
- struct nsync_note_s_* parent
- struct abs_deadline abs_deadline
- struct nsync_note_s_*
nsync_note_waitable_funcs
- struct nsync_note_waitable_funcs
__nt2sysv
Translates function call from code built w/ MS-style compiler.
This wraps WinMain() and callback functions passed to Win32 API. Please note an intermediary jump slot is needed to set %rax.
- %rax
- is function address
- %rax,%xmm0
ntaccesscheck
Asks Microsoft if we're authorized to use a folder or file.
Implementation Details: MSDN documentation imposes no limit on the internal size of SECURITY_DESCRIPTOR, which we are responsible for allocating. We've selected 1024 which shall hopefully be adequate.
- const unsigned short* pathname
- unsigned int flags
- can have R_OK, W_OK, X_OK, etc.
- int
- 0 if authorized, or -1 w/ errno
NtGetVersion
Returns New Technology version, e.g.
This can only be called on Windows.
- int
ntsetprivilege
Sets NT permission thing, e.g.
int64_t htoken; if (OpenProcessToken(GetCurrentProcess(), kNtTokenAdjustPrivileges | kNtTokenQuery, &htoken)) { ntsetprivilege(htoken, u"SeManageVolumePrivilege", kNtSePrivilegeEnabled); CloseHandle(htoken); }
- long token
- const unsigned short* name
- unsigned int attrs
- const unsigned short* name
- int
ntspawn
Spawns process on Windows NT.
This function delegates to CreateProcess() with UTF-8 โ UTF-16 translation and argv escaping. Please note this will NOT escape command interpreter syntax.
- const char* prog
- won't be PATH searched
- char** argv
- specifies prog arguments
- char** envp
- const char* extravar
- is added to envp to avoid setenv() in caller
- struct NtSecurityAttributes* opt_lpProcessAttributes
- struct NtSecurityAttributes* opt_lpThreadAttributes
- int bInheritHandles
- struct NtSecurityAttributes* opt_lpThreadAttributes
- means handles already marked inheritable will be inherited; which, assuming the System V wrapper functions are being used, should mean (1) all files and sockets that weren't opened with O_CLOEXEC; and (2) all memory mappings
- unsigned int dwCreationFlags
- const unsigned short* opt_lpCurrentDirectory
- struct NtStartupInfo* lpStartupInfo
- struct NtProcessInformation* opt_out_lpProcessInformation
- const unsigned short* opt_lpCurrentDirectory
- can be used to return process and thread IDs to parent, as well as open handles that need close()
- int
- 0 on success, or -1 w/ errno
__on_arithmetic_overflow
Arithmetic overflow handler.
This function is provided weakly, so that programs which depend on
this library may define it themselves. This default implementation
will print a message to standard error and raise SIGTRAP. A custom
implementation may return from this function, in which case the op
shall have -fwrapv
i.e. signed two's complement behavior.
- void
__oncrash_amd64
Crashes in a developer-friendly human-centric way.
We first try to launch GDB if it's an interactive development session. Otherwise we show a really good crash report, sort of like Python, that includes filenames and line numbers. Many editors, e.g. Emacs, will even recognize its syntax for quick hopping to the failing line. That's only possible if the the .com.dbg file is in the same folder. If the concomitant debug binary can't be found, we simply print addresses which may be cross-referenced using objdump.
This function never returns, except for traps w/ human supervision.
- int sig
- struct siginfo_t* si
- void* arg
- struct siginfo_t* si
- void
open
Opens file.
This is equivalent to saying:
int fd = openat(AT_FDCWD, file, flags, ...);
- const char* file
- specifies filesystem path to open
- int flags
- ...
- int
- file descriptor, or -1 w/ errno
openat
Opens file.
Here's an example of how a file can be created:
int fd = openat(AT_FDCWD, "hi.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644); write(fd, "hello\n", 6); close(fd);Here's an example of how that file could read back into memory:
char data[513] = {0}; int fd = openat(AT_FDCWD, "hi.txt", O_RDONLY); read(fd, data, 512); close(fd); assert(!strcmp(data, "hello\n"));If your main() source file has this statement:
__static_yoink("zipos");Then you can read zip assets by adding a
"/zip/..."
prefix to file
, e.g.
// run `zip program.com hi.txt` beforehand openat(AT_FDCWD, "/zip/hi.txt", O_RDONLY);
- int dirfd
- is normally
AT_FDCWD
but if it's an open directory andfile
names a relative path then it's opened relative todirfd
- const char* file
- is a UTF-8 string naming filesystem entity, e.g.
foo/bar.txt
, which on Windows is bludgeoned into a WIN32 path automatically, e.g.foo/bar.txt
becomesfoo\bar.txt
/tmp/...
becomes whatever GetTempPath() is\\...
or//...
is passed through to WIN32 unchanged/c/foo
or\c\foo
becomes\\?\c:\foo
c:/foo
orc:\foo
becomes\\?\c:\foo
/D
becomes\\?\D:\
- int flags
- must have one of the following under the
O_ACCMODE
bits:O_RDONLY
to openfile
for reading onlyO_WRONLY
to openfile
for writingO_RDWR
to openfile
for reading and writing
flags
:O_CREAT
create file if it doesn't existO_TRUNC
automaticftruncate(fd,0)
if existsO_CLOEXEC
automatic close() upon execve()O_EXCL
exclusive access (see below)O_APPEND
open file for appending onlyO_EXEC
open file for execution only; see fexecve()O_NOCTTY
preventsfile
possibly becoming controlling terminalO_NONBLOCK
asks read/write to fail withEAGAIN
rather than blockO_DIRECT
it's complicated (not supported on Apple and OpenBSD)O_DIRECTORY
useful for stat'ing (hint on UNIX but required on NT)O_NOFOLLOW
fail if it's a symlink (zero on Windows)O_DSYNC
it's complicated (zero on non-Linux/Apple)O_RSYNC
it's complicated (zero on non-Linux/Apple)O_VERIFY
it's complicated (zero on non-FreeBSD)O_SHLOCK
it's complicated (zero on non-BSD)O_EXLOCK
it's complicated (zero on non-BSD)O_PATH
open only for metadata (Linux 2.6.39+ otherwise zero)O_NOATIME
don't record access time (zero on non-Linux)O_RANDOM
hint random access intent (zero on non-Windows)O_SEQUENTIAL
hint sequential access intent (zero on non-Windows)O_COMPRESSED
ask fs to abstract compression (zero on non-Windows)O_INDEXED
turns on that slow performance (zero on non-Windows)O_TMPFILE
should not be used; use tmpfd() or tmpfile() instead
O_RDONLY
: Opens existing file for reading. If it doesn't exist then nil is returned and errno will beENOENT
(or in some other casesENOTDIR
).O_WRONLY|O_CREAT|O_TRUNC
: Creates file. If it already exists, then the existing copy is destroyed and the opened file will start off with a length of zero. This is the behavior of the traditional creat() system call.O_WRONLY|O_CREAT|O_EXCL
: Create file only if doesn't exist already. If it does exist thennil
is returned along witherrno
set toEEXIST
.
- ...
- int
- file descriptor (which needs to be close()'d), or -1 w/ errno
file
path
file
flags & O_ACCMODE
was denied
O_TRUNC
was specified in flags
but writing was denied
file
is on zip file system and dirfd
isn't AT_FDCWD
file
exists as non-directory
file
is relative and dirfd
isn't an open directory
file
on read-only filesystem
file
length exceeds PATH_MAX
file
exists longer than NAME_MAX
file
is on zip file system and process is vfork()'d
file
would be O_CREAT
ed
O_CREAT|O_EXCL
are used and file
already existed
file
doesn't exist when O_CREAT
isn't in flags
file
points to a string that's empty
RLIMIT_NOFILE
has been reached
file
names a named socket
file
points to invalid memory
file
that's being executed
flags
had O_NOFOLLOW
and file
is a symbolic link
file
file
names a directory
opendir
Opens directory, e.g.
DIR *d; struct dirent *e; CHECK((d = opendir(path))); while ((e = readdir(d))) { printf("%s/%s\n", path, e->d_name); } LOGIFNEG1(closedir(d));
- const char* name
- struct dirstream*
openlog
Opens a connection to the system logger
Calling this function before calling syslog() is optional and only allow customizing the identity, options and facility of the messages logged.
- const char* ident
- a string that prepends every logged message. If it set to NULL, the program name is used.
- int opt
- specifies flags which control the operation of openlog().
Only the following flags are supported:
LOG_CONS = Write directly to the system console if there is an error while sending to the system logger. LOG_NDELAY = Open the connection with the system logger immediately instead of waiting for the first message to be logged. LOG_ODELAY = The converse of LOG_NDELAY. LOG_PERROR = Also log the message to stderr. LOG_PID = Include the caller's PID with each message
- int facility
- specifies the default facitlity value that defines what kind of program is logging the message. Possible values are: LOG_AUTH, LOG_AUTHPRIV, LOG_CRON, LOG_DAEMON, LOG_FTP, LOG_LOCAL0 through LOG_LOCAL7, LOG_LPR, LOG_MAIL, LOG_NEWS, LOG_SYSLOG, LOG_USER (default), LOG_UUCP.
- void
OpenProcess
Creates file mapping object on the New Technology.
- unsigned int dwDesiredAccess
- should be kNtProcess... combination
- int bInheritHandle
- unsigned int dwProcessId
- long
- ehandle, or 0 on failure
openpty
Opens new pseudo teletypewriter.
- int* mfd
- receives controlling tty rw fd on success
- int* sfd
- receives subordinate tty rw fd on success
- char* name
- struct linux* tio
- may be passed to tune a century of legacy behaviors
- struct winsize* wsz
- may be passed to set terminal display dimensions
- int
- 0 on success, or -1 w/ errno
OpenSymbolTable
Maps debuggable binary into memory and indexes symbol addresses.
- const char* filename
- struct SymbolTable*
- object freeable with CloseSymbolTable(), or NULL w/ errno
packsswb
Casts shorts to signed chars w/ saturation.
๐ โ {CLAMP[๐แตข]|๐โ[0,4)} โ {CLAMP[๐แตข]|๐โ[4,8)}
- char* a
- const short* b
- const short* c
- const short* b
- void
packuswb
Casts shorts to unsigned chars w/ saturation.
๐ โ {CLAMP[๐แตข]|๐โ[0,4)} โ {CLAMP[๐แตข]|๐โ[4,8)}
- unsigned char* a
- const short* b
- const short* c
- const short* b
- void
paddw
Adds 16-bit integers.
- short* a
- const short* b
- const short* c
- const short* b
- void
__paginate
Displays wall of text in terminal with pagination.
- int fd
- const char* s
- void
palignr
Overlaps vectors.
๐= 0 means ๐โ๐0<๐<16 means ๐โ๐โ๐
๐=16 means ๐โ๐16<๐<32 means ๐โ๐โ0
๐โฅ32 means ๐โ0
- void* c
- void* b
- void* a
- unsigned long i
- void* b
- void
__palignrs
Jump table for palignr() with non-constexpr immediate parameter.
pandn
Nands 128-bit integers.
- unsigned long* a
- const unsigned long* b
- const unsigned long* c
- const unsigned long* b
- void
ParseCidr
Parse IPv4 network address.
For example, a router address might be 10.10.10.1/24
in which case
the IP address word 0x0a0a0a01
would be returned, whose CIDR would
be 24. That means your IP address is on a network with 24 bits which
converts to a netmask 0xffffff00
by using 1u << (32 - res.cidr)
.
You may specify the IP address portion as an integer. As an example,
the value 168430081/1
would be the same as 10.10.10.1/1
- const char* s
- unsigned long n
- if -1 implies strlen
- struct c
- ip is uint32 IPv4 address, or -1 on failure
- cidr is number of bits in network, on interval [1,32]; it defaults to 32; if the return ip is -1 then cidr is undefined
ParseContentLength
Parses Content-Length header.
- const char* s
- unsigned long n
- long
- -1 on invalid or overflow, otherwise >=0 value
ParseForwarded
Parses X-Forwarded-For.
This header is used by reverse proxies. For example:
X-Forwarded-For: 203.0.110.2, 203.0.113.42:31337The port is optional and will be set to zero if absent.
- const char* s
- is input data
- unsigned long n
- if -1 implies strlen
- unsigned int* ip
- receives last/right ip on success if not NULL
- unsigned short* port
- receives port on success if not NULL
- int
- 0 on success or -1 on failure
ParseHost
Parses HTTP Host header.
The input is ISO-8859-1 which is transcoded to UTF-8. Therefore we assume percent-encoded bytes are expressed as UTF-8. Returned values might contain things like NUL characters, C0, and C1 control codes. UTF-8 isn't checked for validity and may contain overlong values. Absent can be discerned from empty by checking if the pointer is set.
This function turns an HTTP header HOST[:PORT] into two strings, one for host and the other for port. You may then call IsAcceptableHost() and IsAcceptablePort() to see if they are valid values. After that a function like sscanf() can be used to do the thing you likely thought this function would do.
This function doesn't initialize h since it's assumed this will be called conditionally after ParseRequestUri() if the host is absent. Fields unrelated to authority won't be impacted by this function.
- const char* s
- is value like
127.0.0.1
orfoo.example:80
- unsigned long n
- is byte length and -1 implies strlen
- struct Url* h
- is needs to be initialized by caller
- char*
- memory backing UrlView needing free
ParseHostsTxt
Parses HOSTS.TXT contents.
Hostnames were invented by Peggy Karp; her format looks like this:
# this is a comment # IP CANON [ALT...] 203.0.113.1 lol.example. lol 203.0.113.2 cat.example. cat
- struct HostsTxt* ht
- struct FILE* f
- is the file content; see fopen() and fmemopen()
- int
- 0 on success, or -1 w/ errno
ParseHttpDateTime
Parses HTTP timestamp, e.g.
Sun, 04 Oct 2020 19:50:10 GMT
- const char* p
- unsigned long n
- if -1 implies strlen
- long
- seconds from unix epoch
ParseHttpMessage
Parses HTTP request or response.
This parser is responsible for determining the length of a message and slicing the strings inside it. Performance is attained using perfect hash tables. No memory allocation is performed for normal messages. Line folding is forbidden. State persists across calls so that fragmented messages can be handled efficiently. A limitation on message size is imposed to make the header data structures smaller.
This parser assumes ISO-8859-1 and guarantees no C0 or C1 control codes are present in message fields, with the exception of tab. Please note that fields like kHttpStateUri may use UTF-8 percent encoding. This parser doesn't care if you choose ASA X3.4-1963 or MULTICS newlines.
kHttpRepeatable defines which standard header fields are O(1) and which ones may have comma entries spilled over into xheaders. For most headers it's sufficient to simply check the static slice. If r->headers[kHttpFoo].a is zero then the header is totally absent.
This parser has linear complexity. Each character only needs to be considered a single time. That's the case even if messages are fragmented. If a message is valid but incomplete, this function will return zero so that it can be resumed as soon as more data arrives.
This parser takes about 400 nanoseconds to parse a 403 byte Chrome HTTP request under MODE=rel on a Core i9 which is about three cycles per byte or a gigabyte per second of throughput per core.
- struct HttpMessage* r
- const char* p
- unsigned long n
- const char* p
- int
ParseHttpRange
Parses HTTP Range request header.
Here are some example values:
Range: bytes=0- (everything) Range: bytes=0-499 (first 500 bytes) Range: bytes=500-999 (second 500 bytes) Range: bytes=-500 (final 500 bytes) Range: bytes=0-0,-1 (first and last and always) Range: bytes=500-600,601-999 (overlong but legal)
- const char* p
- unsigned long n
- long resourcelength
- long* out_start
- long* out_length
- unsigned long n
- _Bool
ParseIp
Parse IPv4 host address.
- const char* s
- unsigned long n
- if -1 implies strlen
- long
- -1 on failure, otherwise 32-bit host-order unsigned integer
ParseParams
Parses HTTP POST key-value params.
These are similar to the parameters found in a Request-URI, except
usually submitted via an HTTP POST request. We translate +
into
space. The mime type is application/x-www-form-urlencoded.
This parser is charset agnostic. Returned values might contain things like NUL characters, NUL, control codes, and non-canonical encodings. Absent can be discerned from empty by checking if the pointer is set.
There's no failure condition for this routine. This is a permissive parser that doesn't impose character restrictions beyond what is necessary for parsing.
- const char* s
- is value like
foo=bar&x=y&z
- unsigned long n
- is byte length and -1 implies strlen
- struct params* h
- must be zeroed by caller and this appends if reused
- char*
- UrlView memory with same n needing free (h.p needs free too)
ParsePromises
Parses the arguments to pledge() into a bitmask.
- const char* promises
- unsigned long* out
- int
- 0 on success, or -1 if invalid
ParseResolvConf
Parses /etc/resolv.conf file.
The content of the file usually looks like this:
nameserver 8.8.8.8 nameserver 8.8.4.4
- struct ResolvConf* resolv
- points to a ResolvConf object, which should be zero initialized by the caller; or if it already contains items, this function will append
- struct FILE* f
- is an open stream with file content
- int
- number of nameservers appended, or -1 w/ errno
ParseUrl
Parses URL.
This parser is charset agnostic. Percent encoded bytes are decoded for all fields (with the exception of scheme). Returned values might contain things like NUL characters, spaces, control codes, and non-canonical encodings. Absent can be discerned from empty by checking if the pointer is set.
There's no failure condition for this routine. This is a permissive
parser. This doesn't normalize path segments like .
or ..
so use
IsAcceptablePath() to check for those. No restrictions are imposed
beyond that which is strictly necessary for parsing. All the s
that is provided will be consumed to the one of the fields. Strict
conformance is enforced on some fields more than others, like scheme,
since it's the most non-deterministically defined field of them all.
Please note this is a URL parser, not a URI parser. Which means we support everything the URI spec says we should do except for the things we won't do, like tokenizing path segments into an array and then nesting another array beneath each of those for storing semicolon parameters. So this parser won't make SIP easy. What it can do is parse HTTP URLs and most URIs like s:opaque, better in fact than most things which claim to be URI parsers.
- const char* s
- is value like
/hi?x=y&z
orhttp://a.example/hi#x
- unsigned long n
- is byte length and -1 implies strlen
- struct Url* h
- is assumed to be uninitialized
- int f
- is flags which may have:
FLAGS_PLUS
to turn+
into space in query paramsFLAGS_LATIN1
to transcode ISO-8859-1 input into UTF-8
- char*
- memory backing UrlView needing free (and h.params.p too)
PascalifyDnsName
Writes dotted hostname to DNS message wire.
The wire format is basically a sequence of Pascal strings, for each label in the name. We only do enough validation to maintain protocol invariants.
- unsigned char* buf
- unsigned long size
- const char* name
- unsigned long size
- is a dotted NUL-terminated hostname string
- int
- bytes written (excluding NUL) or -1 w/ errno
pause
Waits for signal.
This suspends execution until an unmasked signal is delivered. If the signal delivery kills the process, this won't return. The signal mask of the current thread is used. If a signal handler exists, this shall return after it's been invoked.
This function is equivalent to:
select(0, 0, 0, 0, 0);However this has a tinier footprint and better logging.
- int
- -1 w/ errno set to EINTR
pclose
Closes stream created by popen().
This function may be interrupted or cancelled, however it won't actually return until the child process has terminated. Thus we always release the resource, and errors are purely advisory.
- struct FILE* f
- int
- termination status of subprocess, or -1 w/ ECHILD
pcmpgtb
Compares signed 8-bit integers w/ greater than predicate.
Note that operands can be xor'd with 0x80 for unsigned compares.
- char* a
- const char* b
- const char* c
- const char* b
- void
pcmpgtw
Compares signed 16-bit integers w/ greater than predicate.
- short* a
- const short* b
- const short* c
- const short* b
- void
perror
Writes error messages to standard error.
- const char* thing
- void
pipe
Creates file-less file descriptors for interprocess communication.
- int* pipefd
- int
- 0 on success or -1 w/ errno
pipe2
Creates file-less file descriptors for interprocess communication.
- int* pipefd
- is used to return (reader, writer) file descriptors
- int flags
- can have O_CLOEXEC or O_DIRECT or O_NONBLOCK
- int
- 0 on success, or -1 w/ errno and pipefd isn't modified
RLIMIT_NOFILE
has been reached
pivot_root
Changes root mount.
- const char* new_root
- const char* put_old
- int
pmaddubsw
Multiplies bytes and adds adjacent results w/ short saturation.
๐คแตข โ CLAMP[ ๐โแตข๐โแตข + ๐โโแตขโโโ๐โโแตขโโโ ]
- short* w
- const unsigned char* b
- const char* c
- const unsigned char* b
- void
pmovmskb
Turns result of byte comparison into bitmask.
- const unsigned char* p
- unsigned int
pmulhrsw
Multiplies Q15 numbers.
- short* a
- const short* b
- const short* c
- const short* b
- void
poll
Waits for something to happen on multiple file descriptors at once.
Warning: XNU has an inconsistency with other platforms. If you have pollfds with fdโฅ0 and none of the meaningful events flags are added e.g. POLLIN then XNU won't check for POLLNVAL. This matters because one of the use-cases for poll() is quickly checking for open files.
Note: Polling works best on Windows for sockets. We're able to poll input on named pipes. But for anything that isn't a socket, or pipe with POLLIN, (e.g. regular file) then POLLIN/POLLOUT are always set into revents if they're requested, provided they were opened with a mode that permits reading and/or writing.
Note: Windows has a limit of 64 file descriptors and ENOMEM with -1 is returned if that limit is exceeded. In practice the limit is not this low. For example, pollfds with fd<0 don't count. So the caller could flip the sign bit with a short timeout, to poll a larger set.
- struct pollfd* fds
- unsigned long nfds
- int timeout_ms
- unsigned long nfds
- if 0 means don't wait and -1 means wait forever
- int
- number of items fds whose revents field has been set to
nonzero to describe its events, or 0 if the timeout elapsed,
or -1 w/ errno
- fds[๐].revents is always zero initializaed and then will be populated with POLL{IN,OUT,PRI,HUP,ERR,NVAL} if something was determined about the file descriptor
popcnt
Returns number of bits set in integer.
- unsigned long x
- unsigned long
popen
Spawns subprocess and returns pipe stream.
The returned resource needs to be passed to pclose().
This embeds the Cosmopolitan Command Interpreter which provides Bourne-like syntax on all platforms including Windows.
- const char* cmdline
- is a unix shell script
- const char* mode
- can be:
"r"
for reading from subprocess standard output"w"
for writing to subprocess standard input
- struct FILE*
mode
is invalid or specifies read+write
RLIMIT_NOFILE
has been reached
RLIMIT_NPROC
was exceeded
posix_fadvise
Drops hints to O/S about intended I/O behavior.
It makes a huge difference. For example, when copying a large file, it can stop the system from persisting GBs of useless memory content.
- int fd
- long offset
- long len
- long offset
- 0 means until end of file
- int advice
- can be POSIX_FADV_SEQUENTIAL, POSIX_FADV_RANDOM, etc.
- int
- 0 on success, or errno on error
fd
isn't a valid file descriptor
advice
is invalid or len
is huge
fd
refers to a pipe
posix_madvise
Advises kernel about memory intentions, the POSIX way.
- void* addr
- unsigned long len
- int advice
- unsigned long len
- int
- 0 on success, or errno on error
posix_memalign
Allocates aligned memory, the POSIX way.
Allocates a chunk of n bytes, aligned in accord with the alignment argument. Differs from memalign() only in that it:
- Assigns the allocated memory to *pp rather than returning it
- Fails and returns EINVAL if the alignment is not a power of two
- Fails and returns ENOMEM if memory cannot be allocated
- void** pp
- receives pointer, only on success
- unsigned long alignment
- must be 2-power multiple of sizeof(void *)
- unsigned long bytes
- is number of bytes to allocate
- int
- return 0 or EINVAL or ENOMEM w/o setting errno
posix_openpt
Opens new pseudo teletypewriter.
- int flags
- int
- fd of master pty, or -1 w/ errno
- file descriptor, or -1 w/ errno
posix_spawn
Spawns process, the POSIX way.
This function provides an API for vfork() that's intended to be less terrifying to the uninitiated, since it only lets you define actions that are @vforksafe. This function requires TLS not be disabled.
- int* pid
- if non-null shall be set to child pid on success
- const char* path
- is resolved path of program which is not
$PATH
searched - struct _posix_faction** file_actions
- specifies close(), dup2(), and open() operations
- struct _posix_spawna** attrp
- specifies signal masks, user ids, scheduling, etc.
- char** argv
- char** envp
- is environment variables, or
environ
if null
- int
- 0 on success or error number on failure
$PATH
searching
posix_spawn_file_actions_addclose
Add a close action to object.
- struct a** file_actions
- was initialized by posix_spawn_file_actions_init()
- int fildes
- int
- 0 on success, or errno on error
posix_spawn_file_actions_adddup2
Add a dup2 action to object.
- struct a** file_actions
- was initialized by posix_spawn_file_actions_init()
- int fildes
- int newfildes
- int
- 0 on success, or errno on error
posix_spawn_file_actions_addopen
Add an open action to object.
- struct a** file_actions
- was initialized by posix_spawn_file_actions_init()
- int fildes
- const char* path
- will be safely copied
- int oflag
- unsigned int mode
- int
- 0 on success, or errno on error
posix_spawn_file_actions_destroy
Destroys posix_spawn() file actions list.
This function is safe to call multiple times.
- struct a** file_actions
- was initialized by posix_spawn_file_actions_init()
- int
- 0 on success, or errno on error
posix_spawn_file_actions_init
Initializes posix_spawn() file actions list.
- struct a** file_actions
- will need posix_spawn_file_actions_destroy()
- int
- 0 on success, or errno on error
posix_spawnattr_destroy
Destroys posix_spawn() attributes object.
This function is safe to call multiple times.
- struct _posix_spawna** attr
- was initialized by posix_spawnattr_init()
- int
- 0 on success, or errno on error
posix_spawnattr_getflags
Gets posix_spawn() flags.
- struct _posix_spawna** attr
- was initialized by posix_spawnattr_init()
- short* flags
- int
- 0 on success, or errno on error
posix_spawnattr_getschedparam
Gets scheduler parameter that'll be used for spawned process.
If the setter wasn't called then this function will return the scheduling parameter of the current process.
- struct _posix_spawna** attr
- was initialized by posix_spawnattr_init()
- struct schedparam* schedparam
- receives the result
- int
- 0 on success, or errno on error
posix_spawnattr_getschedpolicy
Gets scheduler policy that'll be used for spawned process.
If the setter wasn't called then this function will return the scheduling policy of the current process.
- struct _posix_spawna** attr
- was initialized by posix_spawnattr_init()
- int* schedpolicy
- receives the result
- int
- 0 on success, or errno on error
posix_spawnattr_getsigdefault
Retrieves which signals will be restored to SIG_DFL
.
- struct _posix_spawna** attr
- struct sigdefault* sigdefault
- int
- 0 on success, or errno on error
posix_spawnattr_getsigmask
Gets signal mask for sigprocmask() in child process.
If the setter wasn't called then this function will return the scheduling parameter of the current process.
- struct _posix_spawna** attr
- struct sigdefault* sigmask
- int
- 0 on success, or errno on error
posix_spawnattr_init
Initialize posix_spawn() attributes object with default values.
- struct _posix_spawna** attr
- needs to be passed to posix_spawnattr_destroy() later
- int
- 0 on success, or errno on error
posix_spawnattr_setflags
Sets posix_spawn() flags.
Setting these flags is needed in order for the other setters in this function to take effect. If a flag is known but unsupported by the host platform, it'll be silently removed from the flags. You can check for this by calling the getter afterwards.
- struct _posix_spawna** attr
- was initialized by posix_spawnattr_init()
- short flags
- may have any of the following
POSIX_SPAWN_RESETIDS
POSIX_SPAWN_SETPGROUP
POSIX_SPAWN_SETSIGDEF
POSIX_SPAWN_SETSIGMASK
POSIX_SPAWN_SETSCHEDPARAM
POSIX_SPAWN_SETSCHEDULER
POSIX_SPAWN_SETSID
- int
- 0 on success, or errno on error
flags
has invalid bits
posix_spawnattr_setschedparam
Specifies scheduler parameter override for spawned process.
Scheduling parameters are inherited by default. Use this to change it.
- struct _posix_spawna** attr
- was initialized by posix_spawnattr_init()
- struct schedparam* schedparam
- receives the result
- int
- 0 on success, or errno on error
posix_spawnattr_setschedpolicy
Specifies scheduler policy override for spawned process.
Scheduling policies are inherited by default. Use this to change it.
- struct _posix_spawna** attr
- was initialized by posix_spawnattr_init()
- int schedpolicy
- receives the result
- int
- 0 on success, or errno on error
posix_spawnattr_setsigdefault
Specifies which signals should be restored to SIG_DFL
.
- struct _posix_spawna** attr
- struct sigdefault* sigdefault
- int
- 0 on success, or errno on error
posix_spawnattr_setsigmask
Specifies signal mask for sigprocmask() in child process.
Signal masks are inherited by default. Use this to change it.
- struct _posix_spawna** attr
- struct sigdefault* sigmask
- int
- 0 on success, or errno on error
posix_spawnp
Spawns process the POSIX way w/ PATH search.
- int* pid
- is non-NULL and will be set to child pid in parent
- const char* path
- of executable is PATH searched unless it contains a slash
- ANONYMOUS-STRUCT** file_actions
- ANONYMOUS-STRUCT** attrp
- char** argv
- char** envp
- ANONYMOUS-STRUCT** attrp
- int
- 0 on success or error number on failure
pow
Returns ๐ฅ^๐ฆ.
- double x
- double y
- double
powf
Returns ๐ฅ^๐ฆ.
- float x
- float y
- float
ppoll
Waits for something to happen on multiple file descriptors at once.
This function is the same as saying:
sigset_t old; sigprocmask(SIG_SETMASK, sigmask, &old); poll(fds, nfds, timeout); sigprocmask(SIG_SETMASK, old, 0);Except it happens atomically when the kernel supports doing that. On kernel such as XNU and NetBSD which don't, this wrapper will fall back to using the example above. Consider using pselect() which is atomic on all supported platforms.
The Linux Kernel modifies the timeout parameter. This wrapper gives
it a local variable due to POSIX requiring that timeout
be const.
If you need that information from the Linux Kernel use sys_ppoll().
- struct pollfd* fds
- unsigned long nfds
- struct __ts* timeout
- unsigned long nfds
- if null will block indefinitely
- ANONYMOUS-STRUCT* sigmask
- may be null in which case no mask change happens
- int
pread
Reads from file at offset.
This function never changes the current position of fd
.
- int fd
- is something open()'d earlier, noting pipes might not work
- void* buf
- is copied into, cf. copy_file_range(), sendfile(), etc.
- unsigned long size
- in range [1..0x7ffff000] is reasonable
- long offset
- is bytes from start of file at which read begins
- long
- [1..size] bytes on success, 0 on EOF, or -1 w/ errno; with exception of size==0, in which case return zero means no error
fd
isn't seekable
offset
is negative
fd
isn't an open file descriptor
preadv
Reads with maximum generality.
- int fd
- struct iovec* iov
- int iovlen
- long off
- struct iovec* iov
- long
- number of bytes actually read, or -1 w/ errno
__printargs
Prints lots of information about this process, e.g.
__printargs("");This is called automatically in MODE=dbg if