objects
__assert_disable functions
a64l |
a64lConverts base64 to 32-bit integer, the posix way.
@param
@return
@see
l64a() for inverse
@see
DecodeBase64()
@see libc/str/a64l.c
abortTerminates program abnormally. This function first tries to trigger your SIGABRT handler. If there isn't one or execution resumes, then abort() terminates the program using an escalating variety methods of increasing brutality. acceptCreates client socket file descriptor for incoming connection.
@param
@return
@asyncsignalsafe
@restartable
(unless SO_RCVTIMEO)
@see libc/sock/accept.c
accept4Creates client socket file descriptor for incoming connection.
@param
@return
@asyncsignalsafe
@restartable
(unless SO_RCVTIMEO)
@see libc/sock/accept4.c
accessChecks if effective user can access path in particular ways.
@param
@return
@asyncsignalsafe
@see libc/calls/access.c
acosReturns arc cosine of 𝑥.
@param
@return
@see libc/tinymath/acos.c
acosfReturns arc cosine of 𝑥.
@param
@return
acoshReturns inverse hyperbolic cosine of 𝑥.
@param
@return
@define
acosh(x) = log(x + sqrt(x*x-1))
acoshfReturns inverse hyperbolic cosine of 𝑥.
@param
@return
@define
acosh(x) = log(x + sqrt(x*x-1))
acoslReturns arc cosine of 𝑥.
@param
@return
@define
atan2(fabs(sqrt((1-𝑥)*(1+𝑥))),𝑥)
@domain
-1 ≤ 𝑥 ≤ 1
_addrusageAccumulates resource statistics in
@param
@return
__addvdi3Returns 𝑥+𝑦, aborting on overflow.
@param
@return
@see
-ftrapv
__addvsi3Returns 𝑥+𝑦, aborting on overflow.
@param
@return
@see
-ftrapv
__addvti3Returns 𝑥+𝑦, aborting on overflow.
@param
@return
@see
-ftrapv
adler32Updates 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.
@return
adler32_combineCombine 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.
@return
alarmAsks for single-shot SIGALRM to be raise()'d after interval.
@param
@return
@see
setitimer()
@asyncsignalsafe
@see libc/calls/alarm.c
aligned_allocSame as memalign(a, n) but requires IS2POW(a).
@param
@return
@throw
EINVAL if !IS2POW(a)
@see
pvalloc()
@threadsafe
appenddAppends 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.
@param
@return
@see
appendz(b).i to get buffer length
@note
20% faster than appends()
@see libc/stdio/appendd.c
appendfAppends formatted string to buffer, e.g. char *b = 0; appendf(&b, "hello %d\n", 123); free(b);
@param
@return
@see
appendz(b).i to get buffer length
@note
O(1) amortized buffer growth
@see libc/stdio/appendf.c
appendHostInfo
@param
@return
appendrResets 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.
@param
@return
@see
appendz(b).i to get buffer length
@see libc/stdio/appendr.c
AppendResourceReportGenerates process resource usage report.
@param
@return
appendsAppends 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.
@param
@return
@see
appendz(b).i to get buffer length
@note
2x faster than appendf()
@see libc/stdio/appends.c
appendwAppends 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.
@param
@return
@see
appendz(b).i to get buffer length
@see libc/stdio/appendw.c
appendzReturns size of append buffer.
@param
@return
@see libc/stdio/appendz.c
__arena_popPops memory arena. This pops the most recently created arena, freeing all the memory that was allocated between the push and pop arena calls. If this is the last arena on the stack, then the old malloc hooks are restored.
@return
@see
__arena_push()
@see libc/mem/arena.c
__arena_pushPushes memory arena. This allocator gives a ~3x performance boost over dlmalloc, mostly because it isn't thread safe and it doesn't do defragmentation. Calling this function will push a new arena. It may be called multiple times from the main thread recursively. The first time it's called, it hooks all the regular memory allocation functions. Any allocations that were made previously outside the arena, will be passed on to the previous hooks. Then, the basic idea, is rather than bothering with free() you can just call __arena_pop() to bulk free. Arena allocations also have a slight size advantage, since 32-bit pointers are always used. The maximum amount of arena memory is 805,175,296 bytes.
@return
@see
__arena_pop()
@see libc/mem/arena.c
__asan_checkChecks validity of memory range. Normally this is abstracted by the compiler.
@param
@return
@note
this takes 6 picoseconds per byte
@see libc/intrin/asan.c
asinReturns arc sine of 𝑥.
@param
@return
@see libc/tinymath/asin.c
asinfReturns arc sine of 𝑥.
@param
@return
asinhReturns inverse hyperbolic sine of 𝑥.
@param
@return
@define
asinh(x) = sign(x)*log(|x|+sqrt(x*x+1)) ~= x - x^3/6 + o(x^5)
asinhfReturns inverse hyperbolic sine of 𝑥.
@param
@return
@define
asinh(x) = sign(x)*log(|x|+sqrt(x*x+1)) ~= x - x^3/6 + o(x^5)
asinhlReturns inverse hyperbolic sine of 𝑥.
@param
@return
@define
asinh(x) = sign(x)*log(|x|+sqrt(x*x+1)) ~= x - x^3/6 + o(x^5)
asinlReturns arc sine of 𝑥.
@param
@return
@define
atan2(𝑥,sqrt((1-𝑥)*(1+𝑥)))
@domain
-1 ≤ 𝑥 ≤ 1
asprintfFormats string, allocating needed memory.
@param
@return
@see
xasprintf() for a better API
@threadsafe
@see libc/mem/asprintf.c
__assert_failHandles failure of assert() macro.
@param
@return
atanReturns arc tangent of 𝑥.
@param
@return
atan2lReturns arc tangent of 𝑦/𝑥.
@param
@return
atanfReturns arc tangent of 𝑥.
@param
@return
atanhReturns inverse hyperbolic tangent of 𝑥.
@param
@return
@define
x ? log1p(2 * x / (1 - x)) / 2 : x
atanhfReturns inverse hyperbolic tangent of 𝑥.
@param
@return
@define
x ? log1p(2 * x / (1 - x)) / 2 : x
atanhlReturns inverse hyperbolic tangent of 𝑥.
@param
@return
@define
x ? log1p(2 * x / (1 - x)) / 2 : x
atanlReturns arc tangent of 𝑥. 1 3 1 5 1 7 1 9 1 11 atan(𝑥) = 𝑥 - - 𝑥 + - 𝑥 - - 𝑥 + - 𝑥 - -- 𝑥 ... 3 5 7 9 11
@param
@return
@define
atan(𝑥) = Σₙ₌₀₋∞ 2²ⁿ(𝑛!)²/(𝟸𝑛+𝟷)!(𝑥²ⁿ⁺¹/(𝑥²+𝟷)ⁿ⁺¹)
atexitAdds 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.
@param
@return
@see libc/intrin/atexit.c
atforkRegisters function to be called by fork() in child.
@param
@return
@note
vfork() won't invoke callbacks
@asyncsignalsafe
@see libc/calls/atfork.c
atoiDecodes 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𝑛𝑠
@param
@return
@see libc/fmt/atoi.c
atolDecodes decimal integer from ASCII string.
@param
@return
@see libc/fmt/atol.c
atollDecodes decimal number from ASCII string.
@param
@return
@see libc/fmt/atoll.c
AttachDebuggerLaunches 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.
@param
@return
@note
this is called via eponymous spinlock macro wrapper
ballocAllocates page-guarded buffer.
@param
@return
@see
ralloc()
@deprecated
@see libc/mem/balloc.c
basenameReturns 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.
@param
@return
@see
dirname()
@see
SUSv2
@see libc/fmt/basename.c
bcopyMoves memory the BSD way. Please use memmove() instead. Note the order of arguments.
@param
@return
@see libc/intrin/bcopy.c
bextraExtracts bit field from array.
@param
@return
@see libc/bits/bextra.c
bfreeFrees memory return by balloc().
@param
@return
@deprecated
@see libc/mem/bfree.c
bindAssigns 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, &in, sizeof(in));
@param
@return
@error
ENETDOWN, EPFNOSUPPORT, etc.
@asyncsignalsafe
@see libc/sock/bind.c
bingTurns 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.
@param
@return
@see
unbing() for inverse
@see libc/fmt/bing.c
BLAKE2B256Computes 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
@param
@return
@see libc/str/blake2.c
BLAKE2B256_Process
@param
@return
@see libc/str/blake2.c
BLAKE2B256_Update
@param
@return
@see libc/str/blake2.c
brkSets end of data section. This can be used to allocate and deallocate memory. It won't conflict with malloc() and mmap(NULL, ...) allocations since APE binaries load the image at 0x400000 and does allocations starting at 0x100080000000. You should consult _end, or call sbrk(NULL), to figure out where the existing break is first.
@param
@return
@see
mmap(), sbrk(), _end
@see libc/runtime/brk.c
bsearchSearches sorted array for exact item in logarithmic time.
@param
@return
@see
bsearch_r(), bisectcarleft()
@see libc/alg/bsearch.c
bsearch_rSearches sorted array for exact item in logarithmic time.
@param
@return
@see
bsearch(), bisectcarleft()
@see libc/alg/bsearch_r.c
bsfReturns 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
@param
@return
@see libc/str/bsf.c
bsflReturns 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
@param
@return
@see libc/str/bsfl.c
bsfllReturns 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
@param
@return
@see libc/str/bsfll.c
bsrReturns 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
@param
@return
@see libc/str/bsr.c
bsr128Returns 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
@param
@return
@see
also treasure trove of nearly identical functions
bsrlReturns 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
@param
@return
@see libc/str/bsrl.c
bsrllReturns 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
@param
@return
@see libc/str/bsrll.c
bswap_64Byte-order conversion functions. Endianness is deceptively complicated to the uninitiated. Many helpers have been written by our top minds to address perceived difficulties. These ones got through standardization processes. To protect their legacy, all 19 functions have been implemented in just 17 bytes.
@return
@see
READ32LE(), READ32BE(), etc.
@asyncsignalsafe
bzeroSets 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
@param
@return
@asyncsignalsafe
@see libc/intrin/bzero.c
c16rtomb
@param
@return
@see libc/str/c16rtomb.c
c2rangrComputes transcedental trigonometry op w/ reactive scaling.
@param
@return
@clob
%ax
@see
sin,cos,tan
c32rtomb
@param
@return
@see libc/str/c32rtomb.c
callexitonterminationInstalls default handlers for friendly kill signals.
@param
@return
@see
ShowCrashReports()
@see libc/log/onkill.c
callocAllocates n * itemsize bytes, initialized to zero.
@param
@return
@note
overreliance on memalign is a sure way to fragment space
@see
dlcalloc()
@threadsafe
@see libc/mem/calloc.S
CategorizeIpClassifies IP address.
@param
@return
@see
GetIpCategoryName()
cbrtReturns cube root of 𝑥.
@param
@return
@see libc/tinymath/cbrt.S
cbrtlReturns cube root of 𝑥.
@param
@return
ceilReturns smallest integral not less than 𝑥.
@param
@return
@see
round(),rint(),nearbyint()
@see
vroundsd $_MM_FROUND_TO_POS_INF|_MM_FROUND_NO_EXC,%xmm0,%xmm0,%xmm0
@see libc/tinymath/ceil.S
ceilfReturns smallest integral not less than 𝑥.
@param
@return
@see
round(),rint(),nearbyint()
@see
vroundss $_MM_FROUND_TO_POS_INF|_MM_FROUND_NO_EXC,%xmm0,%xmm0,%xmm0
ceillReturns smallest integral not less than 𝑥.
@param
@return
cescapecEscapes byte for string literal. This turns stuff like (char)0xFF into \0377. The returned string is word-encoded, e.g. '\\'|'0'<<010|'3'<<020|etc.
@param
@return
@see
libc/nexgen32e/cescapec.c
chdirSets current directory. This does *not* update the
@param
@return
@asyncsignalsafe
@see
fchdir()
@see libc/calls/chdir.c
__check_failHandles failure of CHECK_xx() macros.
@param
@return
@see libc/log/checkfail.c
__check_fail_ndebugHandles failure of CHECK_xx() macros in -DNDEBUG mode. This handler (1) makes binaries smaller by not embedding source code; and therefore (2) less likely to leak sensitive information. This can still print backtraces with function names if the .com.dbg file is in the same folder.
@param
_check_sigchldChecks to see if SIGCHLD should be raised on Windows.
@return
@note
yoinked by fork-nt.c
CheckElfAddress
@param
@return
CheckForMemoryLeaksTests 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.
@return
@see libc/log/leaks.c
chmodChanges 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
@param
@return
@errors
ENOENT, ENOTDIR, ENOSYS
@asyncsignalsafe
@see
fchmod()
@see libc/calls/chmod.c
_chompMutates line to remove line-ending characters.
@param
@return
@see
getline
@see libc/str/chomp.c
_chomp16Mutates line to remove line-ending characters.
@param
@return
@see
getline
@see libc/str/chomp16.c
chownChanges owner and/or group of pathname.
@param
@return
@see
fchown() if pathname is already open()'d
@see
lchown() which does not dereference symbolic links
@see
/etc/passwd for user ids
@see
/etc/group for group ids
@asyncsignalsafe
@see libc/calls/chown.c
chrootChanges root directory.
@param
@return
@raise
ENOSYS on Windows
@see libc/calls/chroot.c
_classifypathClassifies 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 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
@param
@return
@see
"The Definitive Guide on Win32 to NT Path Conversion", James
Forshaw, Google Project Zero Blog, 2016-02-29
@see
"Naming Files, Paths, and Namespaces", MSDN 01/04/2021
clearerrClears error state on stream.
@param
@return
@see
clearerr_unlocked()
@threadsafe
__clk_tckReturns system clock ticks per second. The returned value is memoized. This function is intended to be
used via the The returned value is always greater than zero. It's usually 100 hertz which means each clock tick is 10 milliseconds long.
@return
clockReturns how much CPU program has consumed on time-sharing system.
@return
@see
clock_gettime()
@see libc/calls/clock.c
clock_gettimeReturns 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.
nowl l: 45𝑐 15𝑛𝑠 rdtsc l: 13𝑐 4𝑛𝑠 gettimeofday l: 44𝑐 14𝑛𝑠 clock_gettime l: 40𝑐 13𝑛𝑠 __clock_gettime l: 35𝑐 11𝑛𝑠 sys_clock_gettime l: 220𝑐 71𝑛𝑠
@param
@return
@error
EINVAL if clock isn't supported on this system
@see
strftime(), gettimeofday()
@asyncsignalsafe
__clock_gettime_getReturns pointer to fastest clock_gettime().
@param
@return
cloneCreates thread. 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.
The
static char tib[64]; __initialize_tls(tib); __install_tls(tib);If you want a main process TLS size that's larger call it manually. Once you've done the above and/or started creating your own threads you'll be able to access your tls thread information block, using
char *p = __get_tls(); printf("errno is %d\n", *(int *)(p + 0x3c));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.
@param
@return
@threadsafe
@see libc/runtime/clone.c
closeCloses file descriptor. This function may be used for file descriptors returned by functions like open, socket, accept, epoll_create, and landlock_create_ruleset. This function should never be called twice for the same file descriptor, regardless of whether or not an error happened. However that doesn't mean the error should be ignored.
@param
@return
@error
EINTR means a signal was received while closing in which case
close() does not need to be called again, since the fd will close
in the background
@asyncsignalsafe
@vforksafe
@see libc/calls/close.c
close_rangeCloses 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); } }This is supported on Linux 5.9+, FreeBSD, and OpenBSD. On FreeBSD, flags must be zero. On OpenBSD, we call closefrom(int) so last
should be -1 in order to get OpenBSD support, otherwise ENOSYS
will be returned. We also polyfill closefrom on FreeBSD since it's
available on older kernels.
On Linux, the following flags are supported:
@param
@return
@error
ENOSYS if not Linux 5.9+ / FreeBSD / OpenBSD
@error
EBADF on OpenBSD if
first is greater than highest fd
@error
EINVAL if flags are bad or first is greater than last
@error
EMFILE if a weird race condition happens on Linux
@error
EINTR possibly on OpenBSD
@error
ENOMEM on Linux maybe
close_sCloses file descriptor. The caller's variable is made -1 so subsequent calls are no-ops.
@param
@return
@asyncsignalsafe
closedirCloses directory object returned by opendir().
@param
@return
closefromCloses extra file descriptors, e.g. // close all non-stdio file descriptors if (closefrom(3) == -1) { for (int i = 3; i < 256; ++i) { close(i); } }
@param
@return
@error
ENOSYS if not Linux 5.9+ / FreeBSD / OpenBSD
@error
EBADF on OpenBSD if
first is greater than highest fd
@error
EINVAL if flags are bad or first is greater than last
@error
EMFILE if a weird race condition happens on Linux
@error
EINTR possibly on OpenBSD
@error
ENOMEM on Linux maybe
@note
supported on Linux 5.9+, FreeBSD 8+, and OpenBSD
CloseHandleCloses an open object handle.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
closelogCloses the file descriptor being used to write to the system logger Use of closelog is optional
@return
@asyncsignalsafe
@see libc/sock/syslog.c
CloseSymbolTableFrees symbol table.
@param
@return
cmpsbCompares 8-bit signed integers.
@param
@return
cmpslCompares 32-bit signed integers.
@param
@return
cmpsqCompares 64-bit signed integers.
@param
@return
cmpswCompares 16-bit signed integers.
@param
@return
cmpubCompares 8-bit unsigned integers.
@param
@return
cmpulCompares 32-bit unsigned integers.
@param
@return
cmpuqCompares 64-bit unsigned integers.
@param
@return
cmpuwCompares 16-bit unsigned integers.
@param
@return
_cmpxchgCompares and exchanges.
@param
@return
@see
_lockcmpxchg()
commandvResolves full pathname of executable.
@param
@return
@errno
ENOENT, EACCES, ENOMEM
@see
free(), execvpe()
@asyncsignalsafe
@vforksafe
commandvenvFinds 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); }
@param
@return
CompareDnsNamesCompares DNS hostnames in reverse lexicographical asciibetical order.
@param
@return
@see
test/libc/dns/comparednsnames_test.c (the code that matters)
compressCompresses 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.
@return
compress2Compresses 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.
@return
compressBoundReturns 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.
@return
connectConnects 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.
@param
@return
@asyncsignalsafe
@restartable
(unless SO_RCVTIMEO)
@see libc/sock/connect.c
_constructCalls global initialization functions.
@param
@return
copy_file_rangeTransfers data between files.
@param
@return
@see
sendfile() for seekable → socket
@see
splice() for fd ↔ pipe
@see libc/calls/splice.c
copyfdCopies data between file descriptors the slow way.
@param
@return
@see
copy_file_range() for file ↔ file
@see
sendfile() for seekable → socket
@see
splice() for fd ↔ pipe
@see libc/calls/copyfd.c
_copyfdCopies data between fds the old fashioned way. Even though Cosmopolitan polyfills copy_file_range() to fallback to doing this, it's useful to call this function in cases where you know it'd be more helpful to get the larger buffer size with read/write. Reads are allowed to be interrupted. Writes are uninterruptible. If we get an interrupt when partial data was written, we return the partial amount. Therefore the file descriptors are guaranteed to remain in a consistent state, provided EINTR is the only error. If n is 0 then 0 is returned and no i/o operations are performed.
@param
@return
@see libc/mem/copyfd.c
copyfileCopies file. This implementation goes 2x faster than the
@param
@return
copysignReturns 𝑥 with same sign as 𝑦.
@param
@return
copysignfReturns 𝑥 with same sign as 𝑦.
@param
@return
copysignlReturns 𝑥 with same sign as 𝑦.
@param
@return
cosReturns cosine of 𝑥.
@param
@return
@note
should take ~5ns
@see libc/tinymath/cos.c
coshReturns 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)
@param
@return
@see libc/tinymath/cosh.c
coshfReturns 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)
@param
@return
coshlReturns 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)
@param
@return
coslReturns cosine of 𝑥.
@param
@return
@domain
-(3π/8) < 𝑥 < 3π/8 for best accuracy
@see libc/tinymath/cosl.S
cosmoCosmopolitan runtime.
@param
@noreturn
@see libc/runtime/cosmo.S
_countbitsReturns population count of array.
@param
@return
@note
30gbps on Nehalem (Intel 2008+) otherwise 3gbps
cprojlProjects into Rienmann sphere.
@param
@return
@note
needs sse3
crc32Update 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();
@return
crc32_combineCombine 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.
@return
crc32_pclmulComputes Phil Katz CRC-32 w/ carryless multiply isa. This is support code that's abstracted by crc32_z().
@param
@return
@note
needs Westmere (c.2010) or Bulldozer (c.2011)
@see
“Fast CRC Computation for Generic Polynomials Using
PCLMULQDQ Instruction” V. Gopal, E. Ozturk, et al.,
2009, intel.ly/2ySEwL0
crc32_zComputes Phil Katz CRC-32 used by zip/zlib/gzip/etc. 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 0b100000100110000010001110110110111 bitreverse32(0x104c11db7)This implementation takes 32 picoseconds per byte or 30 gibibyte/s.
@param
@return
@see libc/str/crc32z.c
crc32cComputes 32-bit Castagnoli Cyclic Redundancy Check.
@param
@return
@note
Used by ISCSI, TensorFlow, etc.
@see libc/str/crc32c.c
crc32initGenerates lookup table for computing CRC-32 byte-by-byte. void crc32init(uint32_t table[256], uint32_t polynomial) { uint32_t d, i, r; for (d = 0; d < 256; ++d) { r = d; for (i = 0; i < 8; ++i) { r = r >> 1 ^ (r & 1 ? polynomial : 0); } table[d] = r; } }
@param
@return
@note
imposes ~300ns one-time cost
creatCreates new file, returning open()'d file descriptor. This function is shorthand for:
open(file, O_CREAT | O_WRONLY | O_TRUNC, mode)
@param
@return
@see
open(), touch()
@asyncsignalsafe
@see libc/calls/creat.c
CreateDirectoryCreates directory on the New Technology.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
CreateFileOpens file on the New Technology.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
CreateFileMappingCreates file mapping object on the New Technology.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
@see
MapViewOfFileEx()
CreateFileMappingNumaCreates file mapping object on the New Technology.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
@see
MapViewOfFileExNuma()
CreateNamedPipeCreates pipe.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
CreatePipeCreates anonymous pipe.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
CreateProcessCreates process on the New Technology.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
CreateSymbolicLinkCreates symbolic link on the New Technology.
@param
@return
@note
you need to elevate process privileges before calling this
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
CreateThreadOpens file on the New Technology.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
critbit0_allprefixedInvokes callback for all items with prefix.
@param
@return
@note
h/t djb and agl
critbit0_clearRemoves all items from 𝑡.
@param
@return
@note
h/t djb and agl
critbit0_containsReturns non-zero iff 𝑢 ∈ 𝑡.
@param
@return
@note
h/t djb and agl
critbit0_deleteRemoves 𝑢 from 𝑡.
@param
@return
@note
h/t djb and agl
critbit0_emplaceInserts 𝑢 into 𝑡 without copying.
@param
@return
@note
h/t djb and agl
critbit0_getReturns first item in 𝑡 with prefix 𝑢.
@param
@return
@note
h/t djb and agl
critbit0_insertInserts 𝑢 into 𝑡.
@param
@return
@note
h/t djb and agl
cryptEncrypts password the old fashioned way. The method of encryption depends on the first three chars of salt:
@param
@return
@see
third_party/argon2/
crypt_rEncrypts password the old fashioned way. The method of encryption depends on the first three chars of salt:
@param
@return
@see
third_party/argon2/
ctermidGenerates path of controlling terminal. This function always returns /dev/tty since that's supported by all supported platforms, and polyfilled on Windows.
@param
@return
@see libc/stdio/ctermid.c
cthread_attr_getguardsize
@param
@return
@see libc/thread/attr.c
cthread_attr_getstacksize
@param
@return
@see libc/thread/attr.c
cthread_attr_setdetachstate
@param
@return
@see libc/thread/attr.c
cthread_attr_setguardsize
@param
@return
@see libc/thread/attr.c
cthread_attr_setstacksize
@param
@return
@see libc/thread/attr.c
cthread_memory_wait32
@param
@return
@see libc/thread/wait.c
cthread_selfReturns thread descriptor of the current thread.
@return
@see libc/thread/self.c
cthread_sem_destroyDestroys semaphore.
@param
@return
@see libc/thread/sem.c
cthread_sem_initInitializes semaphore.
@param
@return
@see libc/thread/sem.c
cthread_sem_signalNotifies a thread waiting on semaphore.
@param
@return
@see libc/thread/sem.c
cthread_sem_waitWaits on semaphore.
@param
@return
@see libc/thread/sem.c
cthread_sem_wait_futexWaits on semaphore with kernel assistance.
@param
@return
@see libc/thread/sem.c
cthread_sem_wait_spinWaits on semaphore without kernel assistance.
@param
@return
@see libc/thread/sem.c
__cxa_atexitAdds 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().
@param
@return
@note
folks have forked libc in past just to unbloat atexit()
__cxa_finalizeTriggers 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.
@param
@return
__cxa_printexitsPrints global destructors.
@param
@return
_d2ld2Thunks double(*fn)(double,double) -> long double fn.
@param
@return
@note
100% negligible overhead
DecodeBase64Decodes base64 ascii representation to binary. This supports the following alphabets:
@param
@return
DecodeLatin1Decodes ISO-8859-1 to UTF-8.
@param
@return
_deferCalls 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.
@param
@return
@warning
do not return a gc()'d pointer
@warning
do not realloc() with gc()'d pointer
@warning
be careful about static keyword due to impact of inlining
@note
you should use -fno-omit-frame-pointer
@see libc/mem/gc.c
__deferAdds destructor to garbage shadow stack.
@param
@return
deflatedeflate 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:
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.
@return
deflateBounddeflateBound() 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.
@return
deflateCopySets 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.
@return
deflateEndAll dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output.
@return
deflateGetDictionaryReturns 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.
@return
deflateInitInitializes 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).
@return
deflateInit2This 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.
@return
deflateParamsDynamically 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.
@return
deflatePendingdeflatePending() 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.
@return
deflatePrimedeflatePrime() 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.
@return
deflateResetThis 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).
@return
deflateSetDictionaryInitializes 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.
@return
deflateSetHeaderProvides 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.
@return
deflateTuneFine 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.
@return
DeleteFileDeletes existing file.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
DescribeClockNameDescribes clock_gettime() clock argument.
@param
@return
DescribeFlags
@param
@return
DescribeOpenFlagsDescribes clock_gettime() clock argument.
@param
@return
DescribeRlimitNameDescribes setrlimit() / getrlimit() argument.
@param
@return
DescribeSchedParamDescribes clock_gettime() clock argument.
@param
@return
DescribeSchedPolicyDescribes clock_gettime() clock argument.
@param
@return
DescribeSockOptnameDescribes setsockopt() optname arguments.
@param
@return
DeserializeDnsHeaderSerializes DNS message h to wire.
@param
@return
@see libc/dns/dnsheader.c
DeviceIoControlDoes device file stuff on the New Technology.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
__dieAborts process after printing a backtrace. If a debugger is present then this will trigger a breakpoint.
@noreturn
@see libc/log/die.c
dirnameReturns directory portion of path, e.g. path │ dirname() │ basename() ───────────────────────────────── . │ . │ . .. │ . │ .. / │ / │ / usr │ . │ usr /usr/ │ / │ usr /usr/lib │ /usr │ lib
@param
@return
@see
basename()
@see
SUSv2
@see libc/fmt/dirname.c
__divmodti4Divides 128-bit signed integers w/ remainder.
@param
@return
@note
rounds towards zero
__divti3Divides 128-bit signed integers.
@param
@return
@note
rounds towards zero
djbsortD.J. Bernstein's outrageously fast integer sorting algorithm.
@param
@return
@see libc/str/djbsort.c
djbsort_avx2D.J. Bernstein's outrageously fast integer sorting algorithm.
@param
@return
@note
public domain
@see
en.wikipedia.org/wiki/Sorting_network
dlindependent_calloc
@param
@return
dlindependent_comalloc
@param
@return
dlmalloc_requires_more_vespene_gasAcquires more system memory for dlmalloc.
@param
@return
__dos2errnoTranslates 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.
@param
@return
DosDateTimeToUnixConverts MS-DOS timestamp to UNIX.
@param
@return
@note
type signature supports dates greater than 2100
@see
PKZIP, FAT
dprintfFormats string directly to file descriptor.
@param
@return
@see libc/calls/dprintf.c
dremremainder(𝑥,𝑦) means (𝑥 rem 𝑦) w/ rint()-style rounding.
@param
@return
@define
𝑥-rint(𝑥/𝑦)*𝑦
@see
fmod(), emod(), operator%
dsleepSleeps w/ higher precision.
@param
@return
@see libc/time/dsleep.c
dtimeReturns seconds since epoch w/ high-precision.
@param
@return
@see libc/calls/dtime.c
DumpHexcTurns data into "\x00..." string literal.
@param
@return
dupDuplicates file descriptor. The
@param
@return
@raise
EOPNOTSUPP if zipos file
@raise
EBADF if fd isn't open
@asyncsignalsafe
@vforksafe
@see libc/calls/dup.c
dup2Duplicates file descriptor, granting it specific number. The 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.
@param
@return
@raise
EBADF is oldfd isn't open
@raise
EBADF is newfd negative or too big
@raise
EINTR if a signal handler was called
@asyncsignalsafe
@vforksafe
@see libc/calls/dup2.c
dup3Duplicates file descriptor/handle. On Windows, we can't guarantee the desired file descriptor is used. We can however remap the standard handles (non-atomically) if their symbolic names are used.
@param
@return
@raise
EINVAL if flags has unsupported bits
@raise
EINVAL if newfd equals oldfd
@raise
EBADF is oldfd isn't open
@raise
EBADF is newfd negative or too big
@raise
EINTR if a signal handler was called
@see
dup(), dup2()
@see libc/calls/dup3.c
eaccessPerforms access() check using effective user/group id.
@param
@return
@see libc/calls/eaccess.c
EAGAINResource temporarily unavailable (e.g. SO_RCVTIMEO expired, too many processes, too much memory locked, read or write with O_NONBLOCK needs polling, etc.).
@type
@see libc/errno.h
EFAULTPointer passed to system call that would otherwise segfault.
@type
@see libc/errno.h
EfiMainEFI 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
@param
@return
@see
libc/dce.h
EncodeBase64Encodes binary to base64 ascii representation.
@param
@return
EncodeHttpHeaderValueEncodes HTTP header value. This operation involves the following:
@param
@return
EncodeLatin1Encodes UTF-8 to ISO-8859-1.
@param
@return
@error
EILSEQ means UTF-8 found we can't or won't re-encode
@error
ENOMEM means malloc() failed
EncodeUrlEncodes URL.
@param
@return
@see
ParseUrl()
@see net/http/encodeurl.c
endswithReturns true if s has suffix.
@param
@return
@see libc/str/endswith.c
endswith16Returns true if s has suffix.
@param
@return
ENOSYSSystem call unavailable.
@type
@note
kNtErrorInvalidFunction on NT
@see libc/errno.h
__ensurefdsGrows file descriptor array memory if needed.
@param
@return
@asyncsignalsafe
@threadsafe
__ensurefds_unlockedGrows file descriptor array memory if needed.
@param
@return
@see
libc/runtime/memtrack64.txt
@see
libc/runtime/memtrack32.txt
@asyncsignalsafe
epoll_createCreates new epoll instance.
@param
@return
@see libc/sock/epoll.c
epoll_create1Creates new epoll instance.
@param
@return
@see libc/sock/epoll.c
epoll_ctlControls 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().
@param
@return
@error
ENOTSOCK on Windows if fd isn't a socket :(
@see libc/sock/epoll.c
epoll_waitReceives socket events.
@param
@return
@norestart
@see libc/sock/epoll.c
erfcReturns complementary error function of 𝑥.
@param
@return
@see libc/tinymath/erf.c
err
@param
@noreturn
@see libc/log/err.c
__errnoGlobal 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.
@type
@see
libc/sysv/consts.sh
@see
libc/sysv/errfuns.h
@see
__errno_location() stable abi
@see libc/sysv/errno.c
__errno_locationReturns address of errno variable.
@return
@see
__initialize_tls()
@see
__install_tls()
errx
@param
@noreturn
@see libc/log/errx.c
_escapedosEscapes command so DOS can run it.
@param
@return
@see
Iain Patterson's NSSM for original code in public domain
@see libc/str/escapedos.c
EscapeFragmentEscapes URL fragment.
@param
@return
EscapeHostEscapes URL host or registry name.
@param
@return
EscapeHtmlEscapes HTML entities.
@param
@return
EscapeIpEscapes URL IP-literal. This is the same as EscapeHost except colon is permitted.
@param
@return
@see net/http/escapeip.c
EscapeJsStringLiteralEscapes UTF-8 data for JavaScript or JSON string literal. HTML entities and forward slash are escaped too for added safety. 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.
@param
@return
EscapeParamEscapes query/form name/parameter.
@param
@return
EscapePassEscapes URL password.
@param
@return
EscapePathEscapes URL path. This is the same as EscapePathSegment() except slash is allowed.
@param
@return
EscapeSegmentEscapes 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.
@param
@return
EscapeUrlEscapes URL component using generic table. This function is agnostic to the underlying charset. Always using UTF-8 is a good idea.
@param
@return
@see
kEscapeAuthority
@see
kEscapeIpLiteral
@see
kEscapePath
@see
kEscapePathSegment
@see
kEscapeParam
@see
kEscapeFragment
@see net/http/escapeurl.c
EscapeUrlViewEscapes URL component using generic table w/ stpcpy() api.
@param
@return
EscapeUserEscapes URL user name.
@param
@return
euidaccessPerforms access() check using effective user/group id.
@param
@return
execlExecutes program, with current environment. The current process is replaced with the executed one.
@param
@return
@asyncsignalsafe
@vforksafe
@see libc/calls/execl.c
execleExecutes program, with custom environment. The current process is replaced with the executed one.
@param
@return
@asyncsignalsafe
@vforksafe
@see libc/calls/execle.c
execlpExecutes program, with PATH search and current environment. The current process is replaced with the executed one.
@param
@return
@asyncsignalsafe
@vforksafe
@see libc/calls/execlp.c
execvReplaces process with specific program, using default environment.
@param
@return
@asyncsignalsafe
@vforksafe
@see libc/calls/execv.c
execveReplaces current process with program.
@param
@return
@asyncsignalsafe
@vforksafe
@see libc/calls/execve.c
execvpReplaces process, with path search, using default environment.
@param
@return
@asyncsignalsafe
@vforksafe
@see libc/calls/execvp.c
execvpeExecutes program, with path environment search. The current process is replaced with the executed one.
@param
@return
@asyncsignalsafe
@vforksafe
@see libc/calls/execvpe.c
_exitTerminates 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.
@param
exitExits 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 reeverse order
@param
_ExitTerminates 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.
@param
_Exit1Terminates thread with raw system call.
@param
expReturns 𝑒^x.
@param
@return
exp10Returns 10^x.
@param
@return
@see
pow(), exp()
exp10fReturns 10^x.
@param
@return
exp10lReturns 10^x.
@param
@return
exp2Returns 2^𝑥.
@param
@return
exp2fReturns 2^𝑥.
@param
@return
exp2lReturns 2^𝑥.
@param
@return
expfReturns 𝑒^x.
@param
@return
explReturns 𝑒^x.
@param
@return
@see libc/tinymath/expl.S
explicit_bzeroSets memory to zero w/ accompanying non-optimizing macro. This is intended for security-conscious applications.
@param
@return
expm1Returns 𝑒^x-1.
@param
@return
expm1fReturns 𝑒^x-1.
@param
@return
expm1lReturns 𝑒^𝑥-𝟷.
@param
@return
_f2ld2Thunks float(*fn)(float,float) -> long double fn.
@param
@return
@note
100% negligible overhead
fabsReturns absolute value of 𝑥.
@param
@return
@see libc/tinymath/fabs.S
fabsfReturns absolute value of 𝑥.
@param
@return
fabslReturns absolute value of 𝑥.
@param
@return
faccessatChecks if effective user can access path in particular ways.
@param
@return
@note
on Linux flags is only supported on Linux 5.8+
@asyncsignalsafe
fadviseDrops 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.
@param
@return
@see libc/calls/fadvise.c
fchdirSets current directory based on file descriptor. This does *not* update the
@param
@return
@see
open(path, O_DIRECTORY)
@asyncsignalsafe
@see libc/calls/fchdir.c
fchmodChanges file permissions via open()'d file descriptor.
@param
@return
@asyncsignalsafe
@see
chmod()
@see libc/calls/fchmod.c
fchmodatChanges 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));
@param
@return
@errors
ENOENT, ENOTDIR, ENOSYS
@asyncsignalsafe
@see
fchmod()
fchownChanges owner and/or group of file, via open()'d descriptor.
@param
@return
@see
/etc/passwd for user ids
@see
/etc/group for group ids
@raises
ENOSYS on Windows
@see libc/calls/fchown.c
fchownatChanges owner and/or group of path.
@param
@return
@see
chown(), lchown() for shorthand notation
@see
/etc/passwd for user ids
@see
/etc/group for group ids
@asyncsignalsafe
fcloseCloses standard i/o stream and its underlying thing.
@param
@return
@see
fclose_s()
@see libc/stdio/fclose.c
fclose_sCloses standard i/o stream and its underlying thing.
@param
@return
fcntlDoes things with file descriptor, via re-imagined hourglass api, 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 POSIX Advisory Locks, e.g.
CHECK_NE(-1, fcntl(zfd, F_SETLKW, &(struct flock){F_WRLCK})); // ... CHECK_NE(-1, fcntl(zfd, F_SETLK, &(struct flock){F_UNLCK}));Please be warned that locks currently do nothing on Windows since figuring out how to polyfill them correctly is a work in progress.
@param
@return
@asyncsignalsafe
@restartable
@see libc/calls/fcntl.c
fdatasyncBlocks until kernel flushes non-metadata buffers for fd to disk.
@param
@return
@see
sync(), fsync(), sync_file_range()
@see
__nosync to secretly disable
@asyncsignalsafe
fdopenAllocates stream object for already-opened file descriptor.
@param
@return
@error
ENOMEM
@see libc/stdio/fdopen.c
fdopendirCreates directory object for file descriptor.
@param
@return
@errors
ENOMEM and fd is closed
fegetroundReturns rounding mode. This implementation retrieves it from the x87 FPU control word.
@return
@see
fesetround() for changing this
__fentry__Function entry hook stub.
@return
@note
cc -pg -mfentry adds this to the start of every function
@see
libc/log/shadowargs.ncabi.c
@mode
long,legacy,real
feofReturns true if stream is in end-of-file state.
@param
@return
@see
feof_unlocked()
@threadsafe
@see libc/stdio/feof.c
feof_unlockedReturns true if stream is in end-of-file state.
@param
@return
@see
feof()
ferrorReturns nonzero if stream is in error state.
@param
@return
@see
ferror_unlocked(), feof()
@note
EOF doesn't count
@threadsafe
@see libc/stdio/ferror.c
ferror_unlockedReturns nonzero if stream is in error state.
@param
@return
@note
EOF doesn't count
@see
ferror(), feof()
fesetroundSets rounding mode. This configures the x87 FPU as well as SSE.
@param
@return
fflushBlocks until data from stream buffer is written out.
@param
@return
@threadsafe
@see libc/stdio/fflush.c
fflush_unlockedBlocks until data from stream buffer is written out.
@param
@return
ffsFinds lowest set bit in word. 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
@param
@return
@see
also treasure trove of nearly identical functions
@asyncsignalsafe
@see libc/nexgen32e/ffs.S
ffslFinds lowest set bit in word. 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
@param
@return
@see
also treasure trove of nearly identical functions
@asyncsignalsafe
ffsllFinds lowest set bit in word. 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
@param
@return
@see
also treasure trove of nearly identical functions
@asyncsignalsafe
fgetcReads byte from stream.
@param
@return
@see
fgetc_unlocked()
@threadsafe
@see libc/stdio/fgetc.c
fgetc_unlockedReads byte from stream.
@param
@return
@see
fgetc()
fgetlnRetrieves 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()
@param
@return
@see
getdelim()
@see libc/stdio/fgetln.c
fgetsReads 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().
@param
@return
@see
fgets_unlocked()
@threadsafe
@see libc/stdio/fgets.c
fgets_unlockedReads 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().
@param
@return
fgetwcReads UTF-8 character from stream.
@param
@return
@see
fgetwc_unlocked()
@threadsafe
@see libc/stdio/fgetwc.c
fgetwc_unlockedReads UTF-8 character from stream.
@param
@return
fgetwsReads 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().
@param
@return
@see
fgetws()
@threadsafe
@see libc/stdio/fgetws.c
fgetws_unlockedReads 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().
@param
@return
@see
fgetws()
filecmpCompares contents of files with memcmp().
@param
@return
@see libc/x/filecmp.c
fileexistsReturns 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.
@param
@return
filenoReturns file descriptor associated with stream.
@param
@return
@threadsafe
@see libc/stdio/fileno.c
fileno_unlockedReturns file descriptor associated with stream.
@param
@return
FindCloseFinds more files in directory.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
FindComBinaryReturns path of binary without debug information, or null.
@return
FindContentTypeReturns Content-Type for file extension.
@param
@return
FindDebugBinaryReturns path of binary with the debug information, or null.
@return
FindEmbeddedApeReturns offset of binary embedded inside binary. This can be used to load zip assets from an executable that hasn't
gone through the
@param
@return
FindFirstFileFinds first file in directory.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
FindNextFileFinds more files in directory.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
_firewallChecks outbound address against firewall. The goal is to keep local software local, by raising an error if our Makefile tries to talk to the Internet.
@param
@return
@see libc/sock/firewall.c
__fixupnewfdApplies file descriptor fixups on XNU or old Linux.
@param
@return
@see
__fixupnewsockfd() for socket file descriptors
__fixupnewsockfdApplies non-atomic file descriptor fixups on XNU or ancient Linux.
@param
@return
__flbfReturns nonzero if stream is line buffered.
@param
@return
@see libc/stdio/flbf.c
flockAcquires lock on file. Please note multiple file descriptors means multiple locks.
@param
@return
@restartable
@see libc/calls/flock.c
flockfileAcquires reentrant lock on stdio object, blocking if needed.
@param
@return
flogfWrites formatted message w/ timestamp to log.
@param
@return
@see
vflogf()
@see libc/log/flogf.c
floorReturns largest integral not greater than 𝑥.
@param
@return
floorfReturns largest integral not greater than 𝑥.
@param
@return
floorlReturns largest integral not greater than 𝑥.
@param
@return
FlushFileBuffersFlushes 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.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
@note
consider buying a ups
@see
FlushViewOfFile()
FlushViewOfFileSyncs 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.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
@note
consider buying a ups
@see
FlushFileBuffers()
fmaxReturns 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.
@param
@return
@see libc/tinymath/fmax.c
fmaxfReturns 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.
@param
@return
fmaxlReturns 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.
@param
@return
fmemopenOpens buffer as stream.
@param
@return
fminReturns 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.
@param
@return
@see libc/tinymath/fmin.c
fminfReturns minimum 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.
@param
@return
fminlReturns 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.
@param
@return
fmodfmod [sic] does (𝑥 rem 𝑦) w/ round()-style rounding.
@param
@return
@define
𝑥-trunc(𝑥/𝑦)*𝑦
@see
emod()
@see libc/tinymath/fmod.S
fmodlfmod [sic] does (𝑥 rem 𝑦) w/ round()-style rounding.
@param
@return
@define
𝑥-truncl(𝑥/𝑦)*𝑦
@see
emod()
@see libc/calls/fmodl.S
__fmtImplements {,v}{,s{,n},{,{,x}as},f,d}printf domain-specific language. Type Specifiers
@param
@return
@note
implementation detail of printf(), snprintf(), etc.
@see
printf() for wordier documentation
@note
netlib.org is so helpful
@asyncsignalsafe
if floating point isn't used
@vforksafe
if floating point isn't used
@see libc/fmt/fmt.c
__fmt_stoaConverts string to array. This is used by __fmt() to implement the %s and %c directives. The content outputted to the array is always UTF-8, but the input may be UTF-16 or UTF-32.
@param
@return
@see
__fmt()
@see libc/fmt/stoa.c
fnmatchMatches filename.
@param
@return
@see
glob()
FoldHeaderCollapses repeating headers onto a single line.
@param
@return
fopenOpens file as stream object.
@param
@return
@note
microsoft unilaterally deprecated this function lool
@see libc/stdio/fopen.c
forkCreates new process.
@return
@asyncsignalsafe
@see libc/runtime/fork.c
FormatBinary64Converts unsigned 64-bit integer to binary string.
@param
@return
FormatFlex64Formats integer using decimal or hexadecimal. This formats as int64 signed decimal. However it's a:
@param
@return
FormatHex64Converts unsigned 64-bit integer to hex string.
@param
@return
FormatHttpDateTimeFormats 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𝑛𝑠
@param
@return
@see
ParseHttpDateTime()
FormatInt32Converts signed 32-bit integer to string.
@param
@return
FormatInt64Converts signed 64-bit integer to string.
@param
@return
FormatInt64ThousandsConverts 64-bit integer to string w/ commas.
@param
@return
FormatMemorySizeRepresents size of memory readably.
@param
@return
FormatOctal32Converts unsigned 32-bit integer to octal string.
@param
@return
FormatOctal64Converts unsigned 64-bit integer to octal string.
@param
@return
FormatUint32Converts unsigned 32-bit integer to string.
@param
@return
FormatUint64Converts unsigned 64-bit integer to string.
@param
@return
FormatUint64ThousandsConverts unsigned 64-bit integer to string w/ commas.
@param
@return
fprintfFormats and writes text to stream.
@param
@return
@see
printf() for further documentation
@see libc/stdio/fprintf.c
fprintf_unlockedFormats and writes text to stream.
@param
@return
@see
printf() for further documentation
fpurgeDiscards contents of stream buffer.
@param
@return
@see libc/stdio/fpurge.c
fputcWrites byte to stream.
@param
@return
@threadsafe
@see libc/stdio/fputc.c
fputc_unlockedWrites byte to stream.
@param
@return
fputsWrites 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.
@param
@return
@threadsafe
@see libc/stdio/fputs.c
fputs_unlockedWrites 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.
@param
@return
fputwcWrites wide character to stream.
@param
@return
@threadsafe
@see libc/stdio/fputwc.c
fputwc_unlockedWrites wide character to stream.
@param
@return
fputwsWrites 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.
@param
@return
@threadsafe
@see libc/stdio/fputws.c
fputws_unlockedWrites 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.
@param
@return
freadReads data from stream.
@param
@return
@threadsafe
@see libc/stdio/fread.c
fread_unlockedReads data from stream.
@param
@return
freeFree 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. If p was not malloced or already freed, free(p) will by default cause the current program to abort.
@param
@return
@see
dlfree()
@threadsafe
@see libc/mem/free.S
freeaddrinfoFrees addresses returned by getaddrinfo().
@param
@return
@threadsafe
FreeHostsTxtFrees HOSTS.TXT data structure populated by ParseHostsTxt().
@param
@return
FreeResolvConfFrees resolv.conf data structure populated by ParseResolvConf().
@param
@return
freopenOverwrites 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.
@param
@return
@see libc/stdio/freopen.c
frexplSplits number normalized fraction and exponent.
@param
@return
fscanfDecodes 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.
@param
@return
@see
libc/fmt/vcscanf.c
@see libc/stdio/fscanf.c
fseekRepositions 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.
@param
@return
@returns
0 on success or -1 on error
@see libc/stdio/fseek.c
fseekoRepositions 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.
@param
@return
@returns
0 on success or -1 on error
@threadsafe
@see libc/stdio/fseeko.c
fseeko_unlockedRepositions 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.
@param
@return
@returns
0 on success or -1 on error
__fsetlockingDoes nothing and returns
@param
@return
fstatReturns information about file, via open()'d descriptor.
@param
@return
@raise
EBADF if
fd isn't a valid file descriptor
@raise
EIO if an i/o error happens while reading from file system
@raise
EOVERFLOW shouldn't be possible on 64-bit systems
@asyncsignalsafe
@see libc/calls/fstat.c
fstatatReturns information about thing.
@param
@return
@see
S_ISDIR(st.st_mode), S_ISREG()
@asyncsignalsafe
@vforksafe
@see libc/calls/fstatat.c
fsumAdds doubles in array.
@param
@return
@see libc/tinymath/fsum.c
fsyncBlocks until kernel flushes buffers for fd to disk.
@param
@return
@see
fdatasync(), sync_file_range()
@see
__nosync to secretly disable
@asyncsignalsafe
@see libc/calls/fsync.c
ftellReturns current position of stream.
@param
@return
@returns
current byte offset from beginning, or -1 w/ errno
@see libc/stdio/ftell.c
ftelloReturns current position of stream.
@param
@return
@returns
current byte offset from beginning, or -1 w/ errno
@threadsafe
@see libc/stdio/ftello.c
ftokConvert pathname and a project ID to System V IPC key.
@param
@return
@see libc/calls/ftok.c
__ftraceFunction tracing enabled state. After ftrace_install() has been called, the logging of C function
calls may be controlled by changing this variable. If By convention, functions wishing to disable function tracing for a short time period should say:
void foo() { --__ftrace; bar(); ++__ftrace; }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.
@type
@see libc/intrin/ftrace.c
ftrace_initEnables plaintext function tracing if The
@return
@see
libc/runtime/_init.S for documentation
ftracerPrints name of function being called. We insert CALL instructions that point to this function, in the prologues of other functions. We assume those functions behave according to the System Five NexGen32e ABI.
@return
ftruncateChanges size of file.
@param
@return
@asyncsignalsafe
ftrylockfileTries to acquire reentrant stdio object lock.
@param
@return
ftwWalks file tree.
@param
@return
@see
examples/walk.c for example
@see
nftw()
futimensSets atime/mtime on file descriptor. This function is the same as
@param
@return
@raise
ENOSYS on RHEL5
futimesSets atime/mtime on file descriptor.
@param
@return
@note
better than microsecond precision on most platforms
@see
fstat() for reading timestamps
@see libc/time/futimes.c
futimesatChanges last accessed/modified times on file.
@param
@return
@see
utimensat() which uses nanos
fwriteWrites data to stream.
@param
@return
@threadsafe
@see libc/stdio/fwrite.c
fwrite_unlockedWrites data to stream.
@param
@return
__gcInvokes 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.
@param
@return
@see
test/libc/runtime/gc_test.c
@see libc/nexgen32e/gc.S
_gcFrees 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)
@param
@return
@warning
do not return a gc()'d pointer
@warning
do not realloc() with gc()'d pointer
@warning
be careful about static keyword due to impact of inlining
@note
you should use -fno-omit-frame-pointer
@see libc/mem/gc.c
_gclongjmpJumps 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().
@param
@noreturn
@assume
system five nexgen32e abi conformant
@see
examples/ctrlc.c
gdbexecAttaches GDB temporarily, to do something like print a variable.
@param
@return
@see libc/log/gdbexec.c
gdtoa
@param
@return
GenerateConsoleCtrlEventSends signal to process group that shares console w/ calling process.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
get_current_dir_nameReturns current working directory. If the
@return
@threadsafe
__get_symbolReturns low index into symbol table for address.
@param
@return
__get_virtualReturns pointer to page table entry for page at virtual address. Additional page tables are allocated if needed as a side-effect.
@param
@return
getaddrinfoResolves address for internet name.
@param
@return
@threadsafe
getauxvalReturns auxiliary value, or zero if kernel didn't provide it. This function is typically regarded as a libc implementation detail; thus, the source code is the documentation.
@param
@return
@see
libc/sysv/consts.sh
@see
System Five Application Binary Interface § 3.4.3
@error
ENOENT when value not found
@asyncsignalsafe
_getauxvalReturns auxiliary value, or zero if kernel didn't provide it. This function is typically regarded as a libc implementation detail; thus, the source code is the documentation.
@param
@return
@see
libc/sysv/consts.sh
@see
System Five Application Binary Interface § 3.4.3
@error
ENOENT when value not found
@asyncsignalsafe
getcReads byte from stream.
@param
@return
@threadsafe
@see libc/stdio/getc.c
getc_unlockedReads byte from stream.
@param
@return
getcachesizeReturns CPU cache size.
@param
@return
GetCallerNameReturns name of function that called caller function.
@param
@return
getcharReads byte from stdin.
@return
@htreadsafe
@see libc/stdio/getchar.c
getcontextGets machine state.
@return
@note
please use longerjmp() and setlongerjmp() for fibers
@note
currently only gets general registers
@see
setcontext()
GetCpuCountReturns number of CPUs in system. On Intel systems with HyperThreading this will return the number of cores multiplied by two.
@return
getcwdReturns 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);
@param
@return
@error
ERANGE, EINVAL, ENOMEM
getdelimReads 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);
@param
@return
@note
this function will ignore EINTR if it occurs mid-line
@raises
EBADF if stream isn't open for reading
@see
fgetln(), getline(), _chomp(), gettok_r()
getdelim_unlockedReads string from unlocked stream.
@param
@return
@see
getdelim() for documentation
GetDosArgvTokenizes and transcodes Windows NT CLI args, thus avoiding CommandLineToArgv() schlepping in forty megs of dependencies.
@param
@return
@see
test/libc/dosarg_test.c
@see
libc/runtime/ntspawn.c
@note
kudos to Simon Tatham for figuring out quoting behavior
GetDosEnvironTranscodes NT environment variable block from UTF-16 to UTF-8.
@param
@return
getegidReturns effective group ID of calling process.
@return
@see libc/calls/getegid.c
GetElfDynSymbolTable
@param
@return
GetElfSectionAddress
@param
@return
GetElfSectionHeaderAddress
@param
@return
GetElfSectionName
@param
@return
GetElfSegmentHeaderAddress
@param
@return
GetElfString
@param
@return
GetElfStrs
@param
@return
GetElfSymbolTable
@param
@return
GetElfVirtualAddressRange
@param
@return
getentropyReturns random seeding bytes, the XNU/OpenBSD way.
@param
@return
@see
getrandom()
getenvReturns value of environment variable, or NULL if not found. Environment variables can store empty string on Unix but not Windows.
@param
@return
@note
should not be used after __cxa_finalize() is called
GetExitCodeProcessObtains exit code for process.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
GetFileAttributesGets file info on the New Technology.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
getfiledescriptorsizeDetermines size of open file. This function is equivalent to:
struct stat st; !fstat(fd, &st) ? st.st_size : -1Except faster on BSD/Windows and a much smaller link size.
@param
@return
@asyncsignalsafe
GetFileSizeReturns the byte length of file by path.
@param
@return
@see
getfiledescriptorsize()
getgidReturns 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.
@return
@asyncsignalsafe
@vforksafe
@see libc/calls/getuid.c
getgrgid_r
@param
@return
getgrnam_r
@param
@return
GetHostIpsReturns IP addresses of system. Normally return values will look like
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.
@return
gethostnameReturns name of host system, e.g. pheidippides.domain.example ^^^^^^^^^^^^
@param
@return
GetHostsTxtReturns hosts.txt map.
@return
@note
yoinking realloc() ensures there's no size limits
@threadsafe
GetHttpHeaderReturns small number for HTTP header, or -1 if not found.
@param
@return
GetHttpMethodConverts HTTP method string into internal index
@param
@return
GetHttpReasonReturns string describing HTTP reason phrase.
@param
@return
@see
https://tools.ietf.org/html/rfc2616
@see
https://tools.ietf.org/html/rfc6585
GetInstructionLengthsReturns lengths of x86 ops in binary. The first decoded instruction is at
@return
GetInterpreterExecutableNameReturns path of executable interpreter. Unlike
@param
@return
@see
program_invocation_short_name
@see
program_invocation_name
@see
program_executable_name
getitimerRetrieves last setitimer() value, correcting for remaining time.
@param
@return
getlineReads 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().
@param
@return
@see
fgetln(), xgetline(), getdelim(), gettok_r()
@see libc/stdio/getline.c
getloadavgReturns system load average.
@param
@return
@raise
ENOSYS on metal
getnameinfoResolves name/service for socket address.
@param
@return
GetNtNameServersExtracts DNS nameserver IPs from Windows Registry.
@param
@return
GetNtOpenFlags
@param
@return
__getntsyspathObtains WIN32 magic path, e.g. GetTempPathA.
@param
@return
getoptParses 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); } }
@param
@return
@see
optind
@see
optarg
getpeernameReturns details about remote end of connected socket.
@param
@return
@see
getsockname()
getpidReturns process id. This function does not need to issue a system call. The PID is tracked by a global variable which is updated atfork(). The only exception is when the process is vfork()'d in which case a system call shall be issued. On Linux, and only Linux, the process id is guaranteed to be the same as gettid() for the main thread.
@return
@asyncsignalsafe
@threadsafe
@vforksafe
@see libc/intrin/getpid.c
getpriorityReturns nice value of thing. Since -1 might be a valid return value for this API, it's necessary
to clear
@param
@return
@see
setpriority(), nice()
GetProcAddressModuleReturns address of function in a DLL that's already loaded.
@param
@return
getpwnam_r
@param
@return
getpwuid_r
@param
@return
getrandomReturns cryptographic random data. This random number seed generator obtains information from:
@param
@return
@note
this function could block a nontrivial time on old computers
@note
this function is indeed intended for cryptography
@note
this function takes around 900 cycles
@asyncsignalsafe
@restartable
@vforksafe
getresgidGets real, effective, and "saved" group ids.
@param
@return
@see
setresuid()
getresuidGets real, effective, and "saved" user ids.
@param
@return
@see
setresuid()
getrlimitGets resource limit for current process.
@param
@return
@see
libc/sysv/consts.sh
getrusageReturns resource usage statistics.
@param
@return
GetSiCodeNameReturns symbolic name for siginfo::si_code value.
@param
@return
getsidCreates session and sets the process group id.
@param
@return
@see libc/calls/getsid.c
getsocknameReturns details about network interface kernel granted socket.
@param
@return
@see
getpeername()
getsockoptRetrieves socket setting.
@param
@return
@error
ENOPROTOOPT for unknown (level,optname)
@error
EINVAL if
out_optlen is invalid somehow
@error
ENOTSOCK if
fd is valid but not a socket
@error
EBADF if
fd isn't valid
@error
EFAULT if optval memory isn't valid
@see
libc/sysv/consts.sh for tuning catalogue
@see
setsockopt()
GetSymbolTableReturns 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.
@return
GetTempPathA_flunkCalls GetTempPathA() w/ different API.
@return
@see
GetSystemDirectoryA(), GetWindowsDirectoryA()
gettidReturns 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. This function issues a system call. That stops being the case as soon as __install_tls() is called. That'll happen automatically, when you call clone() and provide the TLS parameter. We assume that when a TLS block exists, then
*(int *)(__get_tls() + 0x38)will contain the thread id. Therefore when issuing clone() calls, the CLONE_CHILD_SETTID and CLONE_CHILD_CLEARTID flags should use that
index as its ctid memory.
gettid (single threaded) l: 126𝑐 41𝑛𝑠 gettid (tls enabled) l: 2𝑐 1𝑛𝑠The TLS convention is important for reentrant lock performance.
@return
@asyncsignalsafe
@threadsafe
@vforksafe
@see libc/intrin/gettid.c
gettimeofdayReturns system wall time in microseconds, e.g. int64_t t; char p[30]; struct tm tm; struct timeval tv; gettimeofday(&tv, 0); t = tv.tv_sec; gmtime_r(&t, &tm); FormatHttpDateTime(p, &tm); printf("%s\n", p);
@param
@return
@error
EFAULT if
tv or tz isn't valid memory
@see
clock_gettime() for nanosecond precision
@see
strftime() for string formatting
__gettimeofday_getReturns pointer to fastest gettimeofday().
@param
@return
getttycolsShorthand for getting ws_col from getttysize(). It is recommended that programs err on the side of showing more information, if this value can't be obtained with certainty.
@param
@return
getttysizeReturns dimensions of controlling terminal. It is recommended that programs err on the side of showing more information, if this value can't be obtained with certainty.
@param
@return
@returns
-1 on error or something else on success
getuidReturns 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.
@return
@asyncsignalsafe
@vforksafe
@see libc/calls/getuid.c
getutf16Decodes UTF-16 character.
@param
@return
@note
synchronization is performed to skip leading continuations;
canonicalization and validation are performed to some extent
@todo
delete
getwcReads UTF-8 character from stream.
@param
@return
@threadsafe
@see libc/stdio/getwc.c
getwc_unlockedReads UTF-8 character from stream.
@param
@return
getwcharReads UTF-8 character from stream.
@return
@threadsafe
getwchar_unlockedReads UTF-8 character from stream.
@return
getx86processormodelIdentifies microarchitecture of host processor.
@param
@return
@see
https://en.wikichip.org/wiki/intel/cpuid
@see
https://a4lg.com/tech/x86/database/x86-families-and-models.en.html
GetZipCdirCommentReturns comment of zip central directory.
@param
@return
GetZipCdirCommentSizeReturns comment of zip central directory.
@param
@return
GetZipCdirOffsetReturns offset of zip central directory.
@param
@return
GetZipCdirRecordsReturns number of records in zip central directory.
@param
@return
GetZipCdirSizeReturns size of zip central directory.
@param
@return
GetZipCfileCompressedSizeReturns compressed size in bytes from zip central directory header.
@param
@return
GetZipCfileModeReturns st_mode from ZIP central directory record.
@param
@return
GetZipCfileOffsetReturns offset of local file header.
@param
@return
GetZipCfileTimestampsExtracts modified/access/creation timestamps from zip entry.
@param
@return
GetZipCfileUncompressedSizeReturns uncompressed size in bytes from zip central directory header.
@param
@return
GetZipLfileCompressedSizeReturns compressed size in bytes from zip local file header.
@param
@return
GetZipLfileUncompressedSizeReturns uncompressed size in bytes from zip local file header.
@param
@return
globFinds 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);
@param
@return
GoodSocketReturns new socket with modern goodness enabled.
@param
@return
grayReturns gray code for x.
@param
@return
@see
https://en.wikipedia.org/wiki/Gray_code
@see
ungray()
@see libc/bits/gray.c
__growGrows array.
@param
@return
@deprecated
favor realloc
@see libc/runtime/grow.c
gzbufferSets 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().
@return
gzclearerrClears 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.
@return
gzcloseFlushes 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.
@return
gzclose_rSame 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.
@return
gzdirectReturns 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.)
@return
gzdopenAssociates 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.
@return
gzeofReturns 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.
@return
gzerrorReturns 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.
@return
gzflushFlushes 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.
@return
gzfreadRead 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.
@return
gzfwriteWrites 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.
@return
gzgetcReads 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.
@return
gzgetsReads 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.
@return
gzoffsetReturns 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.
@return
gzopenOpens 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.
@return
gzprintfConverts, 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().
@param
@return
gzputcWrites character converted to an unsigned char into compressed file.
@return
gzputsWrites the given null-terminated string to the compressed file, excluding the terminating null character.
@return
gzreadReads 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.
@return
gzrewindRewinds file. This function is supported only for reading.
@return
@note
gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
gzseekSets 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.
@return
gzsetparamsDynamically 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.
@return
gztellReturns 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().
@return
@note
gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
gzungetcPushes 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().
@return
gzwriteWrites given number of uncompressed bytes into the compressed file. gzwrite returns the number of uncompressed bytes written or 0 in case of error.
@return
h_errnoError number global for gethostbyname*(), gethostbyaddr*(), etc.
@type
@see libc/dns/h_errno.c
hammingCounts number of different bits.
@param
@return
@see
https://en.wikipedia.org/wiki/Hamming_code
@see libc/bits/hamming.c
HasControlCodesReturns true if C0 or C1 control codes are present
@param
@return
@see
VisualizeControlCodes()
HeaderHasReturns true if standard header has substring.
@param
@return
herrorPrints
@param
@return
@see
perror()
@see libc/dns/herror.c
hextointConverts ASCII hexadecimal character to integer case-insensitively.
@param
@return
@see libc/str/hextoint.c
HighwayHash64Computes 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
@param
@return
hilbertGenerates Hilbert space-filling curve.
@param
@return
@see
https://en.wikipedia.org/wiki/Hilbert_curve
@see
unhilbert()
@see libc/bits/hilbert.c
__hookRewrites code in memory to hook function calls. We do this by searching each function for the nop instruction inserted by GCC when we use the -pg -mnop-mcount flags. There's no risk of corrupting data since the linker scripts won't mix code and data. Modules built with -O3 and without the profiling flags might have these same nop instructions, but that shouldn't be problematic since they're only there for the puposes of aligning jumps, and therefore aren't actually executed. However codebases that use huge function alignments with wide-nop slides could pose minor issues. Further note that Cosmopolitan sources are almost never intentionally written to use code alignment, since we've only seen a few cases where it helps.
@param
@return
@see
ape/ape.lds
hstrerrorTurns
@param
@return
@see libc/dns/hstrerror.c
iconv
@param
@return
@see libc/stdio/iconv.c
ilogbReturns log₂𝑥 exponent part of double.
@param
@return
@note
needs sse3
ilogbfReturns log₂x exponent part of float.
@param
@return
@note
needs sse3
ilogblReturns log₂x exponent part of long double.
@param
@return
@note
needs sse3
imapxlatabIdentity maps 256-byte translation table.
@param
@return
@speed
90mBps
@mode
long
IndentLinesInserts spaces before lines.
@param
@return
indexReturns pointer to first instance of character, the BSD way.
@param
@return
@see libc/str/index.c
inet_addrConverts dotted IPv4 address string to network order binary.
@param
@return
@see
inet_aton()
inet_atonConverts dotted IPv4 address string to network order binary.
@param
@return
inet_ntopFormats internet address to string.
@param
@return
inet_ptonConverts internet address string to binary.
@param
@return
inflateinflate 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:
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.
@return
__inflateDecompresses 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.
@param
@return
inflate_fastDecodes literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate() execution time is spent in this routine. Entry assumptions:
state->mode == LEN strm->avail_in >= INFLATE_FAST_MIN_INPUT (6 bytes) strm->avail_out >= INFLATE_FAST_MIN_OUTPUT (258 bytes) start >= strm->avail_out state->bits < 8On return, state->mode is one of:
LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block dataSome notes: INFLATE_FAST_MIN_INPUT: 6 bytes - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm->avail_in >= 6, then there is enough input to avoid checking for available input while decoding. INFLATE_FAST_MIN_OUTPUT: 258 bytes - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm->avail_out >= 258 for each loop to avoid checking for available output space while decoding.
@param
@return
inflate_tableBuilds set of tables to decode the provided canonical Huffman code. The code lengths are lens[0..codes-1]. The result starts at *table, whose indices are 0..2^bits-1. work is a writable array of at least lens shorts, which is used as a work area. type is the type of code to be generated, CODES, LENS, or DISTS. On return, zero is success, -1 is an invalid code, and +1 means that ENOUGH isn't enough. table on return points to the next available entry's address. bits is the requested root table index bits, and on return it is the actual root table index bits. It will differ if the request is greater than the longest code or if it is less than the shortest code.
@param
@return
inflateBackinflateBack() 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.
@return
inflateBackEndAll memory allocated by inflateBackInit() is freed.
@return
inflateBackInitInitialize 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.
@return
inflateCopySets 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.
@return
inflateEndAll dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output.
@return
inflateGetDictionaryReturns 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.
@return
inflateGetHeaderinflateGetHeader() 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.
@return
inflateInitInitializes 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.
@return
inflateInit2This 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.
@return
inflateMarkReturns 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.
@return
inflatePrimeThis 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.
@return
inflateResetThis 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.
@return
inflateReset2This 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.
@return
inflateSetDictionaryInitializes 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.
@return
inflateSyncSkips 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.
@return
_initDecentralized 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.
@param
@return
@note
rdi is __init_bss_start (callee monotonic lockstep)
@note
rsi is __init_rodata_start (callee monotonic lockstep)
@see
.init.start & .init.end (libc/macros.internal.inc)
@see
ape/ape.lds
@see libc/runtime/init.S
__init_bss_startDecentralized section for unpacked data structures. Data in this section becomes read-only after initialization.
@return
@see
.piro.bss.init (libc/macros.internal.inc)
@see
libc/runtime/piro.c
@see
ape/ape.lds
@see libc/runtime/init.S
__init_rodata_startDecentralized section for packed data structures & initializers.
@return
@see
.initro (libc/macros.internal.inc)
@see
ape/ape.lds
@see libc/runtime/init.S
initstate
@param
@return
@see libc/rand/random.c
insertionsortSorts array of signed 32-bit integers.
@param
@return
@see
djbsort()
int128toarray_radix10Converts signed 128-bit integer to string.
@param
@return
interruptiblecallCalls function that may be cancelled by a signal.
@param
@return
ioctlControls settings on device.
@param
@return
@restartable
@vforksafe
@see libc/calls/ioctl.c
ioctl_fioclexSets "close on exec" on file descriptor the fast way.
@param
@return
@see
ioctl(fd, FIOCLEX, 0) dispatches here
ioctl_siocgifconfReturns information about network interfaces.
@param
@return
@see
ioctl(fd, SIOCGIFCONF, tio) dispatches here
ioctl_tcgetsReturns information about terminal.
@param
@return
@see
tcgetattr(fd, tio) dispatches here
@see
ioctl(fd, TCGETS, tio) dispatches here
@see
ioctl(fd, TIOCGETA, tio) dispatches here
ioctl_tcsetsChanges terminal behavior.
@param
@return
@see
tcsetattr(fd, TCSA{NOW,DRAIN,FLUSH}, tio) dispatches here
@see
ioctl(fd, TCSETS{,W,F}, tio) dispatches here
@see
ioctl(fd, TIOCGETA{,W,F}, tio) dispatches here
ioctl_tiocgwinszReturns width and height of terminal.
@param
@return
@see
ioctl(fd, TIOCGWINSZ, ws) dispatches here
ioctl_tiocswinszSets width and height of terminal.
@param
@return
@see
ioctl(fd, TIOCSWINSZ, ws) dispatches here
__iovec2ntConverts I/O vector from System Five to WIN32 ABI.
@param
@return
@see
IOV_MAX
@see libc/sock/iovec2nt.c
_isabspathReturns true if pathname is considered absolute.
@param
@return
@see libc/str/isabspath.c
IsAcceptableHostReturns 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:
@param
@return
IsAcceptablePathReturns true if path seems legit.
@param
@return
@see
IsReasonablePath()
IsAcceptablePortReturns true if port seems legit. Here's examples of permitted inputs:
@param
@return
isalnumReturns nonzero if c is lower, alpha, or digit.
@param
@return
@see libc/str/isalnum.c
IsAnonymousIpReturns true if IPv4 address is anonymous proxy provider.
@param
@return
IsApnicIpReturns true if IPv4 address is managed by APNIC.
@param
@return
@see net/http/isapnicip.c
IsArinIpReturns true if IPv4 address is managed by ARIN.
@param
@return
@see net/http/isarinip.c
IsAtLeastWindows10Returns true if we're running at least Windows 10. This function may only be called if IsWindows() is true.
@return
isattyTells if file descriptor is a terminal.
@param
@return
@raise
EBADF if fd isn't a valid file descriptor
@raise
ENOTTY if fd is something other than a terminal
@raise
EPERM if pledge() was used without tty
@see libc/calls/isatty.c
ischardevReturns 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.
@param
@return
@see
isregularfile(), isdirectory(), issymlink(), fileexists()
iscntrlReturns nonzero if c is C0 ASCII control code or DEL.
@param
@return
@see libc/str/iscntrl.c
IsDebuggerPresentDetermines if gdb, strace, windbg, etc. is controlling process.
@param
@return
isdirectoryReturns 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.
@param
@return
@see
isregularfile(), issymlink(), ischardev()
isdirectory_ntReturns true if file exists and is a directory on Windows NT.
@param
@return
_isdirsepReturns true if character is directory separator slash.
@param
@return
@see libc/str/isdirsep.c
IsDodIpReturns true if IP is owned by the U.S. Department of Defense.
@param
@return
@see net/http/isdodip.c
isexecutableReturns true if file exists and is executable.
@param
@return
@see
access(exe, X_OK) which is more accurate on NT
@asyncsignalsafe
@vforksafe
isgraphReturns nonzero if c is printable ascii that isn't space.
@param
@return
@see libc/str/isgraph.c
_isheapReturns true if address isn't stack and was malloc'd or mmap'd.
@param
@return
@assume
stack addresses are always greater than heap addresses
@assume
stack memory isn't stored beneath %rsp (-mno-red-zone)
islowerReturns nonzero if c is lowercase alpha ascii character.
@param
@return
@see libc/str/islower.c
IsMimeTypeReturns true if content-type 𝑡 has mime-type 𝑠.
@param
@return
IsMulticastIpReturns true if IPv4 address is used for multicast.
@param
@return
iso8601Converts timestamp to ISO-8601 formatted string.
@param
@return
@see libc/time/iso8601.c
isprintReturns nonzero if c is printable ascii including space.
@param
@return
@see libc/str/isprint.c
IsPrivateIpReturns true if IPv4 address is intended for private networks.
@param
@return
IsPublicIpReturns 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.
@param
@return
@see
IANA IPv4 Special-Purpose Address Registry
ispunctReturns nonzero if
@param
@return
@see libc/str/ispunct.c
IsReasonablePathReturns true if path doesn't contain "." or ".." segments.
@param
@return
@see
IsAcceptablePath()
isregularfileReturns 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.
@param
@return
@see
isdirectory(), ischardev(), issymlink()
isregularfile_ntReturns true if file exists and is a regular file on Windows NT.
@param
@return
IsRipeIpReturns true if IPv4 address is managed by RIPE NCC.
@param
@return
@see net/http/isripeip.c
issetugidDetermines 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.
@return
isspaceReturns nonzero if c is space, \t, \r, \n, \f, or \v.
@param
@return
@see
isblank()
@see libc/str/isspace.c
issymlinkReturns 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.
@param
@return
@see
isregularfile(), isdirectory(), fileexists(), ischardev()
issymlink_ntReturns true if file exists and is a symbolic link on Windows NT.
@param
@return
IsTestnetIpReturns true if IPv4 address is intended for documentation.
@param
@return
@see
RFC5737
_istextReturns true if buffer is most likely plaintext.
@param
@return
@see libc/str/istext.c
isupperReturns nonzero if c is uppercase alpha ascii character.
@param
@return
@see libc/str/isupper.c
IsValidCookieValueReturns true if string is a valid cookie value (any ASCII excluding control char, whitespace, double quotes, comma, semicolon, and backslash).
@param
@return
IsValidHttpTokenReturns true if string is ASCII without delimiters.
@param
@return
iswalnumReturns nonzero if c is lower, alpha, or digit.
@param
@return
@see libc/str/iswalnum.c
iswalphaReturns nonzero if c is alphabetical.
@param
@return
@see libc/str/iswalpha.c
iswblankReturns nonzero if c is space or tab.
@param
@return
@see libc/str/iswblank.c
iswcntrlReturns nonzero if c is C0 or C1 control code.
@param
@return
@see libc/str/iswcntrl.c
iswctypeReturns nonzero if c has property.
@param
@return
@see libc/str/iswctype.c
iswdigitReturns nonzero if c is decimal digit.
@param
@return
@see libc/str/iswdigit.c
iswgraphReturns nonzero if c is printable and not a space.
@param
@return
@see libc/str/iswgraph.c
iswlowerReturns nonzero if c is lowercase letter.
@param
@return
@see libc/str/iswlower.c
__isworkerIndicates 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.
@type
iswprintReturns nonzero if c is printable.
@param
@return
@see libc/str/iswprint.c
iswpunctReturns nonzero if c is punctuation mark.
@param
@return
@see libc/str/iswpunct.c
iswseparatorReturns 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).
@param
@return
iswspaceReturns nonzero if c is space character. We define this as invisible characters which move the cursor. That
means
@param
@return
@see libc/str/iswspace.c
iswupperReturns nonzero if c is uppercase letter.
@param
@return
@see libc/str/iswupper.c
iswxdigitReturns nonzero if c is ascii hex digit.
@param
@return
@see libc/str/iswxdigit.c
IsZipCdir32Returns true if zip end of central directory header seems legit.
@param
@return
IsZipCdir64Returns true if zip64 end of central directory header seems legit.
@param
@return
_jmpstackSwitches stack.
@param
@noreturn
_joinWaits for thread created by _spawn() to terminate. This will free your thread's stack and tls memory too.
@param
@return
@see libc/thread/spawn.c
_joinpathsJoins paths, e.g. 0 + 0 → 0 "" + "" → "" "a" + 0 → "a" "a" + "" → "a/" 0 + "b" → "b" "" + "b" → "b" "." + "b" → "./b" "b" + "." → "b/." "a" + "b" → "a/b" "a/" + "b" → "a/b" "a" + "b/" → "a/b/" "a" + "/b" → "/b"
@param
@return
@see libc/fmt/joinpaths.c
kappendfAppends formatted string to buffer w/ kprintf, e.g. char *b = 0; kappendf(&b, "hello %d\n", 123); free(b);
@param
@return
@see
appendz(b).i to get buffer length
@note
O(1) amortized buffer growth
@see
kprintf()
kCp437ibm cp437 unicode table w/ string literal safety ░▄██▒▄█ ▐██ ░░░ ▀▀████▒▀█▄ ▐███▓██░ ██▌ ▀████▄■█▄ ▐█▓███▀█░██▀ ░ ░▀█████▓▄ ▐█▓██▀▄█▒██▀ ▄▄░ ▄▄▄ ░░░ ░▀████▒▄ ▐████▀▄█■█▀ ▀▀ ░█████░ ▐█▓█▀████▀ ░ ▐▓███▒ █░███▀▀ ░░░ ▄█ ░░░ █████ ▐█▓█░▀▀ ░░▄█▄▄▄▄▄ ▀▄ ▌▄▄▄░▄▄▄▄▄ ▐████░ ▐███▌ ▄▀█████████▄ ▌▐▄████████▄ ▐▓███░ ▐███░░░▀▄█▀▄▄████▄▀░ ▐████████▒ ▀ ░███░ ░████░ ▓▀ ▄███████▀▌ ▀▄■████▀▀█▀ ██▀█ ▓███░ ░▄▀▀░░░ ▀ ░░▌ ▄▀▀▄░░▀░▄▀▄ ▐██▀▄ ░███░ ▄▓▓▄▄░▀▀█▀█ ▌░░ ▀█▀█▀▀ ▐██▀ █▀▄▐██ ▀░░ ▄▀ ▐ █ ▀ ▄▄▄░ ░▀▄█▄▀█ ▌▄ █▓ ▒ ░ █▄█▄▀▄▄▄███▄▀▄ ░░ ░ ▀ █▌ █▌▄░▌ ░░░▄▀█▀███████▄▀▄▀▄▀▀▄▄▄ █▀█░▐ ██▄ ░░░▄█▄▀██▄█■██████▄█▄█▄■▀█░ ▐░▐ ▀██░ ░▄██████████████████▄█▄█ ░█ ░ ▄▀ ▀▓█▄▓░░ ▒█▀█████████████████████▒ ██▀ ▀███ ▓▒ ██████████████▀▀▀▀█▄▀ ░▄█▒ ▀███ ▀█▄▀▄█████▀▀ ▓▓▓▄░ ▐ ░▄██ ▀██ ▄███████▄████████▀░░ ░▄██ ▄██▀▀▄ █▄▀▄██▒▒███████████▀▀▀▄░ ░███░ ▄██▀▄▄░░▀▐▄████▄ █████▀▄░░█▀▄▀░░ ▄██░ █████▄▄▄███▀░█▌██▄▀▀█████▄▄░░░▄▄███▀██▄ ▄▀▀▀▄▄ ▀██████▀■▄█▄▄ ░▀███████████████▓▓░░▄██▀▄████▄▄▀▄ █▀█ █ █▀█ █▀█ █▄▀ ▐▀█▀▌█▀█ █▀█ █▄ █ ▀█▀ █▀█ █▀▀ █▀▄ █ █ █ █ █ ▀▄ █ █▀▄ █ █ █ ▀█ █ █ ▀▀█ █▄█ █▄▌█▄█ █▄█ █ █ █ █ █ █▄█ █ █ ▄█▄ █▄█ █▄█ THERE WILL BE BLOCKS march 01 2017
@return
@see
libc/str/str.h
@see
kCp437i[]
kCpuidsGlobally 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.
@return
@see
www.felixcloutier.com/x86/cpuid
kHttpRepeatableSet 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.
@type
@note
we choose to not recognize this grammar for kHttpConnection
@note
grep '[A-Z][a-z]*".*":"' rfc2616
@note
grep ':.*#' rfc2616
@see
RFC7230 § 4.2
kHttpTokengenerated by: o//tool/build/xlat.com -TiC ' ()<>@,;:\"/[]?={}' -iskHttpToken present absent ──────────────── ──────────────── ∅☺☻♥♦♣♠•◘○◙♂♀♪♫☼ 0x00 ►◄↕‼¶§▬↨↑↓→←∟↔▲▼ 0x10 ! #$%&‘ *+ -. ␠ “ () , / 0x20 0123456789 :;<=>⁇ 0x30 ABCDEFGHIJKLMNO @ 0x40 PQRSTUVWXYZ ^_ [⭝] 0x50 `abcdefghijklmno 0x60 pqrstuvwxyz | ~ { } ⌂ 0x70 ÇüéâäàåçêëèïîìÄÅ 0x80 ÉæÆôöòûùÿÖÜ¢£¥€ƒ 0x90 áíóúñѪº¿⌐¬½¼¡«» 0xa0 ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐ 0xb0 └┴┬├─┼╞╟╚╔╩╦╠═╬╧ 0xc0 ╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ 0xd0 αßΓπΣσμτΦΘΩδ∞φε∩ 0xe0 ≡±≥≤⌠⌡÷≈°∙×√ⁿ²■λ 0xf0const char kHttpToken[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x00 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x10 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 0x20 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 0x30 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 0x50 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, // 0x70 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x90 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xa0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xb0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xc0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xd0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xe0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xf0 };
@return
@see
RFC2616
CHAR = <any US-ASCII character (octets 0 - 127)>
SP = <US-ASCII SP, space (32)>
HT = <US-ASCII HT, horizontal-tab (9)>
CTL = <any US-ASCII control character
(octets 0 - 31) and DEL (127)>token = 1*<any CHAR except CTLs or separators> separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT killSends signal to process. The impact of this action can be terminating the process, or interrupting it to request something happen.
@param
@return
@asyncsignalsafe
@see libc/calls/kill.c
kNtSystemDirectoryRII constant holding 'C:/WINDOWS/SYSTEM32' directory.
@return
@note
guarantees trailing slash if non-empty
kNtWindowsDirectoryRII constant holding 'C:/WINDOWS' directory.
@return
@note
guarantees trailing slash if non-empty
kNtWsaDataInformation 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.
@type
kprintfPrivileged 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:
%t will work. You
can do that by calling GetSymbolTable() . If that hasn't happened it
will print &hexnumber instead.
@param
@return
@asyncsignalsafe
@vforksafe
ksnprintfPrivileged snprintf().
@param
@return
@see
kprintf() for documentation
@asyncsignalsafe
@vforksafe
kStartTscTimestamp of process start.
@type
@see
libc/runtime/winmain.greg.h
@see
libc/crt/crt.S
kTmpPathRII constant holding temporary file directory. The order of precedence is:
@type
kvappendfAppends 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.
@param
@return
@see
kprintf()
kvprintfPrivileged vprintf.
@param
@return
@see
kprintf() for documentation
@asyncsignalsafe
@vforksafe
kvsnprintfPrivileged vsnprintf().
@param
@return
@see
kprintf() for documentation
@asyncsignalsafe
@vforksafe
kXedChipFeaturesMapping 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).
@type
kXedErrorNamesXed error code names. puts(IndexDoubleNulString(kXedErrorNames, xedd->op.error));
@type
@see
XedError
l64aConverts 32-bit integer to base64, the posix way.
@param
@return
@see
a64l() for inverse
@see
EncodeBase64()
@see libc/str/l64a.c
labsReturns absolute value of long integer.
@param
@return
@note
labs(LONG_MIN) returns LONG_MIN unless -ftrapv
@note
consider ABS() to avoid narrowing
@see libc/fmt/labs.c
landlock_add_ruleAdds new rule to Landlock ruleset.
@param
@return
@error
ENOSYS if Landlock isn't supported
@error
EPERM if Landlock supported but SECCOMP BPF shut it down
@error
EOPNOTSUPP if Landlock supported but disabled at boot time
@error
EINVAL if flags not 0, or inconsistent access in the rule,
i.e. landlock_path_beneath_attr::allowed_access is not a subset
of the ruleset handled accesses
@error
ENOMSG empty allowed_access
@error
EBADF
fd is not a file descriptor for current thread, or
member of rule_attr is not a file descriptor as expected
@error
EBADFD
fd is not a ruleset file descriptor, or a member
of rule_attr is not the expected file descriptor type
@error
EPERM
fd has no write access to the underlying ruleset
@error
EFAULT
rule_attr inconsistency
landlock_create_rulesetCreate 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);
@param
@return
@error
ENOSYS if not running Linux 5.13+
@error
EPERM if pledge() or seccomp bpf shut it down
@error
EOPNOTSUPP Landlock supported but disabled at boot
@error
EINVAL unknown flags, or unknown access, or too small size
@error
E2BIG attr or size inconsistencies
@error
EFAULT attr or size inconsistencies
@error
ENOMSG empty landlock_ruleset_attr::handled_access_fs
landlock_restrict_selfEnforces Landlock ruleset on calling thread.
@param
@return
@error
EOPNOTSUPP if Landlock supported but disabled at boot time
@error
EINVAL if flags isn't zero
@error
EBADF if
fd isn't file descriptor for the current thread
@error
EBADFD if
fd is not a ruleset file descriptor
@error
EPERM if
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
@error
E2BIG if the maximum number of stacked rulesets is
reached for current thread
lchownChanges owner and/or group of pathname, w/o dereferencing symlinks.
@param
@return
@see
chown() which dereferences symbolic links
@see
/etc/passwd for user ids
@see
/etc/group for group ids
@see libc/calls/lchown.c
ldexplReturns 𝑥 × 2ʸ.
@param
@return
LengthInt64Returns
@param
@return
LengthInt64ThousandsReturns decimal string length of int64 w/ thousands separators.
@param
@return
LengthUint64Returns
@param
@return
LengthUint64ThousandsReturns decimal string length of uint64 w/ thousands separators.
@param
@return
lgammaf_rReturns natural logarithm of absolute value of Gamma function.
@param
@return
linkCreates 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.
@param
@return
@asyncsignalsafe
@see libc/calls/link.c
linkatCreates 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.
@param
@return
@asyncsignalsafe
@see libc/calls/linkat.c
listenAsks 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.
@param
@return
@see libc/sock/listen.c
llabsReturns absolute value of long long integer.
@param
@return
@note
llabs(LONG_LONG_MIN) returns LONG_LONG_MIN unless -ftrapv
@note
consider ABS() to avoid narrowing
@see libc/fmt/llabs.c
llroundRounds to nearest integer, away from zero.
@param
@return
@see
round(), lrint()
llroundfRounds to nearest integer, away from zero.
@param
@return
@see
round()
_loadxmmLoads XMM registers from buffer.
@param
@return
@note
modern cpus have out-of-order execution engines
_lockcmpxchgCompares and exchanges w/ lock prefix.
@param
@return
@see
cmpxchg() if only written by one thread
_lockxaddCompares and exchanges w/ lock prefix.
@param
@return
@see
InterlockedAdd() for a very similar API
@see
xadd() if only written by one thread
lockxchgCompares and exchanges w/ lock prefix.
@param
@return
@see
xchg()
logReturns natural logarithm of 𝑥.
@param
@return
log10Calculates log₁₀𝑥.
@param
@return
log10fCalculates log₁₀𝑥.
@param
@return
log10lCalculates log₁₀𝑥.
@param
@return
log1pReturns log(𝟷+𝑥).
@param
@return
log1pfReturns log(𝟷+𝑥).
@param
@return
log1plReturns log(𝟷+𝑥).
@param
@return
log2Calculates log₂𝑥.
@param
@return
log2fCalculates log₂𝑥.
@param
@return
log2lCalculates log₂𝑥.
@param
@return
@see
ilogbl()
logbReturns log₂ₓ exponent part of double.
@param
@return
@see libc/tinymath/logb.S
logbfReturns log₂ₓ exponent part of float.
@param
@return
logblReturns log₂ₓ exponent part of long double.
@param
@return
logfReturns natural logarithm of 𝑥.
@param
@return
@see libc/tinymath/logf.S
loglReturns natural logarithm of 𝑥.
@param
@return
@see libc/tinymath/logl.S
longerjmpLoads previously saved processor state.
@param
@noreturn
longjmpLoads previously saved processor state.
@param
@noreturn
@assume
system five nexgen32e abi conformant
@note
code built w/ microsoft abi compiler can't call this
@see
_gclongjmp() unwinds _gc() destructors
_longjmpLoads previously saved processor state.
@param
@noreturn
@assume
system five nexgen32e abi conformant
@note
code built w/ microsoft abi compiler can't call this
@see
_gclongjmp() unwinds _gc() destructors
longsortSorting algorithm for longs that doesn't take long. "What disorder is this? Give me my long sort!" -Lord Capulet
@param
@return
@see libc/str/longsort.c
LookupProtoByNameOpens and searches /etc/protocols to find number for a given name.
@param
@return
@note
aliases are read from file for comparison, but not returned.
@see
LookupProtoByNumber
LookupProtoByNumberOpens 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
@param
@return
@note
aliases are not read from the file.
LookupServicesByNameOpens and searches /etc/services to find port for a given name.
@param
@return
@note
aliases are read from file for comparison, but not returned.
@see
LookupServicesByPort
@threadsafe
LookupServicesByPortOpens 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
@param
@return
@note
aliases are not read from the file.
lroundRounds to nearest integer, away from zero.
@param
@return
@see
round(), lrint()
lroundfRounds to nearest integer, away from zero.
@param
@return
@see
round()
lseekChanges current position of file descriptor/handle.
@param
@return
@asyncsignalsafe
@see libc/calls/lseek.c
lstatReturns information about file, w/o traversing symlinks.
@param
@return
@asyncsignalsafe
@see libc/calls/lstat.c
lutimesChanges file timestamps, the legacy way.
@param
@return
@see libc/calls/lutimes.c
lz4cpyDecompresses 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().
@param
@return
@see
rldecode() for a 16-byte decompressor
@see libc/str/lz4cpy.c
lz4decodeDecompresses 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.
@param
@return
@see
_mapanon(), lz4check()
@see libc/str/lz4decode.c
madviseDrops hints to O/S about intended access patterns of mmap()'d memory.
@param
@return
@see
libc/sysv/consts.sh
@see
fadvise()
@see libc/calls/madvise.c
makedirsRecursively creates directory a.k.a. folder. This function won't fail if the directory already exists.
@param
@return
@see
mkdir()
@see libc/x/makedirs.c
mallocAllocates 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.) 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.
@param
@return
@threadsafe
@see libc/mem/malloc.S
malloc_trimReleases freed memory back to system.
@param
@return
malloc_usable_sizeReturns 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)
@param
@return
@see
dlmalloc_usable_size()
@threadsafe
__map_phdrsMaps APE-defined ELF program headers into memory and clears BSS.
@param
@return
_mapanonHelper 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.
@param
@return
_mapstackAllocates 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.
@return
MapViewOfFileExMaps view of file mapping into memory on the New Technology.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
MapViewOfFileExNumaMaps view of file mapping into memory on the New Technology.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
mbrlen
@param
@return
@see libc/str/mbrlen.c
mbrtoc16
@param
@return
@see libc/str/mbrtoc16.c
mbrtoc32
@param
@return
@see libc/str/mbrtoc32.c
mbrtowc
@param
@return
@see libc/str/mbrtowc.c
mbsnrtowcs
@param
@return
mbsrtowcs
@param
@return
@see libc/str/mbsrtowcs.c
mbstowcs
@param
@return
@see libc/str/mbstowcs.c
MeasureEntropyReturns 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.
@param
@return
memalignAllocates 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.
@param
@return
@see
valloc(), pvalloc()
@threadsafe
@see libc/mem/memalign.S
memcasecmpCompares 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
@param
@return
memccpyCopies 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);
@param
@return
@note
DST and SRC can't overlap
@asyncsignalsafe
@see libc/str/memccpy.c
memchr16Returns pointer to first instance of character in range.
@param
@return
@asyncsignalsafe
memfrobMemfrob implements a crypto algorithm proven to be unbreakable, without meeting its requirements concerning secrecy or length.
@param
@return
@see libc/str/memfrob.c
memjmpinitInitializes jump table for memset() and memcpy().
@param
@return
memmoveCopies 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.
@param
@return
@asyncsignalsafe
memset16Sets wide memory.
@param
@return
@asyncsignalsafe
@see libc/str/memset16.c
MetalPrintfPrints string to serial port. This only supports %d and %s. It'll will work even if .rodata hasn't been loaded into memory yet.
@param
@return
mincoreTells you which pages are resident in memory.
@param
@return
@see libc/calls/mincore.c
mkdirCreates 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
@param
@return
@error
ENAMETOOLONG if >246 characters on NT
@asyncsignalsafe
@see
makedirs()
@see libc/calls/mkdir.c
mkdiratCreates directory a.k.a. folder.
@param
@return
@error
EEXIST, ENOTDIR, ENAMETOOLONG, EACCES, ENOENT
@asyncsignalsafe
@see
makedirs()
@see libc/calls/mkdirat.c
mkdtempCreates temporary directory.
@param
@return
@raise
EINVAL if template didn't end with XXXXXX
@see libc/stdio/mkdtemp.c
mkfifoCreates named pipe.
@param
@return
@asyncsignalsafe
@see libc/calls/mkfifo.c
mknodCreates filesystem inode.
@param
@return
@asyncsignalsafe
@see libc/calls/mknod.c
mkntcmdlineConverts System V argv to Windows-style command line. Escaping is performed and it's designed to round-trip with GetDosArgv() or GetDosArgv(). This function does NOT escape command interpreter syntax, e.g. $VAR (sh), %VAR% (cmd).
@param
@return
@see
libc/runtime/dosargv.c
mkntenvblockCopies sorted environment variable block for Windows. This is designed to meet the requirements of CreateProcess().
@param
@return
@error
E2BIG if total number of shorts exceeded ARG_MAX/2 (32767)
__mkntpath2Copies path for Windows NT. This entails (1) UTF-8 to UTF-16 conversion; (2) replacing forward-slashes with backslashes; and (3) remapping several well-known paths (e.g. /dev/null → NUL) for convenience.
@param
@return
@error
ENAMETOOLONG
mkostempsDelegates to mkotempsm() w/ owner-only non-execute access.
@param
@return
mkostempsmOpens 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.
@param
@return
@see
kTmpPath
mkostempsmi
@param
@return
mktempGenerates unique filename. This function is usually frowned upon, since it's been known to create nasty opportunities for race conditions. Our implementation reflects that; consider using mkostemps().
@param
@return
@see libc/stdio/mktemp.c
_mktlsAllocates thread-local storage memory for new thread.
@param
@return
@see libc/thread/mktls.c
mmapBeseeches system for page-table entries, e.g. char *m; m = mmap(NULL, FRAMESIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); munmap(m, FRAMESIZE);
@param
@return
@see libc/runtime/mmap.c
mortonInterleaves bits.
@param
@return
@see
https://en.wikipedia.org/wiki/Z-order_curve
@see
unmorton()
@see libc/bits/morton.c
mountMounts file system. The following flags may be specified:
type parameter:
@param
@return
@see libc/calls/mount.c
MoveFileExDeletes existing empty directory.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
mprotectModifies restrictions on virtual memory address range.
@param
@return
@see
mmap()
mpsadbwComputes multiple sum of absolute differences. This appears to be intended for video encoding motion estimation. It can be combined with phminposuw. That allows us to search for an int overlapping inside 𝑏 that's nearest to an aligned int in 𝑎.
@param
@return
@note
goes fast w/ sse4 cf. core c. 2006 cf. bulldozer c. 2011
@mayalias
__mpsadbwsJump table for mpsadbw() with non-constexpr immediate parameter.
@return
@note
needs sse4 cf. core c. 2006 cf. bulldozer c. 2011
@see
mpsadbw()
mremapExtends and/or relocates memory pages.
@param
@return
msyncSynchronize memory mapping changes to disk. Without this, there's no guarantee memory is written back to disk. Particularly on RHEL5, OpenBSD, and Windows NT.
@param
@return
@see libc/runtime/msync.c
_mt19937Generates random integer on [0, 2^64)-interval. This uses the Mersenne Twister pseudorandom number generator.
@return
@see
smt19937(), Smt19937()
@see libc/rand/mt19937.c
Mul4x4AdxComputes 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
@param
@return
@note
words are host endian while array is little endian
@mayalias
Mul6x6AdxComputes 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
@param
@return
@note
words are host endian while array is little endian
@mayalias
Mul8x8AdxComputes 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
@param
@return
@note
words are host endian while array is little endian
@mayalias
__mulvdi3Returns 𝑥*𝑦, aborting on overflow.
@param
@return
@see
-ftrapv
__mulvsi3Returns 𝑥*𝑦, aborting on overflow.
@param
@return
@see
-ftrapv
__mulvti3Returns 𝑥*𝑦, aborting on overflow.
@param
@return
@see
-ftrapv
munmapReleases memory pages.
@param
@return
@raises
EINVAL if
n == 0
@raises
EINVAL if
n isn't 48-bit
@raises
EINVAL if
p+(n-1) isn't 48-bit
@raises
EINVAL if
p isn't 65536-byte aligned
_nanosReturns nanoseconds since UNIX epoch.
@param
@return
@see libc/calls/nanos.c
nanosleepSleeps for a particular amount of time.
@param
@return
@raise
EINVAL if
req->tv_nsec ∉ [0,1000000000)
@raise
EINTR if a signal was delivered, and
rem is updated
@raise
EFAULT if
req is NULL or req / rem is a bad pointer
@raise
ENOSYS on bare metal
@note
POSIX.1 specifies nanosleep() measures against
CLOCK_REALTIME
however Linux measures uses CLOCK_MONOTONIC . This shouldn't
matter, since POSIX.1 further specifies that discontinuous
changes in CLOCK_REALTIME shouldn't impact nanosleep()
@norestart
__negvdi2Returns -𝑥, aborting on overflow (two's complement bane).
@param
@return
@see
-ftrapv
__negvsi2Returns -𝑥, aborting on overflow (two's complement bane).
@param
@return
@see
-ftrapv
__negvti2Returns -𝑥, aborting on overflow.
@param
@return
@see
-ftrapv
newlocale
@param
@return
nftwWalks file tree.
@param
@return
@see
examples/walk.c for example
niceChanges process priority.
@param
@return
@see
Linux claims ioprio_set() is tuned automatically by this
@see libc/calls/nice.c
__nocolorIndicates 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
We think colors should be the norm, since most software is usually
too conservative about removing them. Rather than using
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!
@type
__nosyncTunes 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.
@type
@see libc/calls/nosync.c
__nt2sysvTranslates 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.
@param
@return
@note
slower than __sysv2nt
@see
NT2SYSV() macro
ntaccesscheckAsks 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.
@param
@return
@kudos
Aaron Ballman for teaching this
@see
libc/sysv/consts.sh
NtGetVersionReturns New Technology version, e.g. This can only be called on Windows.
@return
@see
IsAtLeastWindows10()
ntsetprivilegeSets NT permission thing, e.g. int64_t htoken; if (OpenProcessToken(GetCurrentProcess(), kNtTokenAdjustPrivileges | kNtTokenQuery, &htoken)) { ntsetprivilege(htoken, u"SeManageVolumePrivilege", kNtSePrivilegeEnabled); CloseHandle(htoken); }
@param
@return
ntspawnSpawns 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.
@param
@return
@see
spawnve() which abstracts this function
@see libc/calls/ntspawn.c
__oncrashCrashes 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.
@param
@return
@threadsafe
@vforksafe
@see libc/log/oncrash.c
__onforkTriggers callbacks registered by atfork().
@return
@note
only fork() should call this
@asyncsignalsafe
@see libc/calls/atfork.c
openOpens file.
@param
@return
@asyncsignalsafe
(zip files may have issues)
@vforksafe
(raises error if zip file)
@restartable
@threadsafe
@see libc/calls/open.c
openatOpens file.
@param
@return
@asyncsignalsafe
(zip files may have issues)
@vforksafe
(raises error if zip file)
@threadsafe
@see libc/calls/openat.c
opendirOpens 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));
@param
@return
@returns
newly allocated DIR object, or NULL w/ errno
@errors
ENOENT, ENOTDIR, EACCES, EMFILE, ENFILE, ENOMEM
@see
glob()
OpenExecutableOpens executable in O_RDWR mode. To avoid ETXTBSY we need to unmap the running executable first, then open the file, and finally load the code back into memory.
@return
@note
only works on .com binary (not .com.dbg)
@note
only supports linux, freebsd, openbsd, and netbsd
openlogOpens 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.
@param
@return
@asyncsignalsafe
@see libc/sock/syslog.c
OpenProcessCreates file mapping object on the New Technology.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
@see
MapViewOfFileEx()
openptyOpens new pseudo teletypewriter.
@param
@return
@params
flags is usually O_RDWR|O_NOCTTY
@see libc/calls/openpty.c
OpenSymbolTableMaps debuggable binary into memory and indexes symbol addresses.
@param
@return
pabsbConverts signed bytes to absolute values, 𝑎ᵢ ← |𝑏ᵢ|.
@param
@return
@note
goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@see libc/intrin/pabsb.c
pabsdConverts shorts to absolute values, 𝑎ᵢ ← |𝑏ᵢ|.
@param
@return
@note
goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@see libc/intrin/pabsd.c
pabswConverts shorts to absolute values, 𝑎ᵢ ← |𝑏ᵢ|.
@param
@return
@note
goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@see libc/intrin/pabsw.c
packssdwCasts ints to shorts w/ saturation.
@param
@return
@mayalias
packsswbCasts shorts to signed chars w/ saturation. 𝑎 ← {CLAMP[𝑏ᵢ]|𝑖∈[0,4)} ║ {CLAMP[𝑐ᵢ]|𝑖∈[4,8)}
@param
@return
@see
packuswb()
@mayalias
packusdwCasts ints to shorts w/ saturation.
@param
@return
@mayalias
packuswbCasts shorts to unsigned chars w/ saturation. 𝑎 ← {CLAMP[𝑏ᵢ]|𝑖∈[0,4)} ║ {CLAMP[𝑐ᵢ]|𝑖∈[4,8)}
@param
@return
@see
packsswb()
@mayalias
paddbAdds 8-bit integers.
@param
@return
@mayalias
@see libc/intrin/paddb.c
padddAdds 32-bit integers.
@param
@return
@mayalias
@see libc/intrin/paddd.c
paddqAdds 64-bit integers.
@param
@return
@mayalias
@see libc/intrin/paddq.c
paddsbAdds signed 8-bit integers w/ saturation.
@param
@return
@mayalias
@see libc/intrin/paddsb.c
paddswAdds signed 16-bit integers w/ saturation.
@param
@return
@mayalias
@see libc/intrin/paddsw.c
paddusbAdds unsigned 8-bit integers w/ saturation.
@param
@return
@mayalias
padduswAdds unsigned 16-bit integers w/ saturation.
@param
@return
@mayalias
paddwAdds 16-bit integers.
@param
@return
@note
shorts can't overflow so ubsan won't report it when it happens
@see
paddsw()
@mayalias
@see libc/intrin/paddw.c
__paginateDisplays wall of text in terminal with pagination.
@param
@return
palignrOverlaps vectors. 𝑖= 0 means 𝑐←𝑎0<𝑖<16 means 𝑐←𝑎║𝑏 𝑖=16 means 𝑐←𝑏16<𝑖<32 means 𝑐←𝑏║0 𝑖≥32 means 𝑐←0
@param
@return
@note
not compatible with mmx
@see
pvalignr()
@mayalias
__palignrsJump table for palignr() with non-constexpr immediate parameter.
@return
@note
needs ssse3 cf. prescott c. 2004 cf. bulldozer c. 2011
@see
palignr()
pandAnds 128-bit integers.
@param
@return
@mayalias
@see libc/intrin/pand.c
pandnNands 128-bit integers.
@param
@return
@mayalias
@see libc/intrin/pandn.c
ParseContentLengthParses Content-Length header.
@param
@return
ParseForwardedParses 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.
@param
@return
@see
RFC7239's poorly designed Forwarded header
ParseHostParses 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.
@param
@return
@see net/http/parseurl.c
ParseHostsTxtParses 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
@param
@return
@see
hoststxtsort() which is the logical next step
ParseHttpDateTimeParses HTTP timestamp, e.g. Sun, 04 Oct 2020 19:50:10 GMT
@param
@return
@see
FormatHttpDateTime()
ParseHttpMessageParses 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.
@param
@return
@note
we assume p points to a buffer that has >=SHRT_MAX bytes
@see
HTTP/1.1 RFC2616 RFC2068
@see
HTTP/1.0 RFC1945
ParseHttpRangeParses 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)
@param
@return
ParseIpParse IPv4 address.
@param
@return
@see net/http/parseip.c
ParseParamsParses HTTP POST key-value params. These are similar to the parameters found in a Request-URI. The main
difference is that 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.
@param
@return
@see net/http/parseurl.c
ParseRequestUriParses HTTP Request-URI. 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.
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. This doesn't normalize path segments like
@param
@return
@see net/http/parseurl.c
ParseResolvConfParses /etc/resolv.conf file. The content of the file usually looks like this:
nameserver 8.8.8.8 nameserver 8.8.4.4
@param
@return
ParseUrlParses 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 Please note this is a URL parser, not a URI parser. Which means we support everything 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.
@param
@return
@see
URI Generic Syntax RFC3986 RFC2396
@see
EncodeUrl()
@see net/http/parseurl.c
PascalifyDnsNameWrites 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.
@param
@return
pauseWaits 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.
@return
@see
sigsuspend()
@norestart
@see libc/calls/pause.c
pavgbAverages packed 8-bit unsigned integers w/ rounding.
@param
@return
@mayalias
@see libc/intrin/pavgb.c
pavgwAverages packed 16-bit unsigned integers w/ rounding.
@param
@return
@mayalias
@see libc/intrin/pavgw.c
pcloseCloses stream created by popen().
@param
@return
@see libc/stdio/pclose.c
pcmpeqbCompares signed 8-bit integers w/ equal to predicate.
@param
@return
@mayalias
pcmpeqdCompares signed 32-bit integers w/ equal to predicate.
@param
@return
@mayalias
pcmpeqwCompares signed 16-bit integers w/ equal to predicate.
@param
@return
@mayalias
pcmpgtbCompares signed 8-bit integers w/ greater than predicate. Note that operands can be xor'd with 0x80 for unsigned compares.
@param
@return
@mayalias
pcmpgtdCompares signed 32-bit integers w/ greater than predicate.
@param
@return
@mayalias
pcmpgtwCompares signed 16-bit integers w/ greater than predicate.
@param
@return
@mayalias
pdepParallel bit deposit.
@param
@return
@see libc/intrin/pdep.c
perrorWrites error messages to standard error.
@param
@return
@see libc/log/perror.c
pextParallel bit extract.
@param
@return
@see libc/intrin/pext.c
phadddAdds adjacent 32-bit integers.
@param
@return
@note
goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@mayalias
@see libc/intrin/phaddd.c
phaddswAdds adjacent shorts w/ saturation.
@param
@return
@note
goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@mayalias
phaddwAdds adjacent 16-bit integers.
@param
@return
@note
goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@mayalias
@see libc/intrin/phaddw.c
phsubdSubtracts adjacent 32-bit integers.
@param
@return
@note
goes fast w/ ssse3
@mayalias
@see libc/intrin/phsubd.c
phsubswSubtracts adjacent shorts w/ saturation.
@param
@return
@note
goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@mayalias
phsubwSubtracts adjacent 16-bit integers.
@param
@return
@note
goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@mayalias
@see libc/intrin/phsubw.c
pipeCreates file-less file descriptors for interprocess communication.
@param
@return
@raise
EFAULT if pipefd is NULL or an invalid address
@raise
EMFILE if RLIMIT_NOFILE is exceedde
@asyncsignalsafe
@see
pipe2()
@see libc/calls/pipe.c
pipe2Creates file-less file descriptors for interprocess communication.
@param
@return
@see libc/calls/pipe2.c
pmaddubswMultiplies bytes and adds adjacent results w/ short saturation. 𝑤ᵢ ← CLAMP[ 𝑏₂ᵢ𝑐₂ᵢ + 𝑏₍₂ᵢ₊₁₎𝑐₍₂ᵢ₊₁₎ ]
@param
@return
@note
SSSE3 w/ Prescott c. 2004, Bulldozer c. 2011
@note
greatest simd op, like, ever
@mayalias
pmaddwdMultiplies 16-bit signed integers and adds adjacent results.
@param
@return
@mayalias
pmaxswGets maximum of signed 16-bit integers.
@param
@return
@mayalias
@see libc/intrin/pmaxsw.c
pmaxubReturns minimum of 8-bit unsigned integers.
@param
@return
@mayalias
@see libc/intrin/pmaxub.c
pminswGets minimum of signed 16-bit integers.
@param
@return
@mayalias
@see libc/intrin/pminsw.c
pminubReturns minimum of 8-bit unsigned integers.
@param
@return
@mayalias
@see libc/intrin/pminub.c
pmovmskbTurns result of byte comparison into bitmask.
@param
@return
@see
pcmpeqb(), bsf(), etc.
pmulhrswMultiplies Q15 numbers.
@param
@return
@note
goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@note
a.k.a. packed multiply high w/ round & scale
@see
Q2F(15,𝑥), F2Q(15,𝑥)
@mayalias
pmulhuwMultiplies 16-bit unsigned integers and stores high word.
@param
@return
@mayalias
pmulhwMultiplies 16-bit signed integers and stores high word.
@param
@return
@mayalias
@see libc/intrin/pmulhw.c
pmulldMultiplies 32-bit integers.
@param
@return
@see
pmuludq()
@mayalias
@see libc/intrin/pmulld.c
pmullwMultiplies 16-bit signed integers.
@param
@return
@mayalias
@see libc/intrin/pmullw.c
pmuludqMultiplies 32-bit unsigned integers w/ promotion.
@param
@return
@see
pmulld()
@mayalias
pollWaits 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.
@param
@return
@asyncsignalsafe
@threadsafe
@norestart
@see libc/calls/poll.c
popcntReturns number of bits set in integer.
@param
@return
@see libc/intrin/popcnt.c
popenSpawns subprocess and returns pipe stream.
@param
@return
@see
pclose()
@see libc/stdio/popen.c
porOrs 128-bit integers.
@param
@return
@mayalias
@see libc/intrin/por.c
posix_memalignAllocates 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:
@param
@return
@see
memalign()
@threadsafe
posix_openptOpens new pseudo teletypewriter.
@param
@return
@params
flags is usually O_RDWR|O_NOCTTY
posix_spawnSpawns process the POSIX way.
@param
@return
@see libc/stdio/spawn.c
posix_spawn_file_actions_addcloseAdd a close action to object.
@param
@return
@see libc/stdio/spawnf.c
posix_spawn_file_actions_adddup2Add a dup2 action to object.
@param
@return
@see libc/stdio/spawnf.c
posix_spawn_file_actions_addopenAdd an open action to object.
@param
@return
@see libc/stdio/spawnf.c
posix_spawn_file_actions_destroyFrees object storage and make invalid.
@param
@return
@see libc/stdio/spawnf.c
posix_spawn_file_actions_initCreates object with no actions.
@param
@return
@see libc/stdio/spawnf.c
posix_spawnattr_getflags
@param
@return
@see libc/stdio/spawna.c
posix_spawnattr_getpgroup
@param
@return
@see libc/stdio/spawna.c
posix_spawnattr_getschedparam
@param
@return
@see libc/stdio/spawna.c
posix_spawnattr_getschedpolicy
@param
@return
@see libc/stdio/spawna.c
posix_spawnattr_getsigdefault
@param
@return
@see libc/stdio/spawna.c
posix_spawnattr_getsigmask
@param
@return
@see libc/stdio/spawna.c
posix_spawnattr_initInitialize object with default values.
@param
@return
@see libc/stdio/spawna.c
posix_spawnattr_setflags
@param
@return
@see libc/stdio/spawna.c
posix_spawnattr_setpgroup
@param
@return
@see libc/stdio/spawna.c
posix_spawnattr_setschedparam
@param
@return
@see libc/stdio/spawna.c
posix_spawnattr_setschedpolicy
@param
@return
@see libc/stdio/spawna.c
posix_spawnattr_setsigdefault
@param
@return
@see libc/stdio/spawna.c
posix_spawnattr_setsigmask
@param
@return
@see libc/stdio/spawna.c
posix_spawnpSpawns process the POSIX way w/ PATH search.
@param
@return
@see libc/stdio/spawnp.c
powReturns 𝑥^𝑦.
@param
@return
pow10Returns 10^x.
@param
@return
@see
pow(), exp()
pow10fReturns 10^x.
@param
@return
pow10lReturns 10^x.
@param
@return
powfReturns 𝑥^𝑦.
@param
@return
powiReturns 𝑥^𝑦.
@param
@return
@see libc/tinymath/powi.S
powifReturns 𝑥^𝑦.
@param
@return
prctlTunes process on Linux.
@param
@return
@raise
ENOSYS on non-Linux
@see libc/calls/prctl.c
preadReads from file at offset, thus avoiding superfluous lseek().
@param
@return
@see
pwrite(), write()
@asyncsignalsafe
@vforksafe
@see libc/calls/pread.c
preadvReads with maximum generality.
@param
@return
@asyncsignalsafe
@vforksafe
@see libc/calls/preadv.c
__printargsPrints lots of information about this process, e.g. __printargs("");This is called automatically in MODE=dbg if --strace is used.
@param
@return
PrintBacktraceUsingSymbolsPrints stack frames with symbols. PrintBacktraceUsingSymbols(STDOUT_FILENO, NULL, GetSymbolTable());
@param
@return
printfFormats and writes text to stdout. Cosmopolitan supports most of the standard formatting behaviors
described by
@param
@return
@see
__fmt() for intuitive reference documentation
@see
{,v}{,s{,n},{,{,x}as},f,d}printf
@see libc/stdio/printf.c
PrintGarbageNumericPrints list of deferred operations on shadow stack w/o symbols.
@param
@return
program_invocation_nameSupplies argv[0] the GNU way. If argv[0] isn't supplied, this value will be null.
@return
@see
program_invocation_short_name
@see
GetProgramExecutableName()
program_invocation_short_nameSupplies basename(argv[0]) The GNU Way. If argv[0] isn't supplied, this value will be null.
@return
@see
GetProgramExecutableName()
@see
program_invocation_name
psadbwComputes sum of absolute differences.
@param
@return
@mayalias
@see libc/intrin/psadbw.c
pselectDoes what poll() does except with bitset API. This system call is supported on all platforms. It's like select() except that it atomically changes the sigprocmask() during the op.
@param
@return
@see libc/sock/pselect.c
pshufbShuffles and/or clears 8-bit integers.
@param
@return
@note
goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@note
doesn't perfectly emulate mmx
@mayalias
@see libc/intrin/pshufb.c
pshufdShuffles int vector.
@param
@return
@mayalias
@see libc/intrin/pshufd.c
pshufhwShuffles lower half of word vector.
@param
@return
@mayalias
pshuflwShuffles lower half of word vector.
@param
@return
@mayalias
pshufwShuffles mmx vector.
@param
@return
@mayalias
@see libc/intrin/pshufw.c
psignbConditionally negates or zeroes signed bytes.
@param
@return
@note
goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@see libc/intrin/psignb.c
psigndConditionally negates or zeroes ints.
@param
@return
@note
goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@see libc/intrin/psignd.c
psignwConditionally negates or zeroes shorts.
@param
@return
@note
goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@see libc/intrin/psignw.c
pslldMultiplies ints by two power.
@param
@return
@note
c needs to be a literal, asmconstexpr, or linkconstsym
@mayalias
@see libc/intrin/pslld.c
pslldqShifts vector left by n bytes w/ zero-fill.
@param
@return
@mayalias
@see libc/intrin/pslldq.c
pslldvMultiplies ints by two power.
@param
@return
@mayalias
@see libc/intrin/pslldv.c
psllqMultiplies longs by two power.
@param
@return
@note
c needs to be a literal, asmconstexpr, or linkconstsym
@mayalias
@see libc/intrin/psllq.c
psllqvMultiplies longs by two power.
@param
@return
@mayalias
@see libc/intrin/psllqv.c
psllwMultiplies shorts by two power.
@param
@return
@note
c needs to be a literal, asmconstexpr, or linkconstsym
@mayalias
@see libc/intrin/psllw.c
psllwvMultiplies shorts by two power.
@param
@return
@mayalias
@see libc/intrin/psllwv.c
psradDivides ints by two power.
@param
@return
@note
c needs to be a literal, asmconstexpr, or linkconstsym
@note
arithmetic shift right will sign extend negatives
@mayalias
@see libc/intrin/psrad.c
psradvDivides shorts by two powers.
@param
@return
@note
arithmetic shift right will sign extend negatives
@mayalias
@see libc/intrin/psradv.c
psrawDivides shorts by two power.
@param
@return
@note
c needs to be a literal, asmconstexpr, or linkconstsym
@note
arithmetic shift right will sign extend negatives
@mayalias
@see libc/intrin/psraw.c
psrawvDivides shorts by two power.
@param
@return
@note
arithmetic shift right will sign extend negatives
@mayalias
@see libc/intrin/psrawv.c
psrldDivides unsigned ints by two power.
@param
@return
@note
c needs to be a literal, asmconstexpr, or linkconstsym
@note
logical shift does not sign extend negatives
@mayalias
@see libc/intrin/psrld.c
psrldqShifts vector left by n bytes w/ zero-fill.
@param
@return
@mayalias
@see libc/intrin/psrldq.c
psrldvDivides ints by two power.
@param
@return
@note
logical shift does not sign extend negatives
@mayalias
@see libc/intrin/psrldv.c
psrlqDivides unsigned longs by two power.
@param
@return
@note
c needs to be a literal, asmconstexpr, or linkconstsym
@note
logical shift does not sign extend negatives
@mayalias
@see libc/intrin/psrlq.c
psrlqvDivides unsigned longs by two power.
@param
@return
@note
logical shift does not sign extend negatives
@mayalias
@see libc/intrin/psrlqv.c
psrlwDivides unsigned shorts by two power.
@param
@return
@note
c needs to be a literal, asmconstexpr, or linkconstsym
@note
logical shift does not sign extend negatives
@mayalias
@see libc/intrin/psrlw.c
psrlwvDivides unsigned shorts by two power.
@param
@return
@note
logical shift does not sign extend negatives
@mayalias
@see libc/intrin/psrlwv.c
psubbSubtracts 8-bit integers.
@param
@return
@mayalias
@see libc/intrin/psubb.c
psubdSubtracts 32-bit integers.
@param
@return
@mayalias
@see libc/intrin/psubd.c
psubqSubtracts 64-bit integers.
@param
@return
@mayalias
@see libc/intrin/psubq.c
psubsbSubtracts signed 8-bit integers w/ saturation.
@param
@return
@mayalias
@see libc/intrin/psubsb.c
psubswSubtracts signed 16-bit integers w/ saturation.
@param
@return
@mayalias
@see libc/intrin/psubsw.c
psubusbSubtracts unsigned 8-bit integers w/ saturation.
@param
@return
@mayalias
psubuswSubtracts unsigned 16-bit integers w/ saturation.
@param
@return
@mayalias
psubwSubtracts 16-bit integers.
@param
@return
@mayalias
@see libc/intrin/psubw.c
pthread_mutex_destroyDestroys mutex.
@param
@return
pthread_mutex_initInitializes mutex.
@param
@return
pthread_mutex_lockLocks mutex. _spinlock() l: 181,570c 58,646ns mutex normal l: 297,965c 96,241ns mutex recursive l: 1,112,166c 359,223ns mutex errorcheck l: 1,449,723c 468,252ns
@param
@return
pthread_mutex_unlockReleases mutex.
@param
@return
@raises
EPERM if in error check mode and not owned by caller
pthread_mutexattr_destroyDestroys mutex attr.
@param
@return
pthread_mutexattr_gettypeGets mutex type.
@param
@return
pthread_mutexattr_initInitializes mutex attr.
@param
@return
pthread_mutexattr_settypeSets mutex type.
@param
@return
@raises
EINVAL if
type is invalid
pthread_setspecificSets value of TLS slot for current thread.
@param
@return
ptraceTraces process.
@param
@return
@note
de facto linux only atm
@vforksafe
@see libc/calls/ptrace.c
puff
@param
@return
punpckhbwInterleaves high bytes.
@param
@return
@mayalias
punpckhdqInterleaves high doublewords. 0 1 2 3 B aaaa bbbb CCCC DDDD C eeee ffff GGGG HHHH └┬─┘ └─┬┘ ┌────┘ │ ┌─────┴─┐ ┌──────┴┐ → A CCCC GGGG DDDD HHHH
@param
@return
@mayalias
punpckhqdqInterleaves high quadwords.
@param
@return
@mayalias
punpckhwdInterleaves high words. 0 1 2 3 4 5 6 7 B aa bb cc dd EE FF GG HH C ii jj kk ll MM NN OO PP └┤ └┤ └┤ └┤ ┌────────┘ │ │ │ │ ┌─────┘ │ │ │ │ ┌──┘ │ ┌───┤ ┌───┤ ┌───┤ ┌───┤ → A EE MM FF NN GG OO HH PP
@param
@return
@mayalias
punpcklbwInterleaves low bytes. 0 1 2 3 4 5 6 7 8 9 A B C D E F B A B C D E F G H i j k l m n o p C Q R S T U V W X y z α σ π μ τ ε │ │ │ │ │ │ │ │ │ │ │ └─────┐ │ │ └───┐ │ etc... │ └─┐ │ │ ├─┐ ├─┐ ├─┐ ├─┐ → A A Q B R C S D T E U F V G W H X
@param
@return
@mayalias
punpckldqInterleaves low doublewords. 0 1 2 3 B AAAA BBBB cccc dddd C EEEE FFFF gggg hhhh └┬─┘ └─┬┘ │ └───┐ ┌┴──────┐ ┌┴──────┐ → A AAAA EEEE BBBB FFFF
@param
@return
@mayalias
punpcklqdqInterleaves low quadwords.
@param
@return
@mayalias
punpcklwdInterleaves low words. 0 1 2 3 4 5 6 7 B AA BB CC DD ee ff gg hh C II JJ KK LL mm nn oo pp ├┘ ├┘ ├┘ ├┘ │ │ │ └────────┐ │ │ └─────┐ │ │ └──┐ │ │ ├───┐ ├───┐ ├───┐ ├───┐ → A AA II BB JJ CC KK DD LL
@param
@return
@mayalias
putcWrites byte to stream.
@param
@return
@threadsafe
@see libc/stdio/putc.c
putc_unlockedWrites byte to stream.
@param
@return
putcharWrites byte to stdout.
@param
@return
@threadsafe
@see libc/stdio/putchar.c
putchar_unlockedWrites byte to stdout.
@param
@return
putenvEmplaces environment key=value.
@param
@return
@see
setenv(), getenv()
@see libc/mem/putenv.c
putsWrites string w/ trailing newline to stdout.
@param
@return
@see libc/stdio/puts.c
pututf16Encodes character to string as UTF-16. Implementation Details: The header macro should ensure this function is only called for truly huge codepoints. Plus this function makes a promise to not clobber any registers but %rax.
@param
@return
@todo
delete
putwcWrites wide character to stream.
@param
@return
@threadsafe
@see libc/stdio/putwc.c
putwc_unlockedWrites wide character to stream.
@param
@return
putwcharWrites wide character to stdout.
@param
@return
@threadsafe
putwchar_unlockedWrites wide character to stdout.
@param
@return
pvallocEquivalent to memalign(PAGESIZE, ROUNDUP(n, PAGESIZE)).
@param
@return
@see
valloc()
@threadsafe
@see libc/mem/pvalloc.c
pwriteWrites to file at offset, thus avoiding superfluous lseek().
@param
@return
@see
pread(), write()
@asyncsignalsafe
@vforksafe
@see libc/calls/pwrite.c
pwritevWrites data from multiple buffers to offset. Please note that it's not an error for a short write to happen. This can happen in the kernel if EINTR happens after some of the write has been committed. It can also happen if we need to polyfill this system call using pwrite().
@param
@return
@asyncsignalsafe
@vforksafe
@see libc/calls/pwritev.c
pxorXors 128-bit integers.
@param
@return
@mayalias
@see libc/intrin/pxor.c
qsortSorts array.
@param
@return
@see
longsort(), djbsort()
@see libc/str/qsort.c
qsort_rSorts array.
@param
@return
@see
qsort()
@see libc/str/qsort.c
quick_exitExits process faster.
@param
@noreturn
raiseSends signal to this process.
@param
@return
@asyncsignalsafe
@see libc/calls/raise.c
randReturns 31-bit linear congruential pseudorandom number, e.g. int x = rand(); assert(x >= 0);This function always returns a positive number. If srand() isn't called, then it'll return the same sequence each time your program runs. Faster and more modern alternatives exist to this function. This function is not thread safe in the sense that multiple threads might simultaneously generate the same random values.
@return
@note
this function does well on bigcrush and practrand
@note
this function is not intended for cryptography
@see
lemur64(), rand64(), rdrand()
@see libc/rand/rand.c
rand64Returns nondeterministic random data. This function is similar to lemur64() except that it doesn't produce the same sequences of numbers each time your program is run. This is the case even across forks and threads, whose sequences will differ.
@return
@see
rdseed(), rdrand(), rand(), random(), rngset()
@note
this function takes 5 cycles (30 if
__threaded )
@note
this function is not intended for cryptography
@note
this function passes bigcrush and practrand
@asyncsignalsafe
@threadsafe
@vforksafe
@see libc/rand/rand64.c
rawmemchr16Returns pointer to first instance of character in range.
@param
@return
rawwmemchrReturns pointer to first instance of character in range.
@param
@return
rdrandRetrieves 64-bits of hardware random data from RDRAND instruction. If RDRAND isn't available (we check CPUID and we also disable it automatically for microarchitectures where it's slow or buggy) then we try getrandom(), RtlGenRandom(), or sysctl(KERN_ARND). If those aren't available then we try /dev/urandom and if that fails, we try getauxval(AT_RANDOM), and if not we finally use RDTSC and getpid().
@return
@note
this function could block a nontrivial time on old computers
@note
this function is indeed intended for cryptography
@note
this function takes around 300 cycles
@see
rngset(), rdseed(), rand64()
@asyncsignalsafe
@vforksafe
@see libc/rand/rdrand.c
rdseedRetrieves 64-bits of true random data from RDSEED instruction. If RDSEED isn't available, we'll try RDRAND (which we automatically disable for microarchitectures where it's known to be slow or buggy). If RDRAND isn't available then we try getrandom(), RtlGenRandom(), or sysctl(KERN_ARND). If those aren't available then we try /dev/urandom and if that fails, we use RDTSC and getpid().
@return
@note
this function could block a nontrivial time on old computers
@note
this function is indeed intended for cryptography
@note
this function takes around 800 cycles
@see
rngset(), rdrand(), rand64()
@asyncsignalsafe
@vforksafe
@see libc/rand/rdseed.c
readReads data from file descriptor.
@param
@return
@see
write(), pread(), readv()
@asyncsignalsafe
@restartable
@see libc/calls/read.c
readansiReads single keystroke or control sequence from character device. When reading ANSI UTF-8 text streams, characters and control codes are oftentimes encoded as multi-byte sequences. This function knows how long each sequence is, so that each read consumes a single thing from the underlying file descriptor, e.g.
"a" ALFA "\316\261" ALPHA "\e[38;5;202m" ORANGERED "\e[A" UP "\e\e[A" ALT-UP "\001" CTRL-ALFA "\e\001" ALT-CTRL-ALFA "\eOP" PF1 "\000" NUL "\e]rm -rf /\e\\" OSC "\302\233A" UP "\300\200" NULThis routine generalizes to ascii, utf-8, chorded modifier keys, function keys, color codes, c0/c1 control codes, cursor movement, mouse movement, etc. Userspace buffering isn't required, since ANSI escape sequences and UTF-8 are decoded without peeking. Noncanonical overlong encodings can cause the stream to go out of sync. This function recovers such events by ignoring continuation bytes at the beginning of each read.
@param
@return
@see
examples/ttyinfo.c
@see
ANSI X3.64-1979
@see
ISO/IEC 6429
@see
FIPS-86
@see
ECMA-48
readdirReads next entry from directory stream. This API doesn't define any particular ordering.
@param
@return
readlinkReads symbolic link.
@param
@return
@see
readlinkat(AT_FDCWD, ...) for modern version of this
@error
EINVAL if path isn't a symbolic link
@asyncsignalsafe
readlinkatReads symbolic link. This does *not* nul-terminate the buffer.
@param
@return
@error
EINVAL if path isn't a symbolic link
@asyncsignalsafe
readvReads data to multiple buffers. This is the same thing as read() except it has multiple buffers. This yields a performance boost in situations where it'd be expensive to stitch data together using memcpy() or issuing multiple syscalls. This wrapper is implemented so that readv() calls where iovlen<2 may be passed to the kernel as read() instead. This yields a 100 cycle performance boost in the case of a single small iovec.
@param
@return
@restartable
@see libc/calls/readv.c
_real1Generates number on [0,1]-real-interval, e.g. double x = _real1(lemur64())
@param
@return
@see
lemur64(), mt19937()
@see libc/rand/real1.c
_real2Generates number on [0,1)-real-interval, e.g. double x = _real2(lemur64())
@param
@return
@see
lemur64(), mt19937()
@see libc/rand/real2.c
_real3Generates number on (0,1)-real-interval, e.g. double x = _real3(lemur64())
@param
@return
@see
lemur64(), mt19937()
@see libc/rand/real3.c
reallocAllocates / resizes / frees memory, e.g. Returns a pointer to a chunk of size n that contains the same data as does chunk p up to the minimum of (n, p's size) bytes, or null if no space is available. If p is NULL, realloc is equivalent to malloc. If p is not NULL and n is 0, realloc is equivalent to free. The returned pointer may or may not be the same as p. The algorithm prefers extending p in most cases when possible, otherwise it employs the equivalent of a malloc-copy-free sequence. Please note that p is NOT free()'d should realloc() fail, thus:
if ((p2 = realloc(p, n2))) { p = p2; ... } else { ... }if n is for fewer bytes than already held by p, the newly unused space is lopped off and freed if possible. The old unix realloc convention of allowing the last-free'd chunk to be used as an argument to realloc is not supported.
@param
@return
@note
realloc(p=0, n=0) → malloc(32)
@note
realloc(p≠0, n=0) → free(p)
@see
dlrealloc()
@threadsafe
@see libc/mem/realloc.S
realloc_in_placeResizes the space allocated for p to size n, only if this can be done without moving p (i.e., only if there is adjacent space available if n is greater than p's current allocated size, or n is less than or equal to p's size). This may be used instead of plain realloc if an alternative allocation strategy is needed upon failure to expand space, for example, reallocation of a buffer that must be memory-aligned or cleared. You can use realloc_in_place to trigger these alternatives only when needed.
@param
@return
@see
dlrealloc_in_place()
@threadsafe
reallocarrayManages array memory, the BSD way.
@param
@return
@threadsafe
realpathReturns absolute pathname. This function removes
@param
@return
rebootReboots system. The
sync() operation before the reboot happens.
This can be prevented by or'ing howto with RB_NOSYNC . Setting
this option will also prevent apps on Windows from having time to
close themselves.
@param
@return
@see libc/calls/reboot.c
recvReceives data from network socket.
@param
@return
@error
EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable),
EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
@asyncsignalsafe
@restartable
(unless SO_RCVTIMEO)
@see libc/sock/recv.c
recvfromReceives data from network. This function blocks unless MSG_DONTWAIT is passed.
@param
@return
@error
EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable),
EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
@asyncsignalsafe
@restartable
(unless SO_RCVTIMEO)
@see libc/sock/recvfrom.c
recvmsgSends a message from a socket.
@param
@return
@error
EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable),
EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
@asyncsignalsafe
@restartable
(unless SO_RCVTIMEO)
@see libc/sock/recvmsg.c
regcompCompiles regular expression, e.g. regex_t rx; CHECK_EQ(REG_OK, regcomp(&rx, "^[A-Za-z]{2}$", REG_EXTENDED)); CHECK_EQ(REG_OK, regexec(&rx, "→A", 0, NULL, 0)); regfree(&rx);
@param
@return
@see
regexec(), regfree(), regerror()
regerrorConverts regular expression error code to string.
@param
@return
regexecExecutes regular expression.
@param
@return
regfreeFrees any memory allocated by regcomp(). The same object may be destroyed by regfree() multiple times, in which case subsequent calls do nothing. Once a regex is freed, it may be passed to regcomp() to reinitialize it.
@param
@return
remainderremainder(𝑥,𝑦) means (𝑥 rem 𝑦) w/ rint()-style rounding.
@param
@return
@define
𝑥-rint(𝑥/𝑦)*𝑦
@see
fmod(), emod(), operator%
removeDeletes "file" or empty directory associtaed with name.
@param
@return
@see
unlink() and rmdir() which this abstracts
@see libc/calls/remove.c
RemoveDirectoryDeletes existing empty directory on the New Technology.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
remquolComputes remainder and part of quotient.
@param
@return
renameMoves file the Unix way. This is generally an atomic operation with the file system, since all
it's doing is changing a name associated with an inode. However, that
means rename() doesn't permit your
@param
@return
@asyncsignalsafe
@see libc/calls/rename.c
renameatRenames files relative to directories. This is generally an atomic operation with the file system, since all
it's doing is changing a name associated with an inode. However, that
means rename() doesn't permit your
@param
@return
ReOpenFileReopens file on the New Technology.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
replacestrReplaces all instances of NEEDLE in S with REPLACEMENT.
@param
@return
@error
ENOMEM, EINVAL
replaceuserReplaces tilde in path w/ user home folder.
@param
@return
@see libc/x/replaceuser.c
__replmodeControls ANSI prefix for log emissions. This should be true in raw tty mode repls.
@type
@see
kprintf(), vflogf(), linenoise()
__reservefdFinds open file descriptor slot.
@param
@return
@asyncsignalsafe
@threadsafe
ResolveDnsQueries Domain Name System for address associated with name.
@param
@return
@error
EAFNOSUPPORT. ENETDOWN, ENAMETOOLONG, EBADMSG
ResolveDnsReversePerforms reverse DNS lookup with IP address.
@param
@return
@error
EAFNOSUPPORT, ENETDOWN, ENAMETOOLONG, EBADMSG
ResolveHostsReverseFinds name associated with address in HOSTS.TXT table.
@param
@return
@error
EAFNOSUPPORT
ResolveHostsTxtFinds address associated with name in HOSTS.TXT table.
@param
@return
@error
EAFNOSUPPORT
rewindMoves standard i/o stream to beginning of file. Like fseek(), this function can be used to restore a stream from the EOF state, without reopening it.
@param
@return
@see libc/stdio/rewind.c
rindexReturns pointer to last instance of character the BSD way.
@param
@return
@see libc/str/rindex.S
rintRounds to nearest integer.
@param
@return
@note
rounding behavior can be changed in mxcsr
@see libc/tinymath/rint.S
rintlRounds to nearest integer.
@param
@return
@note
rounding behavior can be changed in control word
rldecodeThirteen byte decompressor.
@param
@return
@mode
long,legacy,real
rmdirDeletes empty directory.
@param
@return
@see libc/calls/rmdir.c
rngsetFills memory with random bytes, e.g. char buf[512]; rngset(buf, sizeof(buf), 0, 0);If reseed is zero then the internal PRNG is disabled and bytes are simply copied in little-endian order from the seed function. If seed is NULL then the reseed parameter is used as the seed value for the internal PRNG. If seed!=NULL and reseed>8 then reseed is the number of bytes after which the seed() function should be called again, to freshen up the PRNG. The main advantage of this generator is that it produces data at 13 gigabytes per second since Vigna's Algorithm vectorizes better than alternatives, going even faster than xorshift.
@param
@return
@see libc/rand/rngset.c
roundRounds to nearest integer, away from zero.
@param
@return
@define
round(𝑥) = copysign(trunc(fabs(𝑥)+.5),𝑥)
round(𝑥) = trunc(𝑥+copysign(.5,𝑥))
rounddown2powReturns 𝑥 rounded down to previous two power.
@param
@return
@define
(𝑥>0→2^⌊log₂𝑥⌋, x=0→0, 𝑇→⊥)
@see
roundup2pow()
roundfRounds to nearest integer, away from zero.
@param
@return
roundlRounds to nearest integer, away from zero.
@param
@return
roundup2logReturns 𝑥 rounded up to next two power and log'd.
@param
@return
@see
roundup2pow()
roundup2powReturns 𝑥 rounded up to next two power.
@param
@return
@define
(𝑥>0→2^⌈log₂x⌉, x=0→0, 𝑇→⊥)
@see
rounddown2pow()
rt_end
@param
@return
@see libc/rand/randtest.c
__sample_pidsReturns handles of windows pids being tracked. We return 64 at most because Windows can't await on a larger number of things at the same time. If we have a lot of subprocesses, then we choose a subgroup to monitor at random.
@param
@return
_savexmmStores XMM registers to buffer.
@param
@return
@note
modern cpus have out-of-order execution engines
sbrkAdjusts end of data section. This shrinks or increases the program break by delta bytes. On success, the previous program break is returned. It's possible to pass zero to this function to get the current program break
@param
@return
@see
mmap(), brk(), _end
@see libc/runtime/brk.c
scalbReturns 𝑥 × 2ʸ.
@param
@return
@see
ldexp()
scalbfReturns 𝑥 × 2ʸ.
@param
@return
@see
ldexpf()
scalblReturns 𝑥 × 2ʸ.
@param
@return
@see
ldexpl()
scalblnlReturns 𝑥 × 2ʸ.
@param
@return
scalbnlReturns 𝑥 × 2ʸ.
@param
@return
scanfStandard input decoder.
@param
@return
@see
libc/fmt/vcscanf.h
@see libc/stdio/scanf.c
sched_get_priority_maxReturns maximum
@param
@return
@raise
ENOSYS on XNU, Windows, OpenBSD
@raise
EINVAL if
policy is invalid
sched_get_priority_minReturns minimum
@param
@return
@raise
ENOSYS on XNU, Windows, OpenBSD
@raise
EINVAL if
policy is invalid
sched_getaffinityGets kernel scheduling for particular CPUs.
@param
@return
@raise
ENOSYS on non-Linux
sched_getparamGets scheduler policy parameter.
@param
@return
@raise
ENOSYS on XNU, Windows
sched_getschedulerGets scheduler policy for
@param
@return
@error
ESRCH if
pid not found
@error
EPERM if not permitted
@error
EINVAL if
pid is negative on Linux
sched_rr_get_intervalReturns round-robin
@param
@return
@error
ENOSYS if not Linux or FreeBSD
@error
EFAULT if
tp memory is invalid
@error
EINVAL if invalid
pid
@error
ESRCH if could not find
pid
sched_setaffinityAsks kernel to only schedule process on particular CPUs.
@param
@return
@raise
ENOSYS if not Linux or Windows
sched_setparamSets scheduler policy parameter.
@param
@return
@raise
ENOSYS on XNU, Windows
sched_setschedulerSets scheduling policy of process, e.g. struct sched_param p = {sched_get_priority_max(SCHED_OTHER)}; LOGIFNEG1(sched_setscheduler(0, SCHED_OTHER, &p));Processes with numerically higher priority values are scheduled before processes with numerically lower priority values.
@param
@return
@raise
ENOSYS on XNU, Windows, OpenBSD
@raise
EPERM if not authorized to use scheduler in question (e.g.
trying to use a real-time scheduler as non-root on Linux) or
possibly because pledge() was used and isn't allowing this
@raise
EINVAL if
param is NULL
@raise
EINVAL if
policy is invalid
@raise
EINVAL if
param has value out of ranges defined by policy
sched_yieldAsks kernel to let other threads be scheduled.
@return
@norestart
seccompTunes Linux security policy. This system call was first introduced in Linux 3.17. We polyfill automatically features like SECCOMP_SET_MODE_STRICT, for kernels dating back to 2.6.23, whenever possible.
@param
@return
@raise
ENOSYS on non-Linux.
@see libc/calls/seccomp.c
selectDoes what poll() does except with bitset API. This system call is supported on all platforms. However, on Windows, this is polyfilled to translate into poll(). So it's recommended that poll() be used instead.
@param
@return
@see libc/sock/select.c
sendSends data to network socket.
@param
@return
@error
EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable),
EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
@asyncsignalsafe
@restartable
(unless SO_RCVTIMEO)
@see libc/sock/send.c
sendfileTransfers data from file to network.
@param
@return
@see
copy_file_range() for file ↔ file
@see
splice() for fd ↔ pipe
@see libc/sock/sendfile.c
sendmsgSends a message on a socket.
@param
@return
@error
EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable),
EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
@asyncsignalsafe
@restartable
(unless SO_RCVTIMEO)
@see libc/sock/sendmsg.c
sendtoSends data over network. This function blocks unless MSG_DONTWAIT is passed. In that case, the non-error EWOULDBLOCK might be returned. It basically means we didn't wait around to learn an amount of bytes were written that we know in advance are guaranteed to be atomic.
@param
@return
@error
EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable),
EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
@asyncsignalsafe
@restartable
(unless SO_RCVTIMEO)
@see libc/sock/sendto.c
SerializeDnsHeaderSerializes DNS message h to wire.
@param
@return
@see
pascalifydnsname()
@see libc/dns/dnsheader.c
SerializeDnsQuestionSerializes DNS question record to wire.
@param
@return
@see
pascalifydnsname()
setbufSets buffer on stdio stream.
@param
@return
@see libc/stdio/setbuf.c
setbufferSets buffer on stdio stream.
@param
@return
setcontextSets machine state.
@return
@note
please use longerjmp() and setlongerjmp() for fibers
@note
currently only sets general registers
@see
getcontext()
SetCurrentDirectorySets current directory.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
setegidSets effective group ID.
@param
@return
@raise
EINVAL if euid not in legal range
@raise
EPERM if lack privileges
@see libc/calls/setegid.c
setenvCopies variable to environment.
@param
@return
@see
putenv(), getenv()
@see libc/mem/setenv.c
seteuidSets effective user ID.
@param
@return
@raise
EINVAL if euid not in legal range
@raise
EPERM if lack privileges
@see libc/calls/seteuid.c
setfsgidSets user id of current process for file system ops.
@param
@return
setfsuidSets user id of current process for file system ops.
@param
@return
setgidSets group id of current process.
@param
@return
@raise
EINVAL if gid not in legal range
@raise
EPERM if lack privileges
@see libc/calls/setgid.c
setitimerSchedules delivery of one-shot or intermittent interrupt signal, e.g. Raise SIGALRM every 1.5s:
CHECK_NE(-1, sigaction(SIGALRM, &(struct sigaction){.sa_sigaction = missingno}, NULL)); CHECK_NE(-1, setitimer(ITIMER_REAL, &(const struct itimerval){{1, 500000}, {1, 500000}}, NULL));Set single-shot 50ms timer callback to interrupt laggy connect():
CHECK_NE(-1, sigaction(SIGALRM, &(struct sigaction){.sa_sigaction = missingno, .sa_flags = SA_RESETHAND}, NULL)); CHECK_NE(-1, setitimer(ITIMER_REAL, &(const struct itimerval){{0, 0}, {0, 50000}}, NULL)); if (connect(...) == -1 && errno == EINTR) { ... }Disarm timer:
CHECK_NE(-1, setitimer(ITIMER_REAL, &(const struct itimerval){0}, NULL));Be sure to check for EINTR on your i/o calls, for best low latency. Timers are not inherited across fork.
@param
@return
setjmpSaves caller CPU state to cacheline.
@param
@return
@returnstwice
@assume
system five nexgen32e abi conformant
@note
code built w/ microsoft abi compiler can't call this
@see
longjmp(), _gclongjmp()
_setjmpSaves caller CPU state to cacheline.
@param
@return
@returnstwice
@assume
system five nexgen32e abi conformant
@note
code built w/ microsoft abi compiler can't call this
@see
longjmp(), _gclongjmp()
setlocaleSets program locale. Cosmopolitan only supports the C or POSIX locale.
@param
@return
setlogmaskSets log priority mask Modifies the log priority mask that determines which calls to syslog() may be logged. Log priority values are LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, and LOG_DEBUG.
@param
@return
@asyncsignalsafe
@see libc/sock/syslog.c
setlongerjmpSaves caller CPU state to cacheline.
@param
@return
@returnstwice
setpgidChanges process group for process.
@param
@return
@vforksafe
@see libc/calls/setpgid.c
setprioritySets nice value of thing.
@param
@return
@error
EACCES if lower that RLIMIT_NICE
@error
EACCES on Linux without CAP_SYS_NICE
@see
getpriority(), nice()
setregidSets real and/or effective group ids.
@param
@return
setresgidSets real, effective, and "saved" group ids.
@param
@return
@see
setresuid(), getauxval(AT_SECURE)
@raise
ENOSYS on Windows NT
setresuidSets real, effective, and "saved" user ids.
@param
@return
@see
setresgid(), getauxval(AT_SECURE)
@raise
ENOSYS on Windows NT
setreuidSets real and/or effective user ids.
@param
@return
setrlimitSets resource limit for current process. The following resources are recommended:
RLIM_NLIMITS . Usually they're set to RLIM_INFINITY
which is -1 on Linux/Windows, and LONG_MAX on BSDs. In any case
they're both very large numbers under the Cosmopolitan unsigned ABI
because struct rlimit uses uint64_t. The special magnum 127 is used
for constant values that aren't supported by the host platform.
@param
@return
@see
libc/sysv/consts.sh
@vforksafe
setsidCreates session and sets the process group id.
@return
@see libc/calls/setsid.c
setsockoptModifies socket settings. This function is the ultimate rabbit hole. Basic usage: int yes = 1; setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes));
@param
@return
@error
ENOPROTOOPT for unknown (level,optname)
@error
EINVAL if
optlen is invalid somehow
@error
ENOTSOCK if
fd is valid but not a socket
@error
EBADF if
fd isn't valid
@error
EFAULT if optval memory isn't valid
@see
libc/sysv/consts.sh for tuning catalogue
@see
getsockopt()
_setstackSwitches stack.
@param
@return
setuidSets user id of current process.
@param
@return
@raise
EINVAL if uid not in legal range
@raise
EAGAIN on temporary failure
@raise
EAGAIN change would cause
RLIMIT_NPROC to be exceeded
@raise
EPERM if lack privileges
@see libc/calls/setuid.c
SetUpUser-defined test setup function. The test runner will call this function before each TEST() if it's defined by the linkage.
@return
setvbufTunes buffering settings for an stdio stream.
@param
@return
@see libc/stdio/setvbuf.c
sha1_transform_avx2Performs Intel® AVX2™ optimized SHA-1 update. This implementation is based on the previous SSSE3 release: Visit http://software.intel.com/en-us/articles/ and refer to improving-the-performance-of-the-secure-hash-algorithm-1/ Updates 20-byte SHA-1 record at start of 'state', from 'input', for even number of 'blocks' consecutive 64-byte blocks.
void sha1_transform_avx2(struct sha1_state *state, const uint8_t *input, int blocks);
@param
@return
@see
X86_HAVE(SHA)
sha1_transform_niPerforms Intel® SHA-NI™ optimized SHA-1 update. The function takes a pointer to the current hash values, a pointer to the input data, and a number of 64 byte blocks to process. Once all blocks have been processed, the digest pointer is updated with the resulting hash value. The function only processes complete blocks, there is no functionality to store partial blocks. All message padding and hash value initialization must be done outside the update function. The indented lines in the loop are instructions related to rounds processing. The non-indented lines are instructions related to the message schedule.
void sha1_transform_ni(uint32_t digest[static 5], const void *data, uint32_t numBlocks);
@param
@return
@see
X86_HAVE(SHA)
sha256_transform_niPerforms Intel® SHA-NI™ optimized SHA-256 update. The function takes a pointer to the current hash values, a pointer to the input data, and a number of 64 byte blocks to process. Once all blocks have been processed, the digest pointer is updated with the resulting hash value. The function only processes complete blocks, there is no functionality to store partial blocks. All message padding and hash value initialization must be done outside the update function. The indented lines in the loop are instructions related to rounds processing. The non-indented lines are instructions related to the message schedule.
void sha256_transform_ni(uint32_t digest[static 8], const void *data, int32_t numBlocks);
@param
@return
@see
X86_HAVE(SHA)
ShowCrashReport
@param
@return
@see libc/log/oncrash.c
ShowCrashReportsInstalls crash signal handlers. Normally, only functions calling die() will print backtraces. This function may be called at program startup to install handlers that will display similar information, for most types of crashes.
@return
@see
callexitontermination()
shufpdShuffles double vector.
@param
@return
@mayalias
@see libc/intrin/shufpd.c
shufpsShuffles float vector.
@param
@return
@mayalias
@see libc/intrin/shufps.c
shutdownDisables sends or receives on a socket, without closing.
@param
@return
@asyncsignalsafe
@see libc/sock/shutdown.c
__sig_addEnqueues generic signal for delivery on New Technology.
@param
@return
@threadsafe
@see libc/calls/sig2.c
__sig_checkEnqueues generic signal for delivery on New Technology.
@param
@return
@note
called from main thread
@threadsafe
@see libc/calls/sig2.c
__sig_handleHandles signal.
@param
@return
@see libc/calls/sig2.c
__sig_maskChanges signal mask for main thread.
@param
@return
@see libc/calls/sig.c
__sig_raiseHandles signal immediately if not blocked.
@param
@return
@note
called from main thread
@threadsafe
@see libc/calls/sig2.c
sigactionInstalls handler for kernel interrupt, e.g.: void GotCtrlC(int sig, siginfo_t *si, ucontext_t *ctx); struct sigaction sa = {.sa_sigaction = GotCtrlC, .sa_flags = SA_RESETHAND|SA_RESTART|SA_SIGINFO}; CHECK_NE(-1, sigaction(SIGINT, &sa, NULL));The following flags are supported across platforms:
static volatile bool gotctrlc; void OnCtrlC(int sig) { gotctrlc = true; } int main() { size_t got; ssize_t rc; char buf[1]; struct sigaction oldint; struct sigaction saint = {.sa_handler = GotCtrlC}; if (sigaction(SIGINT, &saint, &oldint) == -1) { perror("sigaction"); exit(1); } for (;;) { rc = read(0, buf, sizeof(buf)); if (rc == -1) { if (errno == EINTR) { if (gotctrlc) { break; } } else { perror("read"); exit(2); } } if (!(got = rc)) { break; } for (;;) { rc = write(1, buf, got); if (rc != -1) { assert(rc == 1); break; } else if (errno != EINTR) { perror("write"); exit(3); } } } sigaction(SIGINT, &oldint, 0); }Please note that you can't do the above if you use SA_RESTART. Since the purpose of SA_RESTART is to restart i/o operations whose docs say that they're @restartable and read() is one such function. Here's some even better news: if you don't install any signal handlers at all, then your i/o calls will never be interrupted!
Here's an example of the most professional way to recover from
void ContinueOnCrash(void); void SkipOverFaultingInstruction(struct ucontext *ctx) { struct XedDecodedInst xedd; xed_decoded_inst_zero_set_mode(&xedd, XED_MACHINE_MODE_LONG_64); xed_instruction_length_decode(&xedd, (void *)ctx->uc_mcontext.rip, 15); ctx->uc_mcontext.rip += xedd.length; } void OnCrash(int sig, struct siginfo *si, struct ucontext *ctx) { SkipOverFaultingInstruction(ctx); ContinueOnCrash(); // reinstall here in case *rip faults } void ContinueOnCrash(void) { struct sigaction sa = {.sa_handler = OnSigSegv, .sa_flags = SA_SIGINFO | SA_RESETHAND}; sigaction(SIGSEGV, &sa, 0); sigaction(SIGFPE, &sa, 0); sigaction(SIGILL, &sa, 0); } int main() { ContinueOnCrash(); // ... }You may also edit any other CPU registers during the handler. For example, you can use the above technique so that division by zero becomes defined to a specific value of your choosing!
Please note that Xed isn't needed to recover from The important signals supported across all platforms are:
@param
@return
@see
xsigaction() for a much better api
@asyncsignalsafe
@vforksafe
sigaddsetAdds signal to set.
@param
@return
@raises
EINVAL if
1 ≤ sig ≤ NSIG isn't the case
@asyncsignalsafe
sigaltstackSets and/or gets alternate signal stack, e.g. struct sigaction sa; struct sigaltstack ss; ss.ss_flags = 0; ss.ss_size = GetStackSize(); ss.ss_sp = mmap(0, GetStackSize(), PROT_READ | PROT_WRITE, MAP_STACK | MAP_ANONYMOUS, -1, 0); sa.sa_flags = SA_ONSTACK; sa.sa_handler = OnStackOverflow; __cxa_atexit(free, ss[0].ss_sp, 0); sigemptyset(&sa.ss_mask); sigaltstack(&ss, 0); sigaction(SIGSEGV, &sa, 0);It's strongly recommended that you allocate a stack with the same size as GetStackSize() and that it have GetStackSize() alignment. Otherwise some of your runtime support code (e.g. ftrace stack use logging, kprintf() memory safety) won't be able to work as well.
@param
@return
sigdelsetRemoves signal from set.
@param
@return
@raises
EINVAL if
1 ≤ sig ≤ NSIG isn't the case
@asyncsignalsafe
sigemptysetRemoves all signals from set.
@param
@return
@asyncsignalsafe
sigfillsetAdds all signals to set.
@param
@return
@asyncsignalsafe
@vforksafe
siginterruptTunes whether signal can interrupt restartable system calls.
@param
@return
sigismemberReturns true if signal is member of set.
@param
@return
@raises
EINVAL if
1 ≤ sig ≤ NSIG isn't the case
@asyncsignalsafe
@vforksafe
signalInstalls kernel interrupt handler, e.g. void GotCtrlC(int sig) { ... } CHECK_NE(SIG_ERR, signal(SIGINT, GotCtrlC));
@param
@return
@note
this function has BSD semantics, i.e. SA_RESTART
@see
sigaction() which has more features and docs
@see libc/calls/signal.c
sigprocmaskChanges signal blocking state of calling thread, e.g.: sigset_t neu,old; sigfillset(&neu); sigprocmask(SIG_BLOCK, &neu, &old); sigprocmask(SIG_SETMASK, &old, NULL);
@param
@return
@asyncsignalsafe
@restartable
@vforksafe
sigqueueSends signal to process, with data. The impact of this action can be terminating the process, or interrupting it to request something happen.
@param
@return
@note
this isn't supported on OpenBSD
@asyncsignalsafe
sigsuspendBlocks until SIG ∉ MASK is delivered to process. This temporarily replaces the signal mask until a signal that it doesn't contain is delivered.
@param
@return
@asyncsignalsafe
@norestart
sinReturns sine of 𝑥.
@param
@return
@note
should take ~5ns
@see libc/tinymath/sin.c
sincosReturns sine and cosine of 𝑥.
@param
@return
@note
should take ~10ns
sincosfReturns sine and cosine of 𝑥.
@param
@return
@domain
-(3π/8) < 𝑥 < 3π/8 for best accuracy
sincoslReturns sine and cosine of 𝑥.
@param
@return
@domain
-(3π/8) < 𝑥 < 3π/8 for best accuracy
sinhReturns hyperbolic sine of 𝑥. sinh(x) = (exp(x) - 1/exp(x))/2 = (exp(x)-1 + (exp(x)-1)/exp(x))/2 = x + x^3/6 + o(x^5)
@param
@return
@see libc/tinymath/sinh.c
sinhfReturns hyperbolic sine of 𝑥. sinh(x) = (exp(x) - 1/exp(x))/2 = (exp(x)-1 + (exp(x)-1)/exp(x))/2 = x + x^3/6 + o(x^5)
@param
@return
sinhlReturns hyperbolic sine of 𝑥. sinh(x) = (exp(x) - 1/exp(x))/2 = (exp(x)-1 + (exp(x)-1)/exp(x))/2 = x + x^3/6 + o(x^5)
@param
@return
sinlReturns sine of 𝑥.
@param
@return
@domain
-(3π/8) < 𝑥 < 3π/8 for best accuracy
@see libc/tinymath/sinl.S
sizetolConverts size string to long. The following unit suffixes may be used
@param
@return
@see libc/fmt/sizetol.c
sleb128Encodes signed leb128 integer.
@param
@return
@see libc/fmt/sleb128.c
sleb64Encodes signed integer to array. uleb64 INT64_MAX l: 10𝑐 3𝑛𝑠 zleb64 INT64_MAX l: 13𝑐 4𝑛𝑠 sleb64 INT64_MAX l: 16𝑐 5𝑛𝑠 uleb128 INT64_MAX l: 18𝑐 6𝑛𝑠 zleb128 INT64_MAX l: 18𝑐 6𝑛𝑠 sleb128 INT64_MAX l: 24𝑐 8𝑛𝑠 zleb64 INT64_MIN l: 13𝑐 4𝑛𝑠 sleb64 INT64_MIN l: 16𝑐 5𝑛𝑠 zleb128 INT64_MIN l: 19𝑐 6𝑛𝑠 sleb128 INT64_MIN l: 24𝑐 8𝑛𝑠
@param
@return
@see libc/fmt/sleb64.c
sleepSleeps for particular number of seconds.
@param
@return
@see
nanosleep(), usleep()
@asyncsignalsafe
@norestart
@see libc/calls/sleep.c
_smt19937Initializes mt[NN] with small seed value.
@param
@return
@see
mt19937(), Smt19937()
@see libc/rand/mt19937.c
_Smt19937Initializes mt[NN] with array.
@param
@return
@see
mt19937(), smt19937()
@see libc/rand/mt19937.c
snprintfFormats string to buffer.
@param
@return
@see
__fmt() and printf() for detailed documentation
@asyncsignalsafe
@vforksafe
@see libc/fmt/snprintf.c
sockaddr2bsdConverts sockaddr (Linux/Windows) → sockaddr_bsd (XNU/BSD).
@param
@return
sockaddr2linuxConverts sockaddr_bsd (XNU/BSD) → sockaddr (Linux/Windows).
@param
@return
socketCreates new system resource for network communication, e.g. int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
@param
@return
@error
ENETDOWN, EPFNOSUPPORT, etc.
@see
libc/sysv/consts.sh
@asyncsignalsafe
@see libc/sock/socket.c
socketpairCreates bidirectional pipe, e.g. int sv[2]; socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
@param
@return
@error
EFAULT, EPFNOSUPPORT, etc.
@see
libc/sysv/consts.sh
@asyncsignalsafe
_spawnSpawns thread, e.g. int worker(void *arg, int tid) { const char *s = arg; printf("%s\n", s); return 0; } int main() { struct spawn th; _spawn(worker, "hi", &th); _join(&th); }
@param
@return
@see libc/thread/spawn.c
spliceTransfers data to/from pipe.
@param
@return
@see
copy_file_range() for file ↔ file
@see
sendfile() for seekable → socket
@see libc/calls/splice.c
sprintfFormats string to buffer that's hopefully large enough.
@param
@return
@see
__fmt() and printf() for detailed documentation
@see
snprintf() for same w/ buf size param
@asyncsignalsafe
@vforksafe
@see libc/fmt/sprintf.c
sqrtReturns square root of 𝑥.
@param
@return
@see libc/tinymath/sqrt.S
sqrtlReturns square root of 𝑥.
@param
@return
srandSeeds random number generator that's used by rand().
@param
@return
@see libc/rand/srand.c
sscanfString decoder.
@param
@return
@see
libc/fmt/vcscanf.h (for docs and implementation)
@see libc/fmt/sscanf.c
__start_fatalPrints initial part of fatal message.
@param
@return
@note
this is support code for __check_fail(), __assert_fail(), etc.
startswithReturns true if s has prefix.
@param
@return
startswith16Returns true if s has prefix.
@param
@return
statReturns information about thing.
@param
@return
@see
S_ISDIR(st.st_mode), S_ISREG(), etc.
@raise
EACCES if denied access to component in path prefix
@raise
EIO if i/o error occurred while reading from filesystem
@raise
ELOOP if a symbolic link loop exists in
path
@raise
ENAMETOOLONG if a component in
path exceeds NAME_MAX
@raise
ENOENT on empty string or if component in path doesn't exist
@raise
ENOTDIR if a parent component existed that wasn't a directory
@raise
EOVERFLOW shouldn't be possible on 64-bit systems
@raise
ELOOP may ahappen if
SYMLOOP_MAX symlinks were dereferenced
@raise
ENAMETOOLONG may happen if
path exceeded PATH_MAX
@asyncsignalsafe
@see libc/calls/stat.c
stpcpyCopies bytes from 𝑠 to 𝑑 until a NUL is encountered.
@param
@return
@note
𝑑 and 𝑠 can't overlap
@asyncsignalsafe
@see libc/intrin/stpcpy.c
stpncpyPrepares static search buffer.
@param
@return
@see
stncpy(), memccpy()
@asyncsignalsafe
@see libc/str/stpncpy.c
__straceSystem call logging enabled state. If Cosmopolitan was compiled with the By convention, functions wishing to disable syscall tracing for a short time period should say:
void foo() { --__strace; bar(); ++__strace; }This way you still have some flexibility to force syscall tracing, by setting __strace to a higher number like 2 or 200 . Even though
under normal circumstances, __strace should only be either zero or
one.
@type
__strace_initEnables plaintext system call logging if
@param
@return
strcasecmpCompares NUL-terminated strings ascii case-insensitively.
@param
@return
@asyncsignalsafe
strcasecmp16Compares NUL-terminated UCS-2 strings case-insensitively.
@param
@return
@asyncsignalsafe
strcasecmp8to16Compares UTF-8 and UTF-16 strings, ignoring case.
@param
@return
strcatAppends 𝑠 to 𝑑.
@param
@return
@asyncsignalsafe
@see libc/str/strcat.c
strcat16Appends 𝑠 to 𝑑.
@param
@return
@asyncsignalsafe
@see libc/str/strcat16.c
strchr16Returns pointer to first instance of character.
@param
@return
@note
this won't return NULL if search character is NUL
@asyncsignalsafe
strchrnul16Returns pointer to first instance of character.
@param
@return
@note
this won't return NULL if search character is NUL
strclenReturns number of characters in UTF-8 string.
@param
@return
@see libc/str/strclen.c
strclen16Returns number of characters in UTF-16 or UCS-2 string.
@param
@return
@see libc/str/strclen16.c
strcmpCompares NUL-terminated strings.
@param
@return
@asyncsignalsafe
@see libc/str/strcmp.c
strcmp16Compares NUL-terminated UCS-2 strings.
@param
@return
@asyncsignalsafe
@see libc/str/strcmp16.c
strcmp8to16Compares UTF-8 and UTF-16 strings.
@param
@return
strcollCompares strings in the C locale.
@param
@return
@see libc/str/strcoll.c
strcpyCopies bytes from 𝑠 to 𝑑 until a NUL is encountered.
@param
@return
@note
𝑑 and 𝑠 can't overlap
@asyncsignalsafe
@see libc/intrin/strcpy.c
strcpy16Copies NUL-terminated UCS-2 or UTF-16 string. DEST and SRC must not overlap unless DEST ≤ SRC.
@param
@return
@see libc/str/strcpy16.c
strcspnReturns prefix length, consisting of chars not in reject. a.k.a. Return index of first byte that's in charset.
@param
@return
@see
strspn(), strtok_r()
@asyncsignalsafe
@see libc/str/strcspn.c
strcspn16Returns prefix length, consisting of chars not in reject. a.k.a. Return index of first byte that's in charset.
@param
@return
@see
strspn(), strtok_r()
@asyncsignalsafe
@see libc/str/strcspn16.c
strdupAllocates new copy of string.
@param
@return
@error
ENOMEM
@threadsafe
@see libc/mem/strdup.c
strerdocConverts errno value to descriptive sentence.
@param
@return
strerrnoConverts errno value to symbolic name.
@param
@return
strerrorConverts errno value to string non-reentrantly.
@param
@return
@see
strerror_r()
@see libc/fmt/strerror.c
strerror_rConverts errno value to string.
@param
@return
strerror_wrConverts errno value to string with explicit windows errno too.
@param
@return
strftimeConverts time to string, e.g. char b[64]; int64_t sec; struct tm tm; time(&sec); localtime_r(&sec, &tm); strftime(b, sizeof(b), "%Y-%m-%dT%H:%M:%S%z", &tm); // ISO8601 strftime(b, sizeof(b), "%a, %d %b %Y %H:%M:%S %Z", &tm); // RFC1123
@param
@return
@see
FormatHttpDateTime()
@see libc/time/strftime.c
strftime_l
@param
@return
@see libc/time/strftime.c
stripextsRemoves file extensions.
@param
@return
@see libc/fmt/stripexts.c
strlcatAppends string SRC to DEST, the BSD way.
@param
@return
@note
dest and src can't overlap
@see
strncat()
@see libc/str/strlcat.c
strlcpyCopies string, the BSD way.
@param
@return
@note
d and s can't overlap
@note
we prefer memccpy()
@see libc/str/strlcpy.c
strlenReturns length of NUL-terminated string.
@param
@return
@asyncsignalsafe
@see libc/intrin/strlen.c
strlen16Returns length of NUL-terminated utf-16 string.
@param
@return
@asyncsignalsafe
@see libc/str/strlen16.c
strncasecmpCompares NUL-terminated strings case-insensitively w/ limit.
@param
@return
@asyncsignalsafe
strncasecmp16Compares NUL-terminated UCS-2 strings case-insensitively w/ limit.
@param
@return
@asyncsignalsafe
strncasecmp8to16Compares UTF-8 and UTF-16 strings, ignoring case, with limit.
@param
@return
strncatAppends at most 𝑛 bytes from 𝑠 to 𝑑.
@param
@return
@note
𝑑 and 𝑠 can't overlap
@asyncsignaslenafe
@see libc/str/strncat.c
strncat16Appends at most 𝑛 shorts from 𝑠 to 𝑑.
@param
@return
@note
𝑑 and 𝑠 can't overlap
@asyncsignaslenafe
@see libc/str/strncat16.c
strnclen16
@param
@return
@see libc/str/strclen16.c
strncmpCompares NUL-terminated strings w/ limit.
@param
@return
@asyncsignalsafe
@see libc/str/strncmp.c
strncmp16Compares NUL-terminated UCS-2 strings w/ limit.
@param
@return
@asyncsignalsafe
@see libc/str/strncmp16.c
strncmp8to16Compares UTF-8 and UTF-16 strings, with limit.
@param
@return
strncpyPrepares static search buffer.
Here's an example of the only use case we know of for strncpy:
static const struct People { char name[8]; int age; } kPeople[] = { {"alice", 29}, // {"bob", 42}, // }; int GetAge(const char *name) { char k[8]; int m, l, r; l = 0; r = ARRAYLEN(kPeople) - 1; strncpy(k, name, 8); while (l <= r) { m = (l + r) >> 1; if (READ64BE(kPeople[m].name) < READ64BE(k)) { l = m + 1; } else if (READ64BE(kPeople[m].name) > READ64BE(k)) { r = m - 1; } else { return kPeople[m].age; } } return -1; }
@param
@return
@see
stpncpy(), memccpy()
@asyncsignalsafe
@see libc/str/strncpy.c
strndupAllocates new copy of string, with byte limit.
@param
@return
@error
ENOMEM
@threadsafe
@see libc/mem/strndup.c
strnlenReturns length of NUL-terminated string w/ limit.
@param
@return
@asyncsignalsafe
@see libc/str/strnlen.c
strnlen16Returns length of NUL-terminated 16-bit string w/ limit.
@param
@return
@asyncsignalsafe
@see libc/str/strnlen16.c
strnlen16_sReturns length of char16_t string w/ security blankets. This is like strnlen() except it'll return 0 if (1) RDI is NULL or (2) a NUL-terminator wasn't found in the first RSI shorts.
@param
@return
strnlen_sReturns length of NUL-terminated string... securely. This is like strnlen() except it'll return 0 if
@param
@return
@asyncsignalsafe
@see libc/str/strnlen_s.c
strntoupperMutates string to ASCII uppercase w/ limit.
@param
@return
@praam
s is string
@praam
n is max bytes to consider
strnwidthReturns monospace display width of UTF-8 string.
@param
@return
strnwidth16Returns monospace display width of UTF-16 or UCS-2 string.
@param
@return
strpbrkReturns pointer to first byte matching any in accept, or NULL.
@param
@return
@asyncsignalsafe
@see libc/str/strpbrk.c
strpbrk16Returns pointer to first byte matching any in accept, or NULL.
@param
@return
@asyncsignalsafe
@see libc/str/strpbrk16.c
strrchrSearches for last instance of character in string.
@param
@return
@asyncsignalsafe
@see libc/str/strrchr.c
strrchr16Searches for last instance of char16_t in string.
@param
@return
@asyncsignalsafe
@see libc/str/strrchr16.c
strsak16Swiss Army Knife of string char16_t scanning. Sixteen fast functions in one.
@param
@return
strsepTokenizes string. This works by mutating the caller's pointer and the string itself. The returned value is the next available token, or NULL if we've reached the end. Upon each call, *str is updated to point past the terminator we inserted. Multiple delimiter bytes may be passed, which are treated as a set of characters, not a substring.
@param
@return
@note
unlike strtok() this does empty tokens and is re-entrant
@see libc/str/strsep.c
strsignalReturns string describing signal code. This returns SIGZERO for 0 which is the empty value. Textual names
should be available for signals 1 through 32. Signals in the range 33
and 128 are returned as a
This function is thread safe when
@param
@return
@see
sigaction()
@threadsafe
strspnReturns prefix length, consisting of chars in accept.
@param
@return
@see
strcspn(), strtok_r()
@asyncsignalsafe
@see libc/str/strspn.c
strspn16Returns prefix length, consisting of chars in accept.
@param
@return
@see
strcspn(), strtok_r()
@asyncsignalsafe
@see libc/str/strspn16.c
strstr16Searches for substring.
@param
@return
@asyncsignalsafe
@see
memmem()
@see libc/str/strstr16.c
strtoi128Decodes 128-bit signed integer from ASCII string.
@param
@return
@see
strtou128()
@see libc/fmt/strtoi128.c
strtoimaxDecodes intmax_t from ASCII string.
@param
@return
@see
strtoumax()
@see libc/fmt/strtoimax.c
strtokExtracts non-empty tokens from string.
@param
@return
@see
strtok_r() and strsep() for superior functions
@notasyncsignalsafe
@see libc/str/strtok.c
strtok_rExtracts non-empty tokens from string.
@param
@return
@see
strsep() which is similar
@asyncsignalsafe
@see libc/str/strtok_r.c
strtolDecodes signed 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𝑛𝑠
@param
@return
@see libc/fmt/strtol.c
strtold_lConverts string to long double.
@param
@return
strtollDecodes signed integer from ASCII string.
@param
@return
@see libc/fmt/strtoll.c
strtoll_l
@param
@return
@see libc/fmt/strtoll_l.c
strtonumConverts string to integer, the BSD way.
@param
@return
@see libc/fmt/strtonum.c
strtou128Decodes 128-bit unsigned integer from ASCII string.
@param
@return
@see
strtoi128()
@see libc/fmt/strtou128.c
strtoulDecodes unsigned integer from ASCII string.
@param
@return
@see libc/fmt/strtoul.c
strtoullDecodes unsigned integer from ASCII string.
@param
@return
@see libc/fmt/strtoull.c
strtoull_l
@param
@return
strtoumaxDecodes uintmax_t from ASCII string.
@param
@return
@see
strtoimax()
@see libc/fmt/strtoumax.c
strwidthReturns monospace display width of UTF-8 string.
@param
@return
strwidth16Returns monospace display width of UTF-16 or UCS-2 string.
@param
@return
strxfrmTransforms strings into current C locale. calling strcmp() on two strxfrm()-ed strings is same as calling strcoll() on the originals.
@param
@return
@note
dest and src can't overlap
@note
dest array size should be greater than count
@note
if dest is NULL, count has to be zero
@see libc/str/strxfrm.c
strxfrm_l
@param
@return
__subvdi3Returns 𝑥-𝑦, aborting on overflow.
@param
@return
@see
-ftrapv
__subvsi3Returns 𝑥-𝑦, aborting on overflow.
@param
@return
@see
-ftrapv
__subvti3Returns 𝑥-𝑦, aborting on overflow.
@param
@return
@see
-ftrapv
svignaSeeds vigna() pseudorandom number generator.
@param
@return
@see
vigna(), vigna_r()
@see libc/rand/vigna.c
symlinkCreates symbolic link. This is like link() but adds a tiny indirection to make the fact that the file is a link obvious. It also enables certain other features, like the ability to be broken.
@param
@return
@note
Windows NT only lets admins do this
@asyncsignalsafe
@see libc/calls/symlink.c
symlinkatCreates symbolic link. This is like link() but adds a tiny indirection to make the fact that the file is a link obvious. It also enables certain other features, like the ability to be broken.
@param
@return
@raise
EPERM if a non-admin on Windows NT tries to use this
@asyncsignalsafe
syncFlushes file system changes to disk by any means necessary.
@return
@see
__nosync to secretly disable
@see libc/calls/sync.c
sync_file_rangeFlushes subset of file to disk.
@param
@return
@note
Linux documentation says this call is "dangerous"; for highest
assurance of data recovery after crash, consider fsync() on both
file and directory
@see
fsync(), fdatasync(), PAGESIZE
sys_bind_nt
@param
@return
@see libc/sock/bind-nt.c
sys_clone_linuxInvokes clone() system call on GNU/Systemd.
@param
@return
sys_closesocket_ntCloses socket on Windows. This function should only be called by close().
@param
@return
sys_dup_ntImplements dup(), dup2(), dup3(), and F_DUPFD for Windows.
@param
@return
@see libc/calls/dup-nt.c
sys_fstatSupports fstat(), etc. implementations.
@param
@return
@asyncsignalsafe
sys_fstatatSupports stat(), lstat(), fstatat(), etc. implementations.
@param
@return
@asyncsignalsafe
sys_getrusageReturns resource usage statistics.
@param
@return
sys_getsockopt_nt
@param
@return
sys_gettimeofday_metal
@param
@return
sys_mmapObtains memory mapping directly from system. The mmap() function needs to track memory mappings in order to support Windows NT and Address Sanitizer. That memory tracking can be bypassed by calling this function. However the caller is responsible for passing the magic memory handle on Windows NT to CloseHandle().
@param
@return
@asyncsignalsafe
@threadsafe
sys_mmap_metal
@param
@return
sys_mmap_nt
@param
@return
sys_munmapUnmaps memory directly with system. This function bypasses memtrack. Therefore it won't work on Windows, but it works on everything else including bare metal.
@param
@return
@asyncsignalsafe
@threadsafe
sys_open_nt
@param
@return
@see libc/calls/open-nt.c
sys_poll_ntPolls on the New Technology. This function is used to implement poll() and select(). You may poll on both sockets and files at the same time. We also poll for signals while poll is polling.
@param
@return
@see libc/calls/poll-nt.c
sys_read_nt
@param
@return
@see libc/calls/read-nt.c
sys_recv_ntPerforms stream socket receive on New Technology.
@param
@return
@see libc/sock/recv-nt.c
sys_recvfrom_ntPerforms datagram receive on New Technology.
@param
@return
sys_renameat_nt
@param
@return
sys_send_ntPerforms stream socket send on the New Technology.
@param
@return
@see libc/sock/send-nt.c
sys_sendto_ntPerforms datagram socket send on the New Technology.
@param
@return
sys_setitimer_nt
@param
@return
sys_setsockopt_nt
@param
@return
sys_sync_ntFlushes all open file handles and, if possible, all disk drives.
@return
@see libc/calls/sync-nt.c
sys_unveil_linux
@param
@return
@see libc/calls/unveil.c
sys_wait4_nt
@param
@return
sys_xinet_ntopFormats internet address to string, or dies.
@param
@return
syscallPerforms raw System Five system call. This function provides a direct path into system call support that's friendly to C code, since it doesn't need an intermediate thunk. It only supports arities up to six, since there's no way to do more safely; this isn't a problem with Linux, although certain BSD calls may not be available.
@param
@return
@see libc/sysv/syscall.S
__syscall__Invokes SYSCALL for libfatal forceinline asm() routines.
@param
@return
@clob
rax,rdx,memory,cc
syscon_startSections for varint encoded magic numbers. These sections are all ordered by (group_name, constant_name). They're populated by modules simply referencing the symbols.
@return
@see
libc/sysv/consts.sh
@see
libc/sysv/consts/syscon_h
sysconfReturns configuration value about system. The following parameters are supported:
@param
@return
sysinfoReturns amount of system ram, cores, etc.
@param
@return
@error
ENOSYS, EFAULT
@see libc/calls/sysinfo.c
syslogGenerates a log message which will be distributed by syslogd Note: no errors are reported if an error occurred while logging the message.
@param
@return
@asyncsignalsafe
@see libc/sock/syslog.c
systemLaunches program with system command interpreter.
@param
@return
@see libc/stdio/system.c
systemexecExecutes system command replacing current process.
@param
@return
@vforksafe
__systemfivePerforms System Five System Call. Cosmopolitan is designed to delegate all function calls into the Linux, FreeBSD, OpenBSD, and XNU kernels via this function, with few exceptions. This function should generally only be called by generated thunks in the libc/sysv/syscalls/ directory. It's safe to call this function on Windows, where it will always return -1 with errno == ENOSYS. Further note that -1 is the only return value that means error, a common anti-pattern is to check for values less than 0 (which is more problematic on 32-bit). It is important to consider that system calls are one order of a magnitude more expensive than normal function calls. For example getpid() on Linux usually takes 500ns, and cached i/o calls will take 1µs or more. So we don't need to inline them like Chromium. Another thing to consider is that BSDs only loosely follow the System Five ABI for the SYSCALL instruction. For example Linux always follows the six argument limit but the FreeBSD sendfile system call accepts a seventh argument that is passed on stack and OpenBSD modifies functions like mmap so that the sixth arg is passed on the stack. There's also the carry flag convention that XNU, FreeBSD, and OpenBSD inherited from 386BSD aka Jolix
@param
@return
@clob
%rcx,%r10,%r11
@see
syscalls.sh
tanfReturns tangent of 𝑥.
@param
@return
@domain
-(3π/8) < 𝑥 < 3π/8 for best accuracy
@see libc/tinymath/tanf.S
tanhReturns hyperbolic tangent of 𝑥. tanh(x) = (exp(x) - exp(-x))/(exp(x) + exp(-x)) = (exp(2*x) - 1)/(exp(2*x) - 1 + 2) = (1 - exp(-2*x))/(exp(-2*x) - 1 + 2)
@param
@return
@see libc/tinymath/tanh.c
tanhfReturns hyperbolic tangent of 𝑥. tanh(x) = (exp(x) - exp(-x))/(exp(x) + exp(-x)) = (exp(2*x) - 1)/(exp(2*x) - 1 + 2) = (1 - exp(-2*x))/(exp(-2*x) - 1 + 2)
@param
@return
tanhlReturns hyperbolic tangent of 𝑥. tanh(x) = (exp(x) - exp(-x))/(exp(x) + exp(-x)) = (exp(2*x) - 1)/(exp(2*x) - 1 + 2) = (1 - exp(-2*x))/(exp(-2*x) - 1 + 2)
@param
@return
tanlReturns tangent of 𝑥.
@param
@return
@see libc/tinymath/tanl.S
tarjanDetermines order of things in network and finds tangled clusters too.
@param
@return
@error
ENOMEM
@note
Tarjan's Algorithm is O(|V|+|E|)
@see libc/alg/tarjan.c
tcflowChanges flow of teletypewriter data.
@param
@return
@see libc/calls/tcflow.c
tcflushFlushes teletypewriter data.
@param
@return
@see libc/calls/tcflush.c
tcgetattrObtains the termios struct. Here are the general defaults you can expect across platforms:
c_iflag = ICRNL IXON c_oflag = OPOST ONLCR NL0 CR0 TAB0 BS0 VT0 FF0 c_cflag = ISIG CREAD CS8 c_lflag = ISIG ICANON ECHO ECHOE ECHOK IEXTEN ECHOCTL ECHOKE c_ispeed = 38400 c_ospeed = 38400 c_cc[VINTR] = CTRL-C c_cc[VQUIT] = CTRL-\ # ignore this comment c_cc[VERASE] = CTRL-? c_cc[VKILL] = CTRL-U c_cc[VEOF] = CTRL-D c_cc[VTIME] = CTRL-@ c_cc[VMIN] = CTRL-A c_cc[VSTART] = CTRL-Q c_cc[VSTOP] = CTRL-S c_cc[VSUSP] = CTRL-Z c_cc[VEOL] = CTRL-@ c_cc[VSWTC] = CTRL-@ c_cc[VREPRINT] = CTRL-R c_cc[VDISCARD] = CTRL-O c_cc[VWERASE] = CTRL-W c_cc[VLNEXT] = CTRL-V c_cc[VEOL2] = CTRL-@
@param
@return
@asyncsignalsafe
tcsetattrSets struct on teletypewriter w/ drains and flushes.
@param
@return
@asyncsignalsafe
tcsetpgrpPuts process group in control of terminal.
@param
@return
@asyncsignalsafe
TearDownUser-defined test cleanup function. The test runner will call this function after each TEST() if it's defined by the linkage.
@return
TerminateProcessTerminates the specified process and all of its threads.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
testlib_enable_tmp_setup_teardownEnables setup and teardown of test directories. If the linker says this symbol exists then, regardless of its value, a unique test directory will be created at the start of each test, the test will be run with that directory as its working directory, and if the test succeeds it'll be removed along with any contents.
@type
__text_windows_startSpecial area for Windows NT support code. Isolating this code adds value for Windows users by minimizing page faults through improved locality. On System Five the PIRO runtime can unmap these pages.
@return
@see
libc/runtime/piro.c
@see
ape/ape.lds
@see libc/runtime/init.S
__tfork_threadCreates thread on OpenBSD.
@param
@return
tgkillKills thread group.
@param
@return
@raises
ENOSYS on non-Linux
@see
tkill()
@see libc/calls/tgkill.c
timeReturns time as seconds from UNIX epoch.
@param
@return
@asyncsignalsafe
@see libc/calls/time.c
timesReturns accounting data for process on time-sharing system.
@param
@return
@see libc/time/times.c
_timespec2timevalConverts This divides ts.tv_nsec by 1000 with upward rounding and overflow
handling. Your ts.tv_nsec must be on the interval
@param
@return
_timespec_gtReturns true if timespec
@param
@return
timingsafe_memcmpLexicographically compares the first 𝑛 bytes in 𝑝 and 𝑞. The following expression:
timingsafe_memcmp(p, q, n)Is functionally equivalent to:
MAX(-1, MIN(1, memcmp(p, q, n)))Running time is independent of the byte sequences compared, making this safe to use for comparing secret values such as cryptographic MACs. In contrast, memcmp() may short-circuit after finding the first differing byte.
timingsafe_memcmp n=0 661 picoseconds timingsafe_memcmp n=1 1 ns/byte 590 mb/s timingsafe_memcmp n=2 1 ns/byte 738 mb/s timingsafe_memcmp n=3 1 ns/byte 805 mb/s timingsafe_memcmp n=4 1 ns/byte 843 mb/s timingsafe_memcmp n=5 1 ns/byte 922 mb/s timingsafe_memcmp n=6 1 ns/byte 932 mb/s timingsafe_memcmp n=7 1 ns/byte 939 mb/s timingsafe_memcmp n=8 992 ps/byte 984 mb/s timingsafe_memcmp n=9 992 ps/byte 984 mb/s timingsafe_memcmp n=15 926 ps/byte 1,054 mb/s timingsafe_memcmp n=16 950 ps/byte 1,026 mb/s timingsafe_memcmp n=17 933 ps/byte 1,045 mb/s timingsafe_memcmp n=31 896 ps/byte 1,089 mb/s timingsafe_memcmp n=32 888 ps/byte 1,098 mb/s timingsafe_memcmp n=33 972 ps/byte 1,004 mb/s timingsafe_memcmp n=80 913 ps/byte 1,068 mb/s timingsafe_memcmp n=128 891 ps/byte 1,095 mb/s timingsafe_memcmp n=256 873 ps/byte 1,118 mb/s timingsafe_memcmp n=16384 858 ps/byte 1,138 mb/s timingsafe_memcmp n=32768 856 ps/byte 1,140 mb/s timingsafe_memcmp n=131072 857 ps/byte 1,138 mb/s bcmp ne n=256 3 ps/byte 246 gb/s bcmp eq n=256 32 ps/byte 30,233 mb/s memcmp ne n=256 3 ps/byte 246 gb/s memcmp eq n=256 31 ps/byte 31,493 mb/s timingsafe_bcmp ne n=256 27 ps/byte 35,992 mb/s timingsafe_bcmp eq n=256 27 ps/byte 35,992 mb/s timingsafe_memcmp ne n=256 877 ps/byte 1,113 mb/s timingsafe_memcmp eq n=256 883 ps/byte 1,105 mb/s
@param
@return
@note
each byte is interpreted as unsigned char
@see
timingsafe_bcmp() it's 100x faster
@asyncsignalsafe
tinydivsiSupport code for fast integer division by Si units. Division by magnums is described in Hacker's Delight and is usually generated automatically by compilers, but sadly not when we optimize for size and idiv goes at least 10x slower so we do this which saves space while avoiding build tuning
@param
@return
tinywcslen32-bit strlen that's tiny and near optimal if data's tiny.
@param
@return
@see
libc/nexgen32e/strsak32.S
tinywcsnlen32-bit strnlen that's tiny and near optimal if data's tiny.
@param
@return
@see
libc/nexgen32e/strsak32.S
tkillKills thread.
@param
@return
@see libc/calls/tkill.c
tmpfileCreates a temporary file.
@return
@see
mkostempsm(), kTmpPath
@see libc/stdio/tmpfile.c
touchCreates new file or changes modified time on existing one.
@param
@return
@see
creat()
@see libc/calls/touch.c
towlowerConverts wide character to lower case.
@param
@return
@see libc/str/towlower.c
towupperConverts wide character to upper case.
@param
@return
@see libc/str/towupper.c
tpdecodeThompson-Pike Varint Decoder.
@param
@return
@note
synchronization is performed
@see
libc/str/tpdecodecb.internal.h (for implementation)
@deprecated
tpencEncodes Thompson-Pike varint.
@param
@return
@note
invented on a napkin in a new jersey diner
@see libc/intrin/tpenc.S
tpencodeThompson-Pike Varint Encoder. Implementation Details: The header macro should ensure this function is only called for non-ASCII, or DCE'd entirely. In addition to that this function makes a promise to not clobber any registers but %rax.
@param
@return
@note
this encoding was designed on a napkin in a new jersey diner
@deprecated
tprecode16to8Transcodes UTF-16 to UTF-8. This is a low-level function intended for the core runtime. Use utf16toutf8() for a much better API that uses malloc().
@param
@return
tprecode8to16Transcodes UTF-8 to UTF-16. This is a low-level function intended for the core runtime. Use utf8toutf16() for a much better API that uses malloc().
@param
@return
TrackMemoryInterval
@param
@return
truncateReduces or extends underlying physical medium of file. If file was originally larger, content >length is lost.
@param
@return
@see
ftruncate()
@error
ENOENT
truncfRounds to integer, toward zero.
@param
@return
@define
trunc(𝑥+copysign(.5,𝑥))
@see
round(),rint(),nearbyint()
@see
roundss $_MM_FROUND_TO_ZERO|_MM_FROUND_NO_EXC,%xmm0,%xmm0
trunclRounds to integer, toward zero.
@param
@return
ttyname_rReturns name of terminal, reentrantly.
@param
@return
__udivmodti4Performs 128-bit unsigned division and remainder.
@param
@return
uint128toarray_radix10Converts unsigned 128-bit integer to string.
@param
@return
uint64toarray_radix8Converts unsigned 64-bit integer to octal string.
@param
@return
uleb128Encodes unsigned leb128 integer.
@param
@return
@see libc/fmt/uleb128.c
uleb64Encodes unsigned integer to array. uleb64 INT64_MAX l: 10𝑐 3𝑛𝑠 zleb64 INT64_MAX l: 13𝑐 4𝑛𝑠 sleb64 INT64_MAX l: 16𝑐 5𝑛𝑠 uleb128 INT64_MAX l: 18𝑐 6𝑛𝑠 zleb128 INT64_MAX l: 18𝑐 6𝑛𝑠 sleb128 INT64_MAX l: 24𝑐 8𝑛𝑠 zleb64 INT64_MIN l: 13𝑐 4𝑛𝑠 sleb64 INT64_MIN l: 16𝑐 5𝑛𝑠 zleb128 INT64_MIN l: 19𝑐 6𝑛𝑠 sleb128 INT64_MIN l: 24𝑐 8𝑛𝑠
@param
@return
@see libc/fmt/uleb64.c
umaskSets file mode creation mask.
@param
@return
@note
always succeeds
@see libc/calls/umask.c
unameAsks kernel to give us the
@param
@return
@see libc/calls/uname.c
unbingTurns CP437 unicode glyph into its binary representation.
@param
@return
@see
bing()
@see libc/fmt/unbing.c
unbingbufDecodes human-readable CP437 glyphs into binary, e.g. char binged[5]; char golden[5] = "\0\1\2\3\4"; unbingbuf(binged, sizeof(binged), u" ☺☻♥♦", -1); CHECK_EQ(0, memcmp(binged, golden, 5));
@param
@return
@note
no NUL terminator is added to end of buf
@see
tunbing(), unbingstr(), unbing()
@see libc/x/unbingbuf.c
unbingstrDecodes human-readable CP437 glyphs into binary, e.g. CHECK_EQ(0, memcmp(gc(unbingstr(u" ☺☻♥♦")), "\0\1\2\3\4", 5));
@param
@return
@note
no NUL terminator is added to end of buf
@see
tunbing(), unbingbuf(), unbing()
@see libc/x/unbingstr.c
UnchunkRemoves chunk transfer encoding from message body in place.
@param
@return
@see net/http/unchunk.c
uncompressDecompresses the 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 large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the uncompressed data.
@return
uncompress2Same as uncompress, except that sourceLen is a pointer, where the length of the source is *sourceLen. On return, *sourceLen is the number of source bytes consumed.
@return
undeflateDecompresses raw DEFLATE data. This is 10x smaller and 10x slower than chromium zlib.
@param
@return
@note
h/t Phil Katz, David Huffman, Claude Shannon
@see libc/str/undeflate.c
UnderlongCanonicalizes overlong Thompson-Pike encodings. Please note that the IETF banned these numbers, so if you want to enforce their ban you can simply strcmp() the result to check for the existence of banned numbers.
@param
@return
@see net/http/underlong.c
ungetcPushes byte back to stream.
@param
@return
@threadsafe
@see libc/stdio/ungetc.c
ungetwcPushes wide character back to stream.
@param
@return
@threadsafe
@see libc/stdio/ungetwc.c
ungetwc_unlockedPushes wide character back to stream.
@param
@return
ungrayDecodes gray code.
@param
@return
@see
https://en.wikipedia.org/wiki/Gray_code
@see
gray()
@see libc/bits/ungray.c
unhexbuf
@param
@return
@see libc/fmt/unhexbuf.c
unhilbertDecodes Hilbert space-filling curve.
@param
@return
@see
https://en.wikipedia.org/wiki/Hilbert_curve
@see
hilbert()
@see libc/bits/hilbert.c
unlinkRemoves file. This may be used to delete files but it can't be used to delete directories. The exception are symlinks, which this will delete however not the linked directory.
@param
@return
@asyncsignalsafe
@see libc/calls/unlink.c
unlink_sDeletes file. The caller's variable is made NULL. Note that we define unlink(NULL) as a no-op.
@param
@return
@asyncsignalsafe
unlinkatDeletes inode and maybe the file too. This may be used to delete files and directories and symlinks.
@param
@return
UnmapViewOfFileUnmaps memory created by MapViewOfFileEx().
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
unmortonDeinterleaves bits.
@param
@return
@see
en.wikipedia.org/wiki/Z-order_curve
@see
morton()
@see libc/bits/unmorton.c
unmountUnmounts file system. The following flags may be specified:
@param
@return
@see libc/calls/unmount.c
unsleb128Decodes a GNU-style varint from a buffer. The GNU Assembler is able to encode numbers this way, since it's used by the DWARF debug format.
@param
@return
@see libc/fmt/unsleb128.c
unuleb64Decodes unsigned integer from array.
@param
@return
@see libc/fmt/unuleb64.c
unveilRestricts filesystem operations, e.g. unveil(".", "r"); // current directory + children are visible unveil("/etc", "r"); // make /etc readable too unveil(0, 0); // commit and lock policyUnveiling restricts a view of the filesystem to a set of allowed paths with specific privileges.
Once you start using unveil(), the entire file system is considered
hidden. You then specify, by repeatedly calling unveil(), which paths
should become unhidden. When you're finished, you call There are some differences between unveil() on Linux versus OpenBSD.
@param
@return
@raise
ENOSYS if host os isn't Linux or OpenBSD
@raise
ENOSYS if Landlock isn't supported on this kernel
@raise
EINVAL if one argument is set and the other is not
@raise
EINVAL if an invalid character in
permissions was found
@raise
EPERM if unveil() is called after locking
@note
on Linux this function requires Linux Kernel 5.13+
@see
[1] https://docs.kernel.org/userspace-api/landlock.html
@threadsafe
@see libc/calls/unveil.c
unzleb64Decodes array to signed integer w/ zig-zag encoding.
@param
@return
@see
zleb64()
@see libc/fmt/unzleb64.c
usleepSleeps for particular number of microseconds.
@param
@return
@raise
EINTR if a signal was delivered while sleeping
@see
nanosleep(), sleep()
@norestart
@see libc/calls/usleep.c
utf16to32Transcodes UTF-16 to UTF-32.
@param
@return
@see libc/x/utf16to32.c
utf16toutf8Transcodes UTF-16 to UTF-8.
@param
@return
@see libc/x/utf16toutf8.c
utf8toutf32Transcodes UTF-8 to UTF-32.
@param
@return
@see libc/x/utf8toutf32.c
utimeChanges last accessed/modified times on file.
@param
@return
@asyncsignalsafe
@see libc/calls/utime.c
utimensatSets atime/mtime on file, the modern way. This is two functions in one. If
XNU and RHEL5 only have microsecond accuracy and there's no
@param
@return
@raise
ENOSYS on RHEL5 if path is NULL
@raise
EINVAL if flags had unrecognized bits
@raise
EINVAL if path is NULL and flags has AT_SYMLINK_NOFOLLOW
@raise
EBADF if dirfd isn't a valid fd or AT_FDCWD
@raise
EFAULT if path or ts memory was invalid
@raise
EROFS if file system is read-only
@raise
ENAMETOOLONG
@raise
EPERM
@see
futimens()
@asyncsignalsafe
utimesChanges last accessed/modified times on file.
@param
@return
@asyncsignalsafe
@see
stat()
@see libc/calls/utimes.c
vallocEquivalent to memalign(PAGESIZE, n).
@param
@return
@see
pvalloc()
@threadsafe
@see libc/mem/valloc.c
vappendfAppends formatted string to buffer.
@param
@return
vasprintfFormats string w/ dynamic memory allocation.
@param
@return
@see
xasprintf() for a better API
@threadsafe
@see libc/mem/vasprintf.c
vcscanfString / file / stream decoder. This scanf implementation is able to tokenize strings containing 8-bit through 128-bit integers (with validation), floating point numbers, etc. It can also be used to convert UTF-8 to UTF-16/32.
@param
@return
@see
libc/fmt/pflink.h (dynamic memory is not a requirement)
@see libc/fmt/vcscanf.c
vdprintfFormats string directly to system i/o device.
@param
@return
@asyncsignalsafe
@vforksafe
__vdsosymReturns address of vDSO function.
@param
@return
verr
@param
@noreturn
@see libc/log/verr.c
verrx
@param
@noreturn
@see libc/log/verrx.c
vflogfWrites formatted message w/ timestamp to log. Timestamps are hyphenated out when multiple events happen within the same second in the same process. When timestamps are crossed out, it will display microseconsd as a delta elapsed time. This is useful if you do something like:
INFOF("connecting to foo"); connect(...) INFOF("connected to foo");In that case, the second log entry will always display the amount of time that it took to connect. This is great in forking applications.
@param
@return
@asyncsignalsafe
@threadsafe
@see libc/log/vflogf.c
vforkForks process without copying page tables. This is the same as fork() except it's optimized for the case where the caller invokes execve() immediately afterwards. You can also call functions like close(), dup2(), etc. You cannot call read() safely but you can call pread(). Call _exit() but don't call exit(). Look for the vforksafe function annotation Do not make the assumption that the parent is suspended until the child terminates since this impl calls fork() on Windows.
@return
@returnstwice
@vforksafe
@see libc/runtime/vfork.S
vfprintfFormats and writes text to stream.
@param
@return
@see
printf() for further documentation
vfprintf_unlockedFormats and writes text to stream.
@param
@return
@see
printf() for further documentation
vfscanfStream decoder.
@param
@return
@see
libc/fmt/vcscanf.h
@see libc/stdio/vfscanf.c
vignaReturns deterministic pseudorandom data, e.g. uint64_t x = vigna();You can generate different types of numbers as follows:
int64_t x = vigna() >> 1; // make positive signed integer double x = _real1(vigna()); // make float on [0,1]-intervalYou can seed this random number generator using:
svigna(rdseed());You may use the reentrant version of this function:
static uint64_t s = 0; uint64_t x = svigna_r(&s);If you want to fill a buffer with data then rngset() implements vigna's algorithm to do that extremely well:
char buf[4096]; rngset(buf, sizeof(buf), vigna, 0);If you want a fast pseudorandom number generator that seeds itself automatically on startup and fork() then consider rand64(). If you want true random data then consider rdseed, rdrand, and getrandom.
@return
@note
this function is not intended for cryptography
@note
this function passes bigcrush and practrand
@note
this function takes at minimum 4 cycles
@see libc/rand/vigna.c
vigna_rReturns pseudorandom data.
@param
@return
@see
vigna() for easy api
@see libc/rand/vigna.c
VirtualProtectProtects memory on the New Technology.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
VisualizeControlCodesMakes control codes and trojan source plainly viewable. This is useful for logging data like HTTP messages, where we don't want full blown C string literal escaping, but we don't want things like raw ANSI control codes from untrusted devices in our terminals. This function also canonicalizes overlong encodings. Therefore it isn't necessary to say VisualizeControlCodes(Underlong(𝑥))) since VisualizeControlCodes(𝑥) will do the same thing.
@param
@return
vmspliceTransfers memory to pipe.
@param
@return
vprintfFormats and writes text to stdout.
@param
@return
@see
printf() for further documentation
@see libc/stdio/vprintf.c
vscanfString decoder.
@param
@return
@see
libc/fmt/vcscanf.h
@see libc/stdio/vscanf.c
vsnprintfFormats string to buffer w/ preexisting vararg state.
@param
@return
@see
__fmt() and printf() for detailed documentation
@asyncsignalsafe
@vforksafe
@see libc/fmt/vsnprintf.c
vsprintfFormats string to buffer hopefully large enough w/ vararg state.
@param
@return
@see
__fmt() and printf() for detailed documentation
@see
vsnprintf() for modern alternative w/ buf size param
@see libc/fmt/vsprintf.c
vsscanfDecodes string.
@param
@return
@see
libc/fmt/vcscanf.h (for docs and implementation)
@note
to offer the best performance, we assume small codebases
needing vsscanf() won't need sscanf() too; and as such, there's
a small code size penalty to using both
@see libc/fmt/vsscanf.c
vsyslogGenerates a log message which will be distributed by syslogd Note: no errors are reported if an error occurred while logging the message.
@param
@return
@asyncsignalsafe
@see libc/sock/syslog.c
waitWaits for status to change on any child process.
@param
@return
@asyncsignalsafe
@restartable
@vforksafe
@see libc/calls/wait.c
_wait0Blocks until memory location becomes zero. This is intended to be used on the child thread id, which is updated by the _spawn() system call when a thread terminates. The purpose of this operation is to know when it's safe to munmap() a threads stack
@param
@return
@see libc/intrin/wait0.c
wait3Waits for status to change on any child process.
@param
@return
@asyncsignalsafe
@restartable
@see libc/calls/wait3.c
wait4Waits for status to change on process.
@param
@return
@asyncsignalsafe
@restartable
@see libc/calls/wait4.c
WaitForMultipleObjectsWaits for handles to change status.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
WaitForSingleObjectWaits for handle to change status.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
waitpidWaits for status to change on process.
@param
@return
@asyncsignalsafe
@restartable
@see libc/calls/waitpid.c
_wchompMutates line to remove line-ending characters.
@param
@return
@see
getline
@see libc/str/wchomp.c
wcscasecmpCompares NUL-terminated wide strings case-insensitively.
@param
@return
@asyncsignalsafe
wcscatAppends 𝑠 to 𝑑.
@param
@return
@asyncsignalsafe
@see libc/str/wcscat.c
wcschrReturns pointer to first instance of character.
@param
@return
@note
this won't return NULL if search character is NUL
@asyncsignalsafe
wcschrnulReturns pointer to first instance of character.
@param
@return
@note
this won't return NULL if search character is NUL
wcscmpCompares NUL-terminated wide strings.
@param
@return
@asyncsignalsafe
@see libc/str/wcscmp.c
wcscpyCopies NUL-terminated wide character string. 𝑑 and 𝑠 must not overlap unless 𝑑 ≤ 𝑠.
@param
@return
@asyncsignalsafe
@see libc/str/wcscpy.c
wcscspnReturns prefix length, consisting of chars not in reject. a.k.a. Return index of first byte that's in charset.
@param
@return
@see
strspn(), strtok_r()
@asyncsignalsafe
@see libc/str/wcscspn.c
wcsdupAllocates copy of wide string.
@param
@return
@threadsafe
@see libc/mem/wcsdup.c
wcsendswithReturns true if s has suffix.
@param
@return
wcslenReturns length of NUL-terminated wchar_t string.
@param
@return
@asyncsignalsafe
wcsncasecmpCompares NUL-terminated wide strings case-insensitively w/ limit.
@param
@return
@asyncsignalsafe
wcsncatAppends at most 𝑛 wides from 𝑠 to 𝑑.
@param
@return
@note
𝑑 and 𝑠 can't overlap
@asyncsignaslenafe
@see libc/str/wcsncat.c
wcsncmpCompares NUL-terminated wide strings w/ limit.
@param
@return
@asyncsignalsafe
@see libc/str/wcsncmp.c
wcsnlenReturns length of NUL-terminated memory, with limit.
@param
@return
@asyncsignalsafe
wcsnlen_sReturns length of wchar_t string w/ security blankets. This is like wcsnlen() except it'll return 0 if (1) RDI is NULL or (2) a NUL-terminator wasn't found in the first RSI chars.
@param
@return
wcsnrtombs
@param
@return
wcsnwidthReturns monospace display width of wide character string.
@param
@return
wcspbrkReturns pointer to first byte matching any in accept, or NULL.
@param
@return
@asyncsignalsafe
@see libc/str/wcspbrk.c
wcsrchrSearches for last instance of wchar_t in string.
@param
@return
@asyncsignalsafe
@see libc/str/wcsrchr.c
wcsrtombs
@param
@return
@see libc/str/wcsrtombs.c
wcssakSwiss army knife of wchar_t string scanning. Seven fast functions in one.
@param
@return
wcsspnReturns prefix length, consisting of chars in accept.
@param
@return
@see
strcspn(), strtok_r()
@asyncsignalsafe
@see libc/str/wcsspn.c
wcsstartswithReturns true if s has prefix.
@param
@return
wcsstrSearches for substring.
@param
@return
@asyncsignalsafe
@see
memmem()
@see libc/str/wcslen.c
wcstoi128Decodes 128-bit signed integer from wide string.
@param
@return
@see
strtou128()
@see libc/fmt/wcstoi128.c
wcstoimaxDecodes intmax_t from wide string.
@param
@return
@see
strtoumax()
@see libc/fmt/wcstoimax.c
wcstokExtracts non-empty tokens from string.
@param
@return
@see libc/str/wcstok.c
wcstolDecodes signed long integer from wide string.
@param
@return
@see libc/fmt/wcstol.c
wcstollDecodes signed long long integer from wide string.
@param
@return
@see libc/fmt/wcstoll.c
wcstoll_l
@param
@return
@see libc/fmt/wcstoll_l.c
wcstombs
@param
@return
@see libc/str/wcstombs.c
wcstou128Decodes 128-bit unsigned integer from wide string.
@param
@return
@see
strtoi128()
@see libc/fmt/wcstou128.c
wcstoulDecodes unsigned integer from wide string.
@param
@return
@see libc/fmt/wcstoul.c
wcstoullDecodes unsigned long long integer from wide string.
@param
@return
@see libc/fmt/wcstoull.c
wcstoull_l
@param
@return
wcstoumaxDecodes uintmax_t from wide string.
@param
@return
@see
strtoimax()
@see libc/fmt/wcstoumax.c
wcswidthReturns monospace display width of wide character string.
@param
@return
wcsxfrm_l
@param
@return
wctypeReturns number representing character class name.
@param
@return
@see libc/str/wctype.c
WindowsTimeToTimeSpecConverts Windows COBOL timestamp to UNIX epoch in nanoseconds.
@param
@return
WindowsTimeToTimeValConverts Windows COBOL timestamp to UNIX epoch in microseconds.
@param
@return
__winerrReturn path for failed Win32 API calls.
@return
@note
this is a code-size saving device
WinMainMain function on Windows NT. The Cosmopolitan Runtime provides the following services, which aim to bring Windows NT behavior closer in harmony with System Five:
@param
@return
WinThreadLaunchUsed by clone() on Windows to launch thread. Windows owns the stack memory when we initially enter threads. This function switches us over, so that we can start using the runtime facilities.
@param
@return
@see
clone()
wmemchrReturns pointer to first instance of character in range.
@param
@return
@asyncsignalsafe
wmemcmpCompares NUL-terminated wide strings w/ limit.
@param
@return
@asyncsignalsafe
@see libc/str/wmemcmp.c
writeWrites data to file descriptor.
@param
@return
@see
read(), pwrite(), writev(), SIGPIPE
@asyncsignalsafe
@restartable
@see libc/calls/write.c
writevWrites data from multiple buffers. This is the same thing as write() except it has multiple buffers. This yields a performance boost in situations where it'd be expensive to stitch data together using memcpy() or issuing multiple syscalls. This wrapper is implemented so that writev() calls where iovlen<2 may be passed to the kernel as write() instead. This yields a 100 cycle performance boost in the case of a single small iovec. Please note that it's not an error for a short write to happen. This can happen in the kernel if EINTR happens after some of the write has been committed. It can also happen if we need to polyfill this system call using write().
@param
@return
@restartable
@see libc/calls/writev.c
WSARecvReceives data from Windows socket.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
WSARecvFromReceives data from Windows socket.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
WSAStartupWinsock2 prototypes.
@return
@note
Some of the functions exported by WS2_32.DLL, e.g. bind(),
overlap with the names used by System V. Prototypes for these
functions are declared within their respective wrappers.
@see libc/nt/winsock.h
WSAWaitForMultipleEventsWaits for events on Windows sockets.
@param
@return
@note
this wrapper takes care of ABI, STRACE(), and __winerr()
xasprintfReturns dynamically formatted string.
@param
@return
@note
greatest of all C functions
@see libc/x/xasprintf.c
xbarfWrites data to file.
@param
@return
@note
this is uninterruptible
@see libc/x/xbarf.c
xcallocAllocates initialized memory, or dies.
@param
@return
@see libc/x/xcalloc.c
xdirnameReturns directory portion of path.
@param
@return
@see libc/x/xdirname.c
xdtoaConverts double to string the easy way.
@param
@return
@see libc/x/xdtoa.c
xdtoafConverts double to string w/ high-accuracy the easy way.
@param
@return
@see libc/x/xdtoaf.c
xdtoalConverts double to string the easy way.
@param
@return
@see libc/x/xdtoal.c
xed_decoded_inst_zero_set_modeClears instruction decoder state.
@param
@return
xed_instruction_length_decodeDecodes machine instruction length. This function also decodes other useful attributes, such as the offsets of displacement, immediates, etc. It works for all ISAs from 1977 to 2020.
@param
@return
@note
binary footprint increases ~4kb if this is used
@see
biggest code in gdb/clang/tensorflow binaries
xed_prefix_table_bitPhash tables for instruction length decoding.
@return
@see
build/rle.py for more context here
xgetlineReads line from stream.
@param
@return
@see
getdelim() for a more difficult api
@see
_chomp()
@see libc/x/xgetline.c
xiso8601tsReturns allocated string representation of nanosecond timestamp.
@param
@return
@see libc/time/xiso8601.c
xiso8601tvReturns allocated string representation of microsecond timestamp.
@param
@return
@see libc/time/xiso8601.c
xjoinpathsJoins paths, e.g. "a" + "b" → "a/b" "a/" + "b" → "a/b" "a" + "b/" → "a/b/" "a" + "/b" → "/b" "." + "b" → "b" "" + "b" → "b"
@param
@return
@see libc/x/xjoinpaths.c
xloadInflates data once atomically, e.g. void *GetData(void) { static char once; static void *ptr; static const unsigned char rodata[] = {...}; if (once) return ptr; return xload(&once, &ptr, rodata, 112, 1024); }The above is an example of how this helper may be used to have lazy loading of big infrequently accessed image data.
@param
@return
@threadsafe
@see libc/x/xload.c
xloadzdLoads δzd encoded data once atomically.
@param
@return
@threadsafe
@see libc/x/xloadzd.c
xmallocAllocates uninitialized memory, or dies.
@param
@return
@see libc/x/xmalloc.c
xmemalignAllocates aligned memory, or dies.
@param
@return
@see libc/x/xmemalign.c
xmemalignzeroAllocates aligned cleared memory, or dies.
@param
@return
xreadlinkReads symbolic link.
@param
@return
@see
readlink()
@see libc/x/xreadlink.c
xreadlinkatReads symbolic link.
@param
@return
@see
readlinkat()
@see libc/x/xreadlinkat.c
xreallocAllocates/expands/shrinks/frees memory, or die. This API enables you to do the following:
p = xrealloc(p, n)The standard behaviors for realloc() still apply:
@param
@return
@see libc/x/xrealloc.c
xsigactionInstalls handler for kernel interrupt, e.g.: onctrlc(sig) { exit(128+sig); } CHECK_NE(-1, xsigaction(SIGINT, onctrlc, SA_RESETHAND, 0, 0));
@param
@return
@see
libc/sysv/consts.sh
@asyncsignalsafe
@vforksafe
@see libc/x/xsigaction.c
xslurpReads entire file into memory.
@param
@return
@note
this is uninterruptible
@see libc/x/xslurp.c
xspawnSpawns process using fork().
@param
@return
@see libc/x/xspawn.c
xstrcatConcatenates strings / chars to newly allocated memory, e.g. xstrcat("hi", ' ', "there")Or without the C99 helper macro:
(xstrcat)("hi", ' ', "there", NULL)This goes twice as fast as the more powerful xasprintf(). It's not quadratic like strcat(). It's much slower than high-effort stpcpy(), particularly with string literals.
@param
@return
@see
gc()
@see libc/x/xstrcat.c
xstrdupAllocates new copy of string, or dies.
@param
@return
@see libc/x/xstrdup.c
xstripextRemoves file extension.
@param
@return
@see libc/x/xstripext.c
xstripextsRemoves file extensions.
@param
@return
@see libc/x/xstripexts.c
xstrndupAllocates new copy of string, with byte limit.
@param
@return
@error
ENOMEM
@see libc/x/xstrndup.c
xunbingDecodes CP437 glyphs to bounds-checked binary buffer, e.g. char *mem = xunbing(u" ☺☻♥♦"); EXPECT_EQ(0, memcmp("\0\1\2\3\4", mem, 5)); tfree(mem);
@param
@return
@see
xunbing(), unbingstr(), unbing()
@see libc/x/tunbing.c
xunbingaSame as xunbing() w/ alignment guarantee.
@param
@return
@see libc/x/tunbing.c
xvallocAllocates page-aligned memory, or dies.
@param
@return
@see libc/x/xvalloc.c
xvasprintfReturns dynamically formatted string.
@param
@return
@see
xasprintf()
@see libc/x/xvasprintf.c
xvspawnSpawns process using vfork().
@param
@return
@see libc/x/xvspawn.c
xwriteWrites data uninterruptibly.
@param
@return
@see libc/x/xwrite.c
zErrorExported to allow conversion of error code to string for compress() and uncompress()
@param
@return
__zipos_closeCloses compressed object.
@param
@return
@asyncsignalsafe
@threadsafe
@vforksafe
@see libc/zipos/close.c
__zipos_freeFrees ZipOS handle.
@param
@return
@asyncsignalsafe
@threadsafe
@see libc/zipos/free.c
__zipos_fstatReads file metadata from αcτµαlly pδrταblε εxεcµταblε object store.
@param
@return
@asyncsignalsafe
@see libc/zipos/fstat.c
__zipos_getReturns pointer to zip central directory of current executable.
@return
@asyncsignalsafe
@threadsafe
@see libc/zipos/get.c
__zipos_lseekChanges current position of zip file handle.
@param
@return
@asyncsignalsafe
@see libc/zipos/lseek.c
__zipos_openLoads compressed file from αcτµαlly pδrταblε εxεcµταblε object store.
@param
@return
@asyncsignalsafe
(todo)
@threadsafe
@see libc/zipos/open.c
__zipos_parseuriExtracts information about ZIP URI if it is one.
@param
@return
__zipos_readReads data from zip store object.
@param
@return
@asyncsignalsafe
@see libc/zipos/read.c
__zipos_statReads file metadata from αcτµαlly pδrταblε εxεcµταblε object store.
@param
@return
@asyncsignalsafe
@see libc/zipos/stat.c
zleb128Encodes signed integer to array.
@param
@return
@see libc/fmt/zleb128.c
zleb64Encodes signed integer to array w/ zig-zag encoding. uleb64 INT64_MAX l: 10𝑐 3𝑛𝑠 zleb64 INT64_MAX l: 13𝑐 4𝑛𝑠 sleb64 INT64_MAX l: 16𝑐 5𝑛𝑠 uleb128 INT64_MAX l: 18𝑐 6𝑛𝑠 zleb128 INT64_MAX l: 18𝑐 6𝑛𝑠 sleb128 INT64_MAX l: 24𝑐 8𝑛𝑠
@param
@return
@see
unzleb64()
@see libc/fmt/zleb64.c
zlibVersionThe application can compare zlibVersion and ZLIB_VERSION for consistency. If the first character differs, the library code actually used is not compatible with the zlib.h header file used by the application. This check is automatically made by deflateInit and inflateInit.
@return
|