objects
kCpuids functions
a64l |
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
@see libc/sock/accept.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.S
acosfReturns arc cosine of 𝑥.
@param
@return
acoslReturns arc cosine of 𝑥.
@param
@return
@define
atan2(abs(sqrt((1-𝑥)*(1+𝑥))),𝑥)
@domain
-1 ≤ 𝑥 ≤ 1
@mode
long,legacy
__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/time/alarm.c
asctimeConverts date time to string.
@param
@return
@see
asctime_r for reentrant version
@see libc/time/asctime.c
asctime_rConverts date time to string.
@param
@return
@see
asctime_r for reentrant version
asinReturns arc sine of 𝑥.
@param
@return
@see libc/tinymath/asin.S
asinfReturns arc sine of 𝑥.
@param
@return
asinlReturns arc sine of 𝑥.
@param
@return
@define
atan2(𝑥,sqrt((1-𝑥)*(1+𝑥)))
@domain
-1 ≤ 𝑥 ≤ 1
@mode
long,legacy
asprintfFormats string, allocating needed memory.
@param
@return
@see
xasprintf() for a better API
@see libc/mem/asprintf.c
__assert_failHandles failure of assert() macro.
@param
@noreturn
atanReturns arc tangent of 𝑥.
@param
@return
@see libc/tinymath/atan.S
atan2Returns arc tangent of 𝑦/𝑥.
@param
@return
@note
the greatest of all libm functions
atan2fReturns arc tangent of 𝑦/𝑥.
@param
@return
atan2lReturns arc tangent of 𝑦/𝑥.
@param
@return
atanfReturns arc tangent of 𝑥.
@param
@return
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
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 number from ASCII string.
@param
@return
@note
calling strtoimax() directly with base 0 permits greater
flexibility in terms of inputs
@see libc/fmt/atoi.c
atomic_loadAtomically loads value. This macro is intended to prevent things like compiler load tearing optimizations.
@param
@return
atomic_storeAtomically stores value. This macro is intended to prevent things like compiler store tearing optimizations.
@param
@return
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. Both / 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 libc/fmt/basename.c
basename_nReturns pointer to last filename component in path. Both / 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
bcmpCompares memory. This API was thought to be nearly extinct until recent versions of Clang (c. 2019) started generating synthetic calls to it.
@param
@return
@asyncsignalsafe
@see libc/str/bcmp.c
bcopyCopies memory the legacy way.
@param
@return
@see libc/str/bcopy.c
bfreeFrees memory return by balloc().
@param
@return
@deprecated
@see libc/mem/bfree.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
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
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
bsrmaxReturns 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
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
bulk_freeFrees and clears (sets to NULL) each non-null pointer in the given array. This is likely to be faster than freeing them one-by-one. If footers are used, pointers that have been allocated in different mspaces are not freed or cleared, and the count of all such pointers is returned. For large arrays of pointers with poor locality, it may be worthwhile to sort this array before calling bulk_free.
@param
@return
bzeroSets memory to zero. C code should always favor memset(), since that's the one we've prototyped with the best optimizations. This definition is used by old code and sometimes code generators, as a thunk.
@param
@return
@see
memset(), explicit_bzero()
c2rangrComputes transcedental trigonometry op w/ reactive scaling.
@param
@return
@clob
%ax
@see
sin,cos,tan
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()
@see libc/mem/calloc.S
cancolorReturns true if ANSI terminal colors are appropriate. We take an optimistic approach here. We use colors, unless we see the environment variable TERM=dumb, which is set by software like Emacs. It's a common antipattern to check isatty(STDERR_FILENO), since that usually makes colors harder to get than they are to remove:
sed 's/\x1b\[[;[:digit:]]*m//g' <color.txt >uncolor.txtIdeally, all software should be updated to understand color, since it's been formally standardized nearly as long as ASCII. Even old MS-DOS supports it (but Windows didn't until Windows 10) yet even tools like less may need wrapper scripts, e.g.:
#!/bin/sh LESSCHARSET=UTF-8 exec /usr/bin/less -RS "$@"It's that easy fam.
@return
@see libc/log/cancolor.c
carsort100Sorts int32 key-value arrays of trivial size.
@param
@return
@see
test/libc/alg/carsort_test.c
@see
carsort1000() if larger
carsort1000Sorts int32 key-value arrays of nontrivial size.
@param
@return
@see
test/libc/alg/carsort_test.c
@see
carsort100() if smaller
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.
@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
@return
@see
libc/log/thunks/__check_fail_ndebug.S
CheckElfAddress
@param
@return
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 bitThis works on Windows NT if you ignore the error ;-)
@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
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.
@param
@return
@error
ENOSYS if clockid isn't available; in which case this function
guarantees an ordinary timestamp is still stored to ts; and
errno isn't restored to its original value, to detect prec. loss
@see
strftime(), gettimeofday()
@asyncsignalsafe
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
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()
@see libc/bits/cmpxchg.c
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
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
_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
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
@domain
-(3π/8) < 𝑥 < 3π/8 for best accuracy
@see libc/tinymath/cos.S
cosfReturns cosine of 𝑥.
@param
@return
@domain
-(3π/8) < 𝑥 < 3π/8 for best accuracy
@see libc/tinymath/cosf.S
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
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)
@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.S
crc32c_pureComputes Castagnoli CRC-32 on old computers.
@param
@return
crc32c_sse42Hashes data with hardware acceleration at 10GBps.
@param
@return
@note
needs Nehalem+ c. 2008 or Bulldozer+ c. 2011
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
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
__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
_d2ld2Thunks double(*fn)(double,double) -> long double fn.
@param
@return
@note
100% negligible overhead
__deferCalls FN(ARG) when function returns.
@param
@return
@see libc/runtime/gc.h
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
deserializednsheaderSerializes DNS message header to wire.
@param
@return
@see libc/dns/dnsheader.c
devrandReads random bytes from system pseudo random number api.
@param
@return
@see libc/rand/devrand.c
__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.
@param
@return
@see libc/fmt/dirname.c
div1000000000int64Divides 64-bit signed integer by 1,000,000,000.
@param
@return
div1000000int64Divides 64-bit signed integer by 1,000,000.
@param
@return
div10000int64Divides 64-bit signed integer by 10,000.
@param
@return
div100int64Divides 64-bit signed integer by 100.
@param
@return
__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_callocindependent_calloc(size_t n_elements, size_t element_size, void* chunks[]); independent_calloc is similar to calloc, but instead of returning a single cleared space, it returns an array of pointers to n_elements independent elements that can hold contents of size elem_size, each of which starts out cleared, and can be independently freed, realloc'ed etc. The elements are guaranteed to be adjacently allocated (this is not guaranteed to occur with multiple callocs or mallocs), which may also improve cache locality in some applications. The "chunks" argument is optional (i.e., may be null, which is probably the most typical usage). If it is null, the returned array is itself dynamically allocated and should also be freed when it is no longer needed. Otherwise, the chunks array must be of at least n_elements in length. It is filled in with the pointers to the chunks. In either case, independent_calloc returns this pointer array, or null if the allocation failed. * If n_elements is zero and "chunks" is null, it returns a chunk representing an array with zero elements (which should be freed if not wanted). Each element must be freed when it is no longer needed. This can be done all at once using bulk_free. independent_calloc simplifies and speeds up implementations of many kinds of pools. * It may also be useful when constructing large data structures that initially have a fixed number of fixed-sized nodes, but the number is not known at compile time, and some of the nodes may later need to be freed. For example:
struct Node { int item; struct Node* next; }; struct Node* build_list() { struct Node **pool; int n = read_number_of_nodes_needed(); if (n <= 0) return 0; pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0); if (pool == 0) __die(); // organize into a linked list... struct Node* first = pool[0]; for (i = 0; i < n-1; ++i) pool[i]->next = pool[i+1]; free(pool); * // Can now free the array (or not, if it is needed later) return first; }
@param
@return
dlindependent_comallocindependent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]); independent_comalloc allocates, all at once, a set of n_elements chunks with sizes indicated in the "sizes" array. It returns an array of pointers to these elements, each of which can be independently freed, realloc'ed etc. The elements are guaranteed to be adjacently allocated (this is not guaranteed to occur with multiple callocs or mallocs), which may also improve cache locality in some applications. The "chunks" argument is optional (i.e., may be null). If it is null the returned array is itself dynamically allocated and should also be freed when it is no longer needed. Otherwise, the chunks array must be of at least n_elements in length. It is filled in with the pointers to the chunks. In either case, independent_comalloc returns this pointer array, or null if the allocation failed. If n_elements is zero and chunks is null, it returns a chunk representing an array with zero elements (which should be freed if not wanted). Each element must be freed when it is no longer needed. This can be done all at once using bulk_free. independent_comallac differs from independent_calloc in that each element may have a different size, and also that it does not automatically clear elements. independent_comalloc can be used to speed up allocation in cases where several structs or objects must always be allocated at the same time. For example:
struct Head { ... } struct Foot { ... } void send_message(char* msg) { int msglen = strlen(msg); size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) }; void* chunks[3]; if (independent_comalloc(3, sizes, chunks) == 0) __die(); struct Head* head = (struct Head*)(chunks[0]); char* body = (char*)(chunks[1]); struct Foot* foot = (struct Foot*)(chunks[2]); // ... }In general though, independent_comalloc is worth using only for larger values of n_elements. For small values, you probably won't detect enough difference from series of malloc calls to bother. Overuse of independent_comalloc can increase overall memory usage, since it cannot reuse existing noncontiguous small chunks that might be available for some of the elements.
@param
@return
dlmalloc_dispose_chunk
@param
@return
dlmalloc_statsPrints on stderr the amount of space obtained from the system (both via sbrk and mmap), the maximum amount (which may be more than current if malloc_trim and/or munmap got called), and the current number of bytes allocated via malloc (or realloc, etc) but not yet freed. Note that this is the number of bytes allocated, not the number requested. It will be larger than the number requested because of alignment and bookkeeping overhead. Because it includes alignment wastage as being in use, this figure may be greater than zero even when no user-level chunks are allocated. The reported current and maximum system memory can be inaccurate if a program makes other calls to system memory allocation functions (normally sbrk) outside of malloc. malloc_stats prints only the most commonly interesting statistics. More information can be obtained by calling mallinfo.
@param
@return
dlmalloc_trimIf possible, gives memory back to the system (via negative arguments to sbrk) if there is unused memory at the The
@param
@return
dlmalloc_try_realloc_chunk
@param
@return
dnsnamecmpCompares DNS hostnames in reverse lexicographical asciibetical order.
@param
@return
@see
test/libc/dns/dnsnamecmp_test.c (the code that matters)
__dos2errnoTranslates Windows error using superset of 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
dupDuplicates file descriptor/handle.
@param
@return
@asyncsignalsafe
@vforksafe
@see libc/calls/dup.c
dup2Duplicates file descriptor, granting it specific number.
@param
@return
@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
@flags
can have O_CLOEXEC
@see
dup(), dup2()
@see libc/calls/dup3.c
eai2strTurns getaddrinfo() return code into string.
@param
@return
@see libc/dns/eai2str.c
endswithReturns true if s has suffix.
@param
@return
@see libc/str/endswith.c
endswith16Returns true if s has suffix.
@param
@return
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.
@return
@see
libc/sysv/consts.sh
@see
libc/sysv/errfuns.h
@see
__errno_location() stable abi
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
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
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
expReturns 𝑒^x.
@param
@return
@see libc/tinymath/exp.S
exp10Returns 10^x.
@param
@return
@see
pow(), exp()
exp10fReturns 10^x.
@param
@return
exp10lReturns 10^x.
@param
@return
exp2Returns 2^𝑥.
@param
@return
@see libc/tinymath/exp2.S
exp2fReturns 2^𝑥.
@param
@return
exp2lReturns 2^𝑥.
@param
@return
expfReturns 𝑒^x.
@param
@return
@see libc/tinymath/expf.S
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. This implementation also hoses every register the abi allows. A concomitant prototype (str.h) countermands compiler magic.
@param
@return
expm1Returns 𝑒^x-1.
@param
@return
expm1fReturns 𝑒^x-1.
@param
@return
expm1lReturns 𝑒^x-1.
@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
@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
favailReturns number of bytes available in stream buffer.
@param
@return
@see libc/stdio/favail.c
fchdirSets current directory based on file descriptor.
@param
@return
@see
open(path, O_DIRECTORY)
@asyncsignalsafe
@see libc/calls/fchdir.c
fchmodChanges file permissions via open()'d file descriptor, 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 V 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 bitThis works on Windows NT if you ignore the error ;-)
@param
@return
@errors
ENOSYS
@asyncsignalsafe
@see
chmod()
@see libc/calls/fchmod.c
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
@see libc/calls/fchown.c
fchownatChanges owner and/or group of pathname.
@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));
@param
@return
@asyncsignalsafe
@see libc/calls/fcntl.c
fdatasyncBlocks until kernel flushes non-metadata buffers for fd to disk.
@param
@return
@see
fsync(), sync_file_range()
@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
__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 libc/stdio/feof.c
ferrorReturns nonzero if stream is in error state.
@param
@return
@note
EOF doesn't count
@see
feof()
@see libc/stdio/ferror.c
fflushBlocks until data from stream buffer is written out.
@param
@return
@see libc/stdio/fflush.c
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
fgetsReads content 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 libc/stdio/fgets.c
fgetwcReads UTF-8 character from stream.
@param
@return
@see libc/stdio/fgetwc.c
fgetwsReads UTF-8 content from stream into UTF-32 buffer.
@param
@return
@see libc/stdio/fgetws.c
filecmpCompares contents of files with memcmp().
@param
@return
@see libc/x/filecmp.c
fileexistsReturns true if file exists at path. 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
@see libc/stdio/fileno.c
FileTimeToTimeSpecConverts Windows COBOL timestamp to UNIX epoch in nanoseconds.
@param
@return
FindComBinaryReturns path of binary without debug information, or null.
@return
FindDebugBinaryReturns path of binary with the debug information, or null.
@return
__fixupnewfdApplies file descriptor fixups on XNU or old Linux.
@param
@return
@see
__fixupnewsockfd() for socket file descriptors
__flbfReturns nonzero if stream is line buffered.
@param
@return
@see libc/stdio/flbf.c
flockAcquires lock on file.
@param
@return
@see libc/calls/flock.c
flockfileDoes nothing since Cosmopolitan currently doesn't support threads.
@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
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()
fnmatchMatches filename.
@param
@return
@see
glob()
fopenOpens file as stream object.
@param
@return
@note
microsoft unilaterally deprecated this function lool
@see libc/stdio/fopen.c
forkCreates new process zygote style.
@return
@asyncsignalsafe
@see libc/runtime/fork.c
__fpurgeDiscards contents of stream buffer.
@param
@return
@see libc/stdio/fpurge.c
fputcWrites byte to stream.
@param
@return
@see
putc() if called within loop
@see libc/stdio/fputc.c
fputcfbWrites byte to stream.
@param
@return
@see libc/stdio/fputcfb.c
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
@see libc/stdio/fputs.c
fputwcWrites wide character to stream.
@param
@return
@see libc/stdio/fputwc.c
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
@see libc/stdio/fputws.c
freadReads data from stream.
@param
@return
@see libc/stdio/fread.c
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 cuase the current program to abort.
@param
@return
@see
dlfree()
@see libc/mem/free.S
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
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
new offset or -1 on error
@see libc/stdio/fseek.c
__fsetlockingDoes nothing and returns
@param
@return
fstatReturns information about file, via open()'d descriptor.
@param
@return
@asyncsignalsafe
@see libc/calls/fstat.c
fstatatReturns information about thing.
@param
@return
@see
S_ISDIR(st.st_mode), S_ISREG()
@asyncsignalsafe
@see libc/calls/fstatat.c
fsyncBlocks until kernel flushes buffers for fd to disk.
@param
@return
@see
fdatasync(), sync_file_range()
@asyncsignalsafe
@see libc/calls/fsync.c
ftellReturns current position of stream.
@param
@return
@returns
current byte offset from beginning of file, or -1
@see libc/stdio/ftell.c
ftoaFormats floating point number.
@param
@return
@see
xdtoa() for higher precision at the cost of bloat
@see
palandprintf() which is intended caller
ftracePrints 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
ftrace_initEnables plaintext function tracing if The
@param
@return
@see
libc/runtime/_init.S for documentation
ftruncateChanges size of file.
@param
@return
@asyncsignalsafe
ftrylockfileDoes nothing since Cosmopolitan currently doesn't support threads.
@param
@return
funlockfileDoes nothing since Cosmopolitan currently doesn't support threads.
@param
@return
futimensSets atime/mtime on file descriptor.
@param
@return
@note
better than microsecond precision on most platforms
@see
fstat() for reading timestamps
@see libc/time/futimens.c
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
@see libc/stdio/fwrite.c
__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
<LIMBO>
@see libc/nexgen32e/gc.S
gdbexecAttachs GDB temporarilly, to do something like print a variable.
@param
@return
@see libc/log/gdbexec.c
gdtoa
@param
@return
get_current_dir_nameReturns current working directory. If the PWD environment variable is set, that'll be returned (since it's faster than issuing a system call).
@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
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
@asyncsignalsafe
getcachesizeReturns CPU cache size.
@param
@return
getcharReads uint8_t from standard input.
@return
@see libc/stdio/getchar.S
getcwdReturns current working directory.
@param
@return
@see
get_current_dir_name() which is better
@error
ERANGE, EINVAL
@see libc/calls/getcwd.c
getdelimReads string from stream.
@param
@return
@note
this function can't punt EINTR to caller
@see
getline(), gettok_r()
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
GetElfSectionAddress
@param
@return
GetElfSectionHeaderAddress
@param
@return
GetElfSectionName
@param
@return
GetElfSegmentHeaderAddress
@param
@return
GetElfString
@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
@see libc/calls/getenv.c
getfiledescriptorsizeDetermines size of open file.
@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. On Linux, this is fast.
@return
@asyncsignalsafe
@see libc/calls/getuid.c
getgrgid_r
@param
@return
gethostnameReturns name of host system, e.g. pheidippides.domain.example ^^^^^^^^^^^^
@param
@return
gethoststxtReturns parsed sorted singleton hardcoded hostname→ip4 map.
@return
@note
yoinking realloc() ensures there's no size limits
getitimerRetrieves last setitimer() value, correcting for remaining time.
@param
@return
getlineReads line from stream. 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
xgetline(), getdelim(), gettok_r()
@see libc/stdio/getline.c
getntnameserversExtracts DNS nameserver IPs from Windows Registry.
@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
getpriorityReturns nice value of thing.
@param
@return
@see
setpriority(), nice()
GetProcAddressModuleReturns address of function in a DLL that's already loaded.
@param
@return
getpwuid_r
@param
@return
getrandomReturns random bytes appropriate for random seeding.
@param
@return
getrlimitGets resource limit for current process.
@param
@return
@see
libc/sysv/consts.sh
getrusageReturns resource usage statistics.
@param
@return
getsidCreates session and sets the process group id.
@param
@return
@see libc/calls/getsid.c
GetSymbolTableReturns debug binary symbol table, as global singleton.
@return
GetTempPathA_flunkCalls GetTempPathA() w/ different API.
@return
@see
GetSystemDirectoryA(), GetWindowsDirectoryA()
gettimeofdayReturns system wall time in microseconds.
@param
@return
@see
clock_gettime() for nanosecond precision
@see
strftime() for string formatting
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. On Linux, this is fast.
@return
@asyncsignalsafe
@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
getwcharReads Thompson-Pike encoded varint from standard input.
@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
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
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
hammingCounts number of different bits.
@param
@return
@see
https://en.wikipedia.org/wiki/Hamming_code
@see libc/bits/hamming.c
hextointConverts ASCII hexadecimal character to integer case-insensitively.
@param
@return
@see libc/str/hextoint.c
HighwayHash64
@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
iconv
@param
@return
@see libc/unicode/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
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
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
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
_init_systemfive_jmptabInitializes System Five system call support. (1) Extracts parameters passed by kernel (2) Detects OS without issuing system calls (3) Unpacks magnums from libc/sysv/consts.sh (4) Replaces stack with one we control
@param
@return
@note
OpenBSD devs: let us know if you start using auxv
insertionsortSorts array of signed 32-bit integers.
@param
@return
@see
djbsort()
int128toarray_radix10Converts signed 128-bit integer to string.
@param
@return
int64toarray_radix10Converts signed 64-bit integer to string.
@param
@return
interruptiblecallCalls function that may be cancelled by a signal.
@param
@return
ioctlControls settings on device.
@param
@return
@vforksafe
@see libc/calls/ioctl.c
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_tiocswinszReturns width and height of terminal.
@param
@return
@see
ioctl(fd, TIOCSWINSZ, ws) dispatches here
isabspathReturns true if pathname could be absolute on any known platform. The ones we know about are System V (/foo/bar), DOS (C:\foo\bar), Windows NT (\\.\C:\foo\bar), Google Cloud (gs://bucket/foo/bar), etc.
@param
@return
@see libc/fmt/isabspath.c
isalnumReturns nonzero if c is lower, alpha, or digit.
@param
@return
@see libc/str/isalnum.c
isattyReturns true if file descriptor is backed by a terminal device.
@param
@return
@asyncsignalsafe
@see libc/calls/isatty.c
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
isexecutableReturns true if file exists and is executable.
@param
@return
@see
access(exe, X_OK) which is more accurate on NT
@asyncsignalsafe
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
isprintReturns nonzero if c is printable ascii including space.
@param
@return
@see libc/str/isprint.c
ispunctReturns nonzero if
@param
@return
@see libc/str/ispunct.c
isspaceReturns true if c is space, \t, \r, \n, \f, or \v.
@param
@return
@see libc/str/isspace.c
isupperReturns nonzero if c is uppercase alpha ascii character.
@param
@return
@see libc/str/isupper.c
iswcntrlReturns nonzero if wc is C0 or C1 control code.
@param
@return
@see libc/str/iswcntrl.c
_jmpstackSwitches stack.
@param
@noreturn
kCp437ibm cp437 unicode table w/ string literal safety ░▄██▒▄█ ▐██ ░░░ ▀▀████▒▀█▄ ▐███▓██░ ██▌ ▀████▄■█▄ ▐█▓███▀█░██▀ ░ ░▀█████▓▄ ▐█▓██▀▄█▒██▀ ▄▄░ ▄▄▄ ░░░ ░▀████▒▄ ▐████▀▄█■█▀ ▀▀ ░█████░ ▐█▓█▀████▀ ░ ▐▓███▒ █░███▀▀ ░░░ ▄█ ░░░ █████ ▐█▓█░▀▀ ░░▄█▄▄▄▄▄ ▀▄ ▌▄▄▄░▄▄▄▄▄ ▐████░ ▐███▌ ▄▀█████████▄ ▌▐▄████████▄ ▐▓███░ ▐███░░░▀▄█▀▄▄████▄▀░ ▐████████▒ ▀ ░███░ ░████░ ▓▀ ▄███████▀▌ ▀▄■████▀▀█▀ ██▀█ ▓███░ ░▄▀▀░░░ ▀ ░░▌ ▄▀▀▄░░▀░▄▀▄ ▐██▀▄ ░███░ ▄▓▓▄▄░▀▀█▀█ ▌░░ ▀█▀█▀▀ ▐██▀ █▀▄▐██ ▀░░ ▄▀ ▐ █ ▀ ▄▄▄░ ░▀▄█▄▀█ ▌▄ █▓ ▒ ░ █▄█▄▀▄▄▄███▄▀▄ ░░ ░ ▀ █▌ █▌▄░▌ ░░░▄▀█▀███████▄▀▄▀▄▀▀▄▄▄ █▀█░▐ ██▄ ░░░▄█▄▀██▄█■██████▄█▄█▄■▀█░ ▐░▐ ▀██░ ░▄██████████████████▄█▄█ ░█ ░ ▄▀ ▀▓█▄▓░░ ▒█▀█████████████████████▒ ██▀ ▀███ ▓▒ ██████████████▀▀▀▀█▄▀ ░▄█▒ ▀███ ▀█▄▀▄█████▀▀ ▓▓▓▄░ ▐ ░▄██ ▀██ ▄███████▄████████▀░░ ░▄██ ▄██▀▀▄ █▄▀▄██▒▒███████████▀▀▀▄░ ░███░ ▄██▀▄▄░░▀▐▄████▄ █████▀▄░░█▀▄▀░░ ▄██░ █████▄▄▄███▀░█▌██▄▀▀█████▄▄░░░▄▄███▀██▄ ▄▀▀▀▄▄ ▀██████▀■▄█▄▄ ░▀███████████████▓▓░░▄██▀▄████▄▄▀▄ █▀█ █ █▀█ █▀█ █▄▀ ▐▀█▀▌█▀█ █▀█ █▄ █ ▀█▀ █▀█ █▀▀ █▀▄ █ █ █ █ █ ▀▄ █ █▀▄ █ █ █ ▀█ █ █ ▀▀█ █▄█ █▄▌█▄█ █▄█ █ █ █ █ █ █▄█ █ █ ▄█▄ █▄█ █▄█ THERE WILL BE BLOCKS march 01 2017
@return
@see
libc/str/str.h
@see
kCp437i[]
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
kStartTscStores CPU Timestamp Counter at startup. It can be useful as an added source of seeding information.
@return
@note
rdtsc is a 25 cycle instruction
kTmpPathRII constant holding /tmp/ directory.
@return
@note
on win32 this is firstNonNull($TMP, $TEMP, $PWD)
@note
guarantees trailing slash if non-empty
kToLowerASCII uppercase → lowercase translation tables. char kToLower[256]; char16_t kToLower16[256];
@return
@note
kToLower16 saves 128kb; CMOVcc can't even 8-bit
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
ldexpReturns 𝑥 × 2ʸ.
@param
@return
ldexpfReturns 𝑥 × 2ʸ.
@param
@return
ldexplReturns 𝑥 × 2ʸ.
@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
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()
lockxchgCompares and exchanges w/ lock prefix.
@param
@return
@see
xchg()
@see libc/bits/lockxchg.c
logReturns natural logarithm of 𝑥.
@param
@return
@see libc/tinymath/log.S
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
@see libc/tinymath/log2.S
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
_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
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
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
lzcntFinds leading bits in 𝑥. 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
lzcntlFinds leading bits in 𝑥. 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
lzcntllFinds leading bits in 𝑥. 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
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.
@param
@return
@see
mkdir()
@see libc/x/makedirs.c
mallinfoReturns (by copy) a struct containing various summary statistics:
@param
@return
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
@note
malloc(0) → malloc(32)
@see
dlmalloc()
@see libc/mem/malloc.S
malloc_footprintReturns the number of bytes obtained from the system. The total number of bytes allocated by malloc, realloc etc., is less than this value. Unlike mallinfo, this function returns only a precomputed result, so can be called frequently to monitor memory consumption. Even if locks are otherwise defined, this function does not use them, so results might not be up to date.
@return
malloc_footprint_limitReturns the number of bytes that the heap is allowed to obtain from the system, returning the last value returned by malloc_set_footprint_limit, or the maximum size_t value if never set. The returned value reflects a permission. There is no guarantee that this number of bytes can actually be obtained from the system.
@return
malloc_inspect_allTraverses the heap and calls the given handler for each managed region, skipping all bytes that are (or may be) used for bookkeeping purposes. Traversal does not include include chunks that have been directly memory mapped. Each reported region begins at the start address, and continues up to but not including the end address. The first used_bytes of the region contain allocated data. If used_bytes is zero, the region is unallocated. The handler is invoked with the given callback argument. If locks are defined, they are held during the entire traversal. It is a bad idea to invoke other malloc functions from within the handler. For example, to count the number of in-use chunks with size greater than 1000, you could write:
static int count = 0; void count_chunks(void* start, void* end, size_t used, void* arg) { if (used >= 1000) ++count; }then,
malloc_inspect_all(count_chunks, NULL);
@param
@return
malloc_max_footprintReturns the maximum number of bytes obtained from the system. This value will be greater than current footprint if deallocated space has been reclaimed by the system. The peak number of bytes allocated by malloc, realloc etc., is less than this value. Unlike mallinfo, this function returns only a precomputed result, so can be called frequently to monitor memory consumption. Even if locks are otherwise defined, this function does not use them, so results might not be up to date.
@return
malloc_set_footprint_limitSets the maximum number of bytes to obtain from the system, causing failure returns from malloc and related functions upon attempts to exceed this value. The argument value may be subject to page rounding to an enforceable limit; this actual value is returned. Using an argument of the maximum possible size_t effectively disables checks. If the argument is less than or equal to the current malloc_footprint, then all future allocations that require additional system memory will fail. However, invocation cannot retroactively deallocate existing used memory.
@param
@return
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()
malloptSets memory allocation parameter. The format is to provide a (parameter-number, parameter-value) pair. mallopt then sets the corresponding parameter to the argument value if it can (i.e., so long as the value is meaningful), and returns 1 if successful else 0. SVID/XPG/ANSI defines four standard param numbers for mallopt, normally defined in malloc.h. None of these are use in this malloc, so setting them has no effect. But this malloc also supports other options in mallopt:
Symbol param # default allowed param values M_TRIM_THRESHOLD -1 2*1024*1024 any (-1U disables trimming) M_GRANULARITY -2 page size any power of 2 >= page size M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support)
@param
@return
__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);Except it offers a small saving on code size.
@param
@return
mbrtowc
@param
@return
@see libc/fmt/mbrtowc.c
mbsrtowcs
@param
@return
@see libc/fmt/mbsrtowcs.c
memalignAllocates aligned memory. Returns a pointer to a newly allocated chunk of n bytes, aligned in accord with the alignment argument. The alignment argument should be a power of two. If the argument is not a power of two, the nearest greater power is used. 8-byte alignment is guaranteed by normal malloc calls, so don't bother calling memalign with an argument of 8 or less.
@param
@return
@note
overreliance on memalign is a sure way to fragment space
@see
dlmemalign()
@see libc/mem/memalign.S
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
memchrReturns pointer to first instance of character.
@param
@return
@asyncsignalsafe
@see libc/str/memchr.c
memchr16Returns pointer to first instance of character in range.
@param
@return
@asyncsignalsafe
memcmpCompares memory.
@param
@return
@asyncsignalsafe
@see libc/str/memcmp.c
memcpyCopies memory. DEST and SRC must not overlap, unless DEST≤SRC.
@param
@return
@mode
long
@asyncsignalsafe
MemCpyCopies memory w/ minimal impact ABI.
@param
@return
@clob
flags,rcx,xmm3,xmm4
@mode
long
memeqmaskCreates bit mask of which bytes are the same.
@param
@return
@note
buffers should be 128-byte aligned
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
memmemSearches for fixed-length substring in memory region.
@param
@return
@see libc/str/memmem.c
memmoveCopies memory. DEST and SRC may overlap.
@param
@return
@clob
flags,rcx
@asyncsignalsafe
memmove_pureCopies memory. DST and SRC may overlap.
@param
@return
@asyncsignalsafe
mempcpyCopies memory. DEST and SRC must not overlap unless DEST ≤ SRC.
@param
@return
memrchrSearches for last instance of byte in memory region.
@param
@return
@note
AVX2 requires Haswell (2014+) or Excavator (2015+)
@asyncsignalsafe
memrchr16Searches for last instance of uint16_t in memory region.
@param
@return
@note
AVX2 requires Haswell (2014+) or Excavator (2015+)
memsetSets memory.
@param
@return
@mode
long
@asyncsignalsafe
MemSetSets memory w/ minimal-impact ABI.
@param
@return
@clob
flags,rcx,xmm3
@mode
long
memset16Sets wide memory.
@param
@return
@asyncsignalsafe
memset_pureSets memory.
@param
@return
@asyncsignalsafe
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
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
EEXIST, ENOTDIR, ENAMETOOLONG, EACCES
@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
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
@kudos
Daniel Colascione for teaching how to quote
@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 (0x8000)
__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
mmapBeseeches system for page-table entries. char *p = mmap(NULL, 65536, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); munmap(p, 65536);
@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
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()
mremap
@param
@return
msyncSynchronize memory mapping changes to disk. Without this, there's no guarantee memory is written back to disk. In practice, what that means is just Windows NT.
@param
@return
@see libc/runtime/msync.c
__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. This function may be used to punch holes in existing mappings, but your mileage may vary on Windows.
@param
@return
nanosleepSleeps for a particular amount of time.
@param
@return
__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
niceChanges process priority.
@param
@return
@see
Linux claims ioprio_set() is tuned automatically by this
@see libc/calls/nice.c
nowlReturns timestamp without needing system calls.
@return
@note
uses microsecond scale fallback on k8 or vm
@see libc/calls/nowl.S
__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
ntoa
@param
@return
ntoa2
@param
@return
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
@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
@vforksafe
@see libc/calls/open.c
openanonCreates anonymous file.
@param
@return
@see
memfd_create() if disk-paranoid
@see
mkostempsm() for named files
openatOpens file.
@param
@return
@asyncsignalsafe
@vforksafe
@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()
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
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
palandprintfImplements {,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
@asyncsignalsafe
@vforksafe
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
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
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
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 and its callback function has been called. It's a better idea to use sigsuspend() w/ sigprocmask() to avoid race conditions
@return
@see
sigsuspend()
@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
@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 signed 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
popcntReturns number of bits set in integer.
@param
@return
@see libc/bits/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 (1) assigns the allocated memory to *pp rather than returning it, (2) fails and returns EINVAL if the alignment is not a power of two (3) fails and returns ENOMEM if memory cannot be allocated.
@param
@return
posix_openptOpens new pseudo teletypewriter.
@param
@return
@params
flags is usually O_RDWR|O_NOCTTY
powReturns 𝑥^𝑦.
@param
@return
@see libc/tinymath/pow.S
pow10Returns 10^x.
@param
@return
@see
pow(), exp()
pow10fReturns 10^x.
@param
@return
pow10lReturns 10^x.
@param
@return
__pow_finiteReturns 𝑥^𝑦.
@param
@return
@see libc/tinymath/pow.S
powfReturns 𝑥^𝑦.
@param
@return
@see libc/tinymath/powf.S
__powf_finiteReturns 𝑥^𝑦.
@param
@return
@see libc/tinymath/powf.S
powiReturns 𝑥^𝑦.
@param
@return
@see libc/tinymath/powi.S
powifReturns 𝑥^𝑦.
@param
@return
preadReads from file at offset, thus avoiding superfluous lseek().
@param
@return
@see
pwrite(), write()
@asyncsignalsafe
@vforksafe
@see libc/calls/pread.c
preadvReads data from multiple buffers from file descriptor at offset.
@param
@return
@asyncsignalsafe
@vforksafe
@see libc/calls/preadv.c
__printPrints string, by any means necessary. This function offers a subset of write(STDERR_FILENO) functionality. It's designed to work even when the runtime hasn't initialized, e.g. before _init() gets called.
@param
@return
@clob
nothing except flags
PrintBacktraceUsingSymbolsPrints stack frames with symbols. PrintBacktraceUsingSymbols(STDOUT_FILENO, NULL, GetSymbolTable());
@param
@return
printfFormats and writes string to stdout. Cosmopolitan supports most of the standard formatting behaviors
described by
@param
@return
@see
palandprintf() for intuitive reference documentation
@see
{,v}{,s{,n},{,{,x}as},f,d}printf
@see libc/stdio/printf.c
__prot2ntConverts System Five memory protection flags to Windows NT, Part 1.
@param
@return
@see
libc/sysv/consts.sh
psadbwComputes sum of absolute differences.
@param
@return
@mayalias
@see libc/intrin/psadbw.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 right 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
ptraceTraces process.
@param
@return
@note
de facto linux only atm
@see libc/calls/ptrace.c
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
putcharWrites byte to stdout.
@param
@return
@see libc/stdio/putchar.c
putenvEmplaces environment key=value.
@param
@return
@see
setenv(), getenv()
@see libc/mem/putenv.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
@see libc/stdio/putwc.S
putwcharWrites wide character to stdout.
@param
@return
pvallocEquivalent to valloc(minimum-page-that-holds(n)), that is, round up n to nearest pagesize.
@param
@return
@see
dlpvalloc()
@see libc/mem/pvalloc.S
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
qsort_r()
@see libc/alg/qsort.c
qsort_rSorts array.
@param
@return
@see
qsort()
@see libc/alg/qsort.c
raiseSends signal to this process.
@param
@return
@asyncsignalsafe
@see libc/calls/raise.c
randReturns 31-bit random number using a linear congruential generator. Please note that, unlike rand32(), the rand() function uses the same seed at startup by default, unless srand() is called. This makes it useful in cases where deterministic behavior is needed.
@return
@see libc/rand/rand.c
rand32This function is an independent 32-bit clone of rand64().
@return
@see libc/rand/rand32.c
rand64Returns nondeterministic random number. This function uses a good random source if it's available, which takes ~400 cycles (~99ns). Otherwise it's seeded at program start with the system provided random value and may perform a few microseconds worth of system calls to get a good value.
@return
@see
rngset()
@see libc/rand/rand64.c
rawmemchrReturns pointer to first instance of character.
@param
@return
@see libc/str/rawmemchr.c
rawmemchr16Returns pointer to first instance of character in range.
@param
@return
rawwmemchrReturns pointer to first instance of character in range.
@param
@return
rdrandIntel Secure Key Digital Random Number Generator Introduced w/ Ivy Bridge c. 2013 and Excavator c. 2015
@return
@see
rdseed(), rand32(), rand64(), and randcpy()
@see libc/rand/rdrand.c
rdseedIntel Securer Key Digital Random Number Generator Introduced w/ Ivy Bridge c. 2013 and Excavator c. 2015
@return
@see
rdrand(), rand32(), rand64(), and randcpy()
@see libc/rand/rdseed.c
readReads data from file descriptor.
@param
@return
@see
write(), pread(), readv()
@asyncsignalsafe
@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 "\033[A" CURSOR UP "\033[38;5;202m" ORANGERED "\eOP" PF1This 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. String control sequences, e.g. "\e_hello\e\\" currently are not tokenized as a single read. Lastly note, this function has limited support for UNICODE representations of C0/C1 control codes, e.g.
"\000" NUL "\300\200" NUL "\302\233A" CURSOR UP
@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
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()
@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()
reallocarrayManages array memory, the BSD way.
@param
@return
recvReceives data from network socket.
@param
@return
@error
EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable),
EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
@asyncsignalsafe
@see libc/sock/recv.c
regcompCompiles regular expression, e.g. regex_t rx; EXPECT_EQ(REG_OK, regcomp(&rx, "^[A-Za-z]{2}$", REG_EXTENDED)); EXPECT_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
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
renameMoves file the Unix way.
@param
@return
@asyncsignalsafe
@see libc/calls/rename.c
renameatRenames files relative to directories.
@param
@return
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
resolvednsQueries Domain Name System for address associated with name.
@param
@return
@error
EAFNOSUPPORT. ENETDOWN, ENAMETOOLONG, EBADMSG
resolvehoststxtFinds address associated with name in HOSTS.TXT table. This function performs binary search, so sorthoststxt() must be called on the table beforehand.
@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
rijndaelinitComputes key schedule for rijndael().
@param
@return
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
rldecodeSeventeen 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[1024]; rngset(buf, sizeof(buf), rand64, -1);
@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
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()
scalblnReturns 𝑥 × 2ʸ.
@param
@return
scalblnfReturns 𝑥 × 2ʸ.
@param
@return
scalblnlReturns 𝑥 × 2ʸ.
@param
@return
scalbnReturns 𝑥 × 2ʸ.
@param
@return
scalbnfReturns 𝑥 × 2ʸ.
@param
@return
scalbnlReturns 𝑥 × 2ʸ.
@param
@return
scanfStandard input decoder.
@param
@return
@see
libc/fmt/vcscanf.h
@see libc/stdio/scanf.c
sched_setaffinityAsks kernel to only schedule process on particular CPUs.
@param
@return
sendSends data to network socket.
@param
@return
@error
EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable),
EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
@asyncsignalsafe
@see libc/sock/send.c
serializednsheaderSerializes DNS message header 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
setegidSets effective group ID.
@param
@return
@see
setgid(), getauxval(AT_SECURE)
@see libc/calls/setegid.S
setenvCopies variable to environment.
@param
@return
@see
putenv(), getenv()
@see libc/mem/setenv.c
seteuidSets effective user ID.
@param
@return
@see
setuid(), getauxval(AT_SECURE)
@see libc/calls/seteuid.S
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.
@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
setprioritySets nice value of thing.
@param
@return
@see
getpriority(), nice()
setresgidSets real, effective, and "saved" group ids.
@param
@return
@see
setregid(), getauxval(AT_SECURE)
setresuidSets real, effective, and "saved" user ids.
@param
@return
@see
setreuid(), getauxval(AT_SECURE)
setrlimitSets resource limit for current process.
@param
@return
@see
libc/sysv/consts.sh
_setstackSwitches stack.
@param
@return
setvbufTunes buffering settings for an stdio stream.
@param
@return
@see libc/stdio/setvbuf.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
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));
@param
@return
@see
xsigaction() for a much better api
@asyncsignalsafe
@vforksafe
sigaddsetAdds signal to set.
@param
@return
@asyncsignalsafe
sigdelsetRemoves signal from set.
@param
@return
@asyncsignalsafe
sigemptysetRemoves all signals from set.
@param
@return
@asyncsignalsafe
sigfillsetAdds all signals to set.
@param
@return
@asyncsignalsafe
sigismemberReturns true if signal is member of set.
@param
@return
@asyncsignalsafe
signalInstalls kernel interrupt handler.
@param
@return
@see
sigaction() which has more features
@see libc/calls/signal.c
sigprocmaskChanges program signal blocking state, e.g.: sigset_t oldmask; sigprocmask(SIG_BLOCK, &kSigsetFull, &oldmask); sigprocmask(SIG_SETMASK, &oldmask, NULL);
@param
@return
@asyncsignalsafe
@vforksafe
sigsuspendBlocks until SIG ∉ MASK is delivered to process.
@param
@return
@asyncsignalsafe
sinReturns sine of 𝑥.
@param
@return
@domain
-(3π/8) < 𝑥 < 3π/8 for best accuracy
@see libc/tinymath/sin.S
sincosReturns sine and cosine of 𝑥.
@param
@return
@domain
-(3π/8) < 𝑥 < 3π/8 for best accuracy
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
sinfReturns sine of 𝑥.
@param
@return
@domain
-(3π/8) < 𝑥 < 3π/8 for best accuracy
@see libc/tinymath/sinf.S
sinlReturns sine of 𝑥.
@param
@return
@domain
-(3π/8) < 𝑥 < 3π/8 for best accuracy
@see libc/tinymath/sinl.S
sleb128Encodes sleb-128 signed integer.
@param
@return
@see libc/fmt/sleb128.c
sleepSleeps for a particular amount of time.
@param
@return
@asyncsignalsafe
@see libc/calls/sleep.c
slowcallApplies no-clobber guarantee to System Five function call.
@param
@return
@see
libc/shadowargs.hook.c for intended use case
snprintfFormats string to buffer.
@param
@return
@see
palandprintf() and printf() for detailed documentation
@asyncsignalsafe
@vforksafe
@see libc/fmt/snprintf.c
socketconnectOpens socket client connection.
@param
@return
sorthoststxtSorts entries in HOSTS.TXT table. This function enables resolvehoststxt() to be called so hard-coded hostname lookups take logarithmic time; you can blackhole all the spam you want, in your /etc/hosts file. The sorted order, defined by dnsnamecmp(), also makes it possible to efficiently search for subdomains, once the initial sort is done.
@param
@return
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
palandprintf() 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.
@see
__start_fatal_ndebug()
__start_fatal_ndebugPrints initial part of fatal message.
@return
@note
this is support code for __check_fail(), __assert_fail(), etc.
@see
__start_fatal()
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.
@asyncsignalsafe
@see libc/calls/stat.c
__stat2linuxTranscodes “The Dismal Data Structure” from BSD→Linux ABI.
@param
@return
@asyncsignalsafe
stpcpyCopies bytes from 𝑠 to 𝑑 until a NUL is encountered.
@param
@return
@note
𝑑 and 𝑠 can't overlap
@asyncsignalsafe
@see libc/str/stpcpy.c
stpncpyPrepares static search buffer.
@param
@return
@see
stncpy(), memccpy()
@asyncsignalsafe
@see libc/str/stpncpy.c
strcasecmpCompares NUL-terminated strings 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
strchrReturns pointer to first instance of character.
@param
@return
@asyncsignalsafe
@see libc/str/strchr.c
strchr16Returns pointer to first instance of character.
@param
@return
@note
this won't return NULL if search character is NUL
@asyncsignalsafe
strchrnulReturns pointer to first instance of character.
@param
@return
@see libc/str/strchrnul.c
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
strcpyCopies bytes from 𝑠 to 𝑑 until a NUL is encountered.
@param
@return
@note
𝑑 and 𝑠 can't overlap
@asyncsignalsafe
@see libc/str/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.
@param
@return
@see
strspn(), strtok_r()
@asyncsignalsafe
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
strcspn_pureReturns 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
strdupAllocates new copy of string.
@param
@return
@error
ENOMEM
@see libc/mem/strdup.c
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
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 libc/time/strftime.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
@clob
ax,dx,cx,xmm3,xmm4
@note
h/t agner fog
@asyncsignalsafe
strlen16Returns length of NUL-terminated char16_t string.
@param
@return
@asyncsignalsafe
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
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.
@param
@return
@see
stpncpy(), memccpy()
@asyncsignalsafe
@see libc/str/strncpy.c
strndupAllocates new copy of string, with byte limit.
@param
@return
@error
ENOMEM
@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 memory, with limit.
@param
@return
@asyncsignalsafe
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 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 bytes.
@param
@return
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
strsakSwiss army knife of string character scanning. Used to be fourteen fast functions in one.
@param
@return
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 name associated with signal code.
@param
@return
@see
sigaction()
@see libc/str/strsignal.c
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
strstrSearches for substring.
@param
@return
@asyncsignalsafe
@see
memmem()
@see libc/str/strstr.c
strstr16Searches for substring.
@param
@return
@asyncsignalsafe
@see
memmem()
@see libc/str/strstr16.c
strtoimaxDecodes 128-bit signed integer 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
strtolConverts string to number.
@param
@return
@see libc/fmt/strtol.c
strtonumConverts string to integer, the BSD way.
@param
@return
@see libc/fmt/strtonum.c
strtoul
@param
@return
@see libc/fmt/strtoul.c
strtoull
@param
@return
@see libc/fmt/strtoull.c
strtoumaxDecodes 128-bit unsigned integer from ASCII string. This is a more restricted form of strtoimax() that's useful for folks needing to decode numbers in the range [1^127, 1^128).
@param
@return
@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
__subvdi3Returns 𝑥-𝑦, aborting on overflow.
@param
@return
@see
-ftrapv
__subvsi3Returns 𝑥-𝑦, aborting on overflow.
@param
@return
@see
-ftrapv
__subvti3Returns 𝑥-𝑦, aborting on overflow.
@param
@return
@see
-ftrapv
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
@note
Windows NT only lets admins do this
@asyncsignalsafe
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_abort_nt
@noreturn
sys_dup_ntImplements dup(), dup2(), and dup3() for Windows NT.
@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_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
sys_mmap_metal
@param
@return
sys_mmap_nt
@param
@return
sys_open_nt
@param
@return
@see libc/calls/open-nt.c
sys_read_nt
@param
@return
@see libc/calls/read-nt.c
sys_sync_ntFlushes all open file handles and, if possible, all disk drives.
@return
@see libc/calls/sync-nt.c
sys_wait4_nt
@param
@return
sys_write_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
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
sysinfoReturns amount of system ram, cores, etc.
@param
@return
@error
ENOSYS, EFAULT
@see libc/calls/sysinfo.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
tanReturns tangent of 𝑥.
@param
@return
@domain
-(3π/8) < 𝑥 < 3π/8 for best accuracy
@see libc/tinymath/tan.S
tanfReturns tangent of 𝑥.
@param
@return
@domain
-(3π/8) < 𝑥 < 3π/8 for best accuracy
@see libc/tinymath/tanf.S
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
tcgetattrObtains the termios struct.
@param
@return
@asyncsignalsafe
tcsetattrSets struct on teletypewriter w/ drains and flushes.
@param
@return
@asyncsignalsafe
tcsetpgrpPuts process group in control of terminal.
@param
@return
@asyncsignalsafe
__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
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
TimeSpecToFileTimeConverts UNIX nanosecond timestamp to Windows COBOL timestamp.
@param
@return
timingsafe_memcmpLexicographically compares the first len bytes in b1 and b2. 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 afterw finding the first differing byte.
@param
@return
@note
each byte is interpreted as unsigned char
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
tinystrlen8-bit strlen that's tiny and near optimal if data's tiny.
@param
@return
@see
libc/nexgen32e/strsak.S
tinystrlen1616-bit strlen that's tiny and near optimal if data's tiny.
@param
@return
@see
libc/nexgen32e/strsak16.S
tinystrncmpCompares strings w/ limit & no-clobber greg abi.
@param
@return
@clob
flags only
@asyncsignalsafe
tinystrnlen8-bit strnlen that's tiny and near optimal if data's tiny.
@param
@return
@see
libc/nexgen32e/strsak.S
tinystrnlen1616-bit strnlen that's tiny and near optimal if data's tiny.
@param
@return
@see
libc/nexgen32e/strsak16.S
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
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/str/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.
@param
@return
tprecode8to16Transcodes UTF-8 to UTF-16.
@param
@return
triplfHoses interrupt descriptor table and triple-faults the system.
@return
@see
youtu.be/GIKfEAF2Yhw?t=67
@mode
long,legacy,real
truncRounds to integer, toward zero.
@param
@return
@define
trunc(𝑥+copysign(.5,𝑥))
@see
round(),rint(),nearbyint()
@see
roundsd $_MM_FROUND_TO_ZERO|_MM_FROUND_NO_EXC,%xmm0,%xmm0
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
tzcntFinds lowest set bit in 𝑥. 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
tzcntlFinds lowest set bit in 𝑥. 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
tzcntllFinds lowest set bit in 𝑥. 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
__udivmodti4Performs 128-bit unsigned division and remainder.
@param
@return
uint128toarray_radix10Converts unsigned 128-bit integer to string.
@param
@return
uint64toarray_radix10Converts unsigned 64-bit integer to string.
@param
@return
uint64toarray_radix8Converts unsigned 64-bit integer to octal string.
@param
@return
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
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
ungrayDecodes gray code.
@param
@return
@see
https://en.wikipedia.org/wiki/Gray_code
@see
gray()
@see libc/bits/ungray.c
unhilbertDecodes Hilbert space-filling curve.
@param
@return
@see
https://en.wikipedia.org/wiki/Hilbert_curve
@see
hilbert()
@see libc/bits/hilbert.c
unlinkDeletes file. Please note the deletion process has different interesting properties on each platform. For example, on System V, if open descriptors exist then only the name of the file is removed and it's actually deleted later on when appropriate.
@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.
@param
@return
unmortonDeinterleaves bits.
@param
@return
@see
en.wikipedia.org/wiki/Z-order_curve
@see
morton()
@see libc/bits/unmorton.c
unrijndaelinitComputes key schedule for unrijndael().
@param
@return
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
usleepSleeps for particular amount of microseconds.
@param
@return
@see libc/time/usleep.c
utimeChanges last accessed/modified times on file.
@param
@return
@asyncsignalsafe
@see libc/calls/utime.c
utimensatSets atime/mtime on file, the modern way.
@param
@return
@note
no xnu/rhel5 support if dirfd≠AT_FDCWD∨flags≠0
@asyncsignalsafe
utimesChanges last accessed/modified times on file.
@param
@return
@asyncsignalsafe
@see
stat()
@see libc/calls/utimes.c
vallocEquivalent to memalign(4096, n).
@param
@return
@see
dlvalloc()
@see libc/mem/valloc.S
vasprintfFormats string w/ dynamic memory allocation.
@param
@return
@see
xasprintf() for a better API
@see libc/mem/vasprintf.c
vclsClears display page.
@param
@return
@mode
long,legacy,real
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
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:
LOGF("connecting to foo"); connect(...) LOGF("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
@see libc/log/vflogf.c
vflogf_onfailTakes corrective action if logging is on the fritz.
@param
@return
@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
vfscanfStream decoder.
@param
@return
@see
libc/fmt/vcscanf.h
@see libc/stdio/vfscanf.c
vmspliceTransfers memory to pipe.
@param
@return
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
palandprintf() 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
palandprintf() 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
waitWaits for status to change on any child process.
@param
@return
@asyncsignalsafe
@vforksafe
@see libc/calls/wait.c
wait3Waits for status to change on any child process.
@param
@return
@asyncsignalsafe
@see libc/calls/wait3.c
wait4Waits for status to change on process.
@param
@return
@asyncsignalsafe
@see libc/calls/wait4.c
waitpidWaits for status to change on process.
@param
@return
@asyncsignalsafe
@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
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
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
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
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
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
wcswidthReturns monospace display width of wide character string.
@param
@return
weakfreeThunks free() if it's linked, otherwise do nothing.
@return
@see
free_s() which can ignore static/stack and clear refs
__winerrReturn path for failed Win32 API calls.
@return
@note
this is a code-size saving device
wmemchrReturns pointer to first instance of character in range.
@param
@return
@asyncsignalsafe
wmemrchrSearches for last instance of wchar_t in memory region.
@param
@return
@note
AVX2 requires Haswell (2014+) or Excavator (2015+)
writeWrites data to file descriptor.
@param
@return
@see
read(), pwrite(), writev(), SIGPIPE
@asyncsignalsafe
@see libc/calls/write.c
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
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
xgetlineReads line from stream.
@param
@return
@see
getline() for a more difficult api
@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
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
xreallocRelocates, extends, and/or shrinks memory──or die. This API is fabulous since it categorically eliminates an extremely common type of memory bug, by simply redefining it as a crash.
@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
@see libc/x/xsigaction.c
xslurpReads entire file into memory.
@param
@return
@note
this is uninterruptible
@see libc/x/xslurp.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
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
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
zipfindcentraldirLocates End Of Central Directory record in ZIP file. We search backwards for the End Of Central Directory Record magnum. The ZIP spec says this can be anywhere in the last 64kb. We go all the way since .com.dbg binaries will have lots of DWARF stuff after the embedded .com binary. As such, we sanity check the other fields too to make sure the record seems legit and it's not just a random occurrence of the magnum.
@param
@return
__zipos_closeCloses compressed object.
@param
@return
@see libc/zipos/close.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
@see libc/zipos/get.c
__zipos_openLoads compressed file from αcτµαlly pδrταblε εxεcµταblε object store.
@param
@return
@note
don't call open() from signal handlers
@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
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
|