honeybadger

cosmopolitan libc

your build-once run-anywhere c library

objects

kCpuids
__log_file
optarg
opterr
optind
optopt
optreset
stderr
stdin
stdout
tzname
z_errmsg

functions

a64l
abort
abs
accept
access
acos
acosf
acosh
acoshf
acoshl
acosl
AddressBirthAction
AddressDeathAction
__addvdi3
__addvsi3
__addvti3
adler32
adler32_combine
adler32_z
alarm
arch_prctl
AreMemoryIntervalsOk
asctime
asctime_r
asin
asinf
asinh
asinhf
asinhl
asinl
asprintf
__assert_fail
atan
atan2
atan2f
atan2l
atanf
atanh
atanhf
atanhl
atanl
atexit
atfork
atof
atoi
atol
atoll
atomic_load
atomic_store
attachdebugger
balloc
basename
basename_n
bcmp
bcopy
bfree
bing
bingblit
bitreverse16
bitreverse32
bitreverse64
bitreverse8
brk
bsearch
bsearch_r
bsf
bsfl
bsfll
bsr
bsrl
bsrll
bsrmax
bswap_64
bulk_free
bzero
c2rangr
callexitontermination
calloc
cancolor
carsort100
carsort1000
cbrt
__cbrt
cbrtf
cbrtl
ceil
ceilf
ceill
cescapec
chdir
__check_fail
___check_fail_ndebug
CheckElfAddress
chmod
chomp
chomp16
chown
clearenv
clearerr
clock
clock_gettime
close_s
closedir
CloseSymbolTable
cmpsb
cmpsl
cmpsq
cmpsw
cmpub
cmpul
cmpuq
cmpuw
cmpxchg
commandv
commandvenv
compress
compress2
compressBound
_construct
convertmicros
ConvertTicksToNanos
copy_file_range
copy_with_crc
copyfd
copyfile
copysign
copysignf
copysignl
cos
cosf
cosh
coshf
coshl
cosl
cosmo
cprojl
crc32
crc32_combine
crc32_pclmul
crc32_z
crc32c
crc32c_pure
crc32c_sse42
crc32init
crc_finalize
crc_reset
creat
critbit0_allprefixed
critbit0_clear
critbit0_contains
critbit0_delete
critbit0_emplace
critbit0_get
critbit0_insert
ctime
ctime_r
__cxa_atexit
__cxa_finalize
_d2ld2
__defer
deflate
deflateBound
deflateCopy
deflateEnd
deflateGetDictionary
deflateInit
deflateInit2
deflateParams
deflatePending
deflatePrime
deflateReset
deflateSetDictionary
deflateSetHeader
deflateTune
describeos
deserializednsheader
devrand
__die
difftime
dirfd
dirname
div
div1000000000int64
div1000000int64
div10000int64
div1000int64
div100int64
div10int64
__divmodti4
__divti3
djbsort
djbsort_avx2
dl_iterate_phdr
dlcalloc
dlclose
dlerror
dlfree
dlindependent_calloc
dlindependent_comalloc
dlmalloc
dlmalloc_dispose_chunk
dlmalloc_init
dlmalloc_stats
dlmalloc_sys_trim
dlmalloc_trim
dlmalloc_try_realloc_chunk
dlmalloc_usable_size
dlmemalign
dlopen
dlposix_memalign
dlpvalloc
dlrealloc
dlrealloc_in_place
dlsym
dlvalloc
dnsnamecmp
do_check_free_chunk
do_check_inuse_chunk
do_check_malloc_state
do_check_malloced_chunk
do_check_mmapped_chunk
do_check_top_chunk
__dos2errno
DosDateTimeToUnix
dprintf
drem
dsleep
dtime
dtoa
dup
dup2
dup3
eai2str
ecvt
endgrent
endpwent
endswith
endswith16
erf
erfc
err
errno
__errno_location
errx
escapedos
execl
execle
execlp
execv
execve
execvp
execvpe
exit
_exit
exp
exp10
exp10f
exp10l
exp2
exp2f
exp2l
expf
expl
explicit_bzero
expm1
expm1f
expm1l
_f2ld2
fabs
fabsf
fabsl
faccessat
fadvise
favail
__fbufsize
fchdir
fchmod
fchown
fchownat
fclose
fclose_s
fcntl
fcvt
fdatasync
fdopen
fdopendir
__fentry__
feof
ferror
fflush
ffs
ffsl
ffsll
fgetc
fgetpos
fgets
fgetwc
fgetws
filecmp
fileexists
fileno
filetimetotime
FileTimeToTimeSpec
FileTimeToTimeVal
FindComBinary
FindDebugBinary
FindMemoryInterval
__fixupnewfd
__flbf
flock
flockfile
flogf
floor
floorf
floorl
_flushlbf
fmax
fmaxf
fmaxl
fmemopen
fmin
fminf
fminl
fmod
fmodl
fnmatch
fopen
fopenflags
fork
__fpending
fprintf
__fpurge
fputc
fputcfb
fputs
fputwc
fputws
fread
__freadable
__freading
free
free_s
freeaddrinfo
freedtoa
freehoststxt
freeresolvconf
freopen
fscanf
fseek
__fsetlocking
fsetpos
fstat
fstatat
fsync
ftell
ftoa
ftrace
ftrace_init
ftruncate
ftrylockfile
funlockfile
futimens
futimes
futimesat
__fwritable
fwrite
__fwriting
g_ddfmt
g_ddfmt_p
g_dfmt
g_dfmt_p
g_ffmt
g_ffmt_p
g_xfmt
g_xfmt_p
__gc
gclongjmp
gdbexec
gdtoa
get_current_dir_name
__get_virtual
GetAddr2linePath
getaddrinfo
getauxval
getcachesize
getchar
getcwd
getdelim
getdomainname
GetDosArgv
GetDosEnviron
GetElfSectionAddress
GetElfSectionHeaderAddress
GetElfSectionName
GetElfSectionNameStringTable
GetElfSegmentHeaderAddress
GetElfString
GetElfStringTable
GetElfSymbolTable
GetElfVirtualAddressRange
getentropy
getenv
getfiledescriptorsize
GetFileSize
GetGdbPath
getgid
getgrent
getgrgid
getgrgid_r
getgrnam
getgrnam_r
getgrouplist
gethostname
gethostname_bsd
gethostname_linux
gethostname_nt
gethoststxt
getitimer
getline
getntnameservers
__getntsyspath
getopt
getpid
getppid
getpriority
GetProcAddressModule
getpwent
getpwnam
getpwnam_r
getpwuid
getpwuid_r
getrandom
getresolvconf
getrlimit
getrusage
gets
getsid
GetSymbolTable
GetTempPathA_flunk
gettid
gettimeofday
getttycols
getttysize
getuid
getutf16
getwchar
getx86processormodel
glob
globfree
gmtime
gmtime_r
grantpt
gray
__grow
gzbuffer
gzclearerr
gzclose
gzclose_r
gzdirect
gzdopen
gzeof
gzerror
gzflush
gzfread
gzfwrite
gzgetc
gzgets
gzoffset
gzopen
gzprintf
gzputc
gzputs
gzread
gzrewind
gzseek
gzsetparams
gztell
gzungetc
gzwrite
hamming
hextoint
HighwayHash64
hilbert
__hook
hypot
hypotf
hypotl
iconv
iconv_close
iconv_open
identity
ilogb
ilogbf
ilogbl
imapxlatab
imaxabs
index
IndexDoubleNulString
inet_addr
inet_aton
inet_ntoa
inet_ntop
inflate
inflate_fast
inflate_table
inflateBack
inflateBackEnd
inflateBackInit
inflateCopy
inflateEnd
inflateGetDictionary
inflateGetHeader
inflateInit
inflateInit2
inflateMark
inflatePrime
inflateReset
inflateReset2
inflateSetDictionary
inflateSync
_init
__init_bss_start
__init_rodata_start
_init_systemfive_jmptab
insertionsort
int128toarray_radix10
int64toarray
int64toarray_radix10
interruptiblecall
ioctl
ioctl_tcgets
ioctl_tcgets_nt
ioctl_tcsets
ioctl_tcsets_nt
ioctl_tiocgwinsz
ioctl_tiocgwinsz_nt
ioctl_tiocswinsz
ioctl_tiocswinsz_nt
isabspath
isalnum
isalpha
isascii
isatty
isblank
ischardev
iscntrl
IsDebuggerPresent
isdigit
isdirectory
IsElf64Binary
IsElfSymbolContent
isexecutable
isgraph
isheap
islower
isprint
ispunct
isregularfile
IsRunningUnderMake
issetugid
isspace
IsTerminalInarticulate
isupper
iswalnum
iswalpha
iswblank
iswcntrl
iswctype
iswdigit
iswgraph
iswlower
iswprint
iswpunct
iswspace
iswupper
iswxdigit
isxdigit
itoa
_jmpstack
kCp437
kill
killpg
kNtSystemDirectory
kNtWindowsDirectory
kStartTsc
kTmpPath
kToLower
l64a
labs
lchown
ldexp
ldexpf
ldexpl
ldiv
lgamma
lgamma_r
link
llabs
lldiv
llog10
llround
llroundf
loadxmm
localeconv
localtime
localtime_r
lockcmpxchg
lockxchg
log
log10
log10f
log10l
log1p
log1pf
log1pl
log2
log2f
log2l
logb
logbf
logbl
logf
logl
_longjmp
longjmp
lround
lroundf
lseek
lstat
lz4check
lz4cpy
lz4decode
lzcnt
lzcntl
lzcntll
madvise
makedirs
mallinfo
malloc
malloc_footprint
malloc_footprint_limit
malloc_inspect_all
malloc_max_footprint
malloc_set_footprint_limit
malloc_stats
malloc_trim
malloc_usable_size
mallopt
__map_phdrs
mapanon
MarsagliaXorshift32
MarsagliaXorshift64
mbrtowc
mbsrtowcs
mbstowcs
mbtowc
memalign
memccpy
memchr
memchr16
memcmp
memcpy
MemCpy
memeqmask
memfrob
meminfo
memjmpinit
memmem
memmove
memmove_pure
mempcpy
memrchr
memrchr16
memset
MemSet
memset16
memset_pure
memsummary
MetalPrintf
mkdir
mkdirat
mkfifo
mknod
mkntcmdline
mkntenvblock
__mkntpath2
mkostemp
mkostemps
mkostempsm
mkostempsmi
mkstemp
mkstemps
mktemp
mktime
mmap
morton
mprotect
mpsadbw
__mpsadbws
mremap
msync
__mulvdi3
__mulvsi3
__mulvti3
munmap
nanosleep
__negvdi2
__negvsi2
__negvti2
__new_page
newaddrinfo
nextafter
nextafterf
nextafterl
nice
nowl
nowl_art
nowl_sys
__nt2sysv
ntaccesscheck
ntcontext2linux
NtGetVersion
ntoa
ntoa2
ntreturn
ntsetprivilege
ntspawn
offset2overlap
__on_arithmetic_overflow
__oncrash
__onfork
open
openanon
openat
opendir
openpty
OpenSymbolTable
pabsb
pabsd
pabsw
packssdw
packsswb
packusdw
packuswb
paddb
paddd
paddq
paddsb
paddsw
paddusb
paddusw
paddw
palandprintf
palignr
__palignrs
pand
pandn
parsehoststxt
parseport
parseresolvconf
pascalifydnsname
pause
pavgb
pavgw
pclose
pcmpeqb
pcmpeqd
pcmpeqw
pcmpgtb
pcmpgtd
pcmpgtw
pdep
perror
pext
phaddd
phaddsw
phaddw
phsubd
phsubsw
phsubw
pipe
pipe2
pmaddubsw
pmaddwd
pmaxsw
pmaxub
pminsw
pminub
pmovmskb
pmulhrsw
pmulhuw
pmulhw
pmulld
pmullw
pmuludq
pochisq
popcnt
popen
por
posix2time
posix_fadvise
posix_madvise
posix_memalign
posix_openpt
pow
pow10
pow10f
pow10l
__pow_finite
powf
__powf_finite
powi
powif
powil
pread
preadv
__print
PrintBacktraceUsingSymbols
printf
PrintMemoryIntervals
__prot2nt
psadbw
pshufb
pshufd
pshufhw
pshuflw
pshufw
psignb
psignd
psignw
pslld
pslldq
pslldv
psllq
psllqv
psllw
psllwv
psrad
psradv
psraw
psrawv
psrld
psrldq
psrldv
psrlq
psrlqv
psrlw
psrlwv
psubb
psubd
psubq
psubsb
psubsw
psubusb
psubusw
psubw
pthread_cancel
pthread_mutex_lock
pthread_mutex_trylock
pthread_mutex_unlock
pthread_once
ptrace
ptsname
ptsname_r
punpckhbw
punpckhdq
punpckhqdq
punpckhwd
punpcklbw
punpckldq
punpcklqdq
punpcklwd
putchar
putenv
PutEnvImpl
puts
pututf16
putwc
putwchar
pvalloc
pwrite
pwritev
pxor
qsort
qsort_r
raise
rand
rand32
rand64
randf
rawmemchr
rawmemchr16
rawwmemchr
rdrand
rdseed
read
readansi
readdir
realloc
realloc_in_place
reallocarray
realpath
recv
regcomp
regerror
regexec
regfree
ReleaseMemoryIntervals
ReleaseMemoryNt
rem1000000000int64
rem1000000int64
rem10000int64
rem1000int64
rem100int64
rem10int64
remainder
remove
rename
renameat
replacestr
replaceuser
__reservefd
resolvedns
resolvehoststxt
rewind
rijndaelinit
rindex
rint
rintl
rldecode
rmdir
rmrf
rngset
round
RoundDecimalPlaces
rounddown2pow
roundf
roundl
roundup2log
roundup2pow
rt_add
rt_end
rt_init
savexmm
sbrk
scalb
scalbf
scalbl
scalbln
scalblnf
scalblnl
scalbn
scalbnf
scalbnl
scanf
sched_setaffinity
sched_yield
send
serializednsheader
serializednsquestion
setbuf
setbuffer
setegid
setenv
seteuid
setgrent
setitimer
_setjmp
setjmp
setlocale
setpriority
setpwent
setresgid
setresuid
setrlimit
setsid
_setstack
setvbuf
ShowBacktrace
showcrashreports
shufpd
shufps
sigaction
sigaddset
sigdelset
sigemptyset
sigfillset
sigignore
sigismember
signal
sigprocmask
sigsuspend
sin
sincos
sincosf
sincosl
sinf
sinh
sinhf
sinhl
sinl
sleb128
sleep
slowcall
snprintf
socketconnect
sorthoststxt
spacepad
splice
sprintf
sqrt
sqrtf
sqrtl
srand
sscanf
__stack_chk_fail
__start_fatal
__start_fatal_ndebug
startswith
startswith16
stat
__stat2linux
stpcpy
stpncpy
strcasecmp
strcasecmp16
strcasecmp16to8
strcasecmp8to16
strcat
strcat16
strchr
strchr16
strchrnul
strchrnul16
strclen
strclen16
strcmp
strcmp16
strcmp16to8
strcmp8to16
strcoll
strcpy
strcpy16
strcspn
strcspn16
strcspn_pure
strdup
strerror
strerror_r
strfry
strftime
strlcat
strlcpy
strlen
strlen16
strlen_pure
strncasecmp
strncasecmp16
strncasecmp16to8
strncasecmp8to16
strncat
strnclen
strnclen16
strncmp
strncmp16
strncmp16to8
strncmp8to16
strncpy
strndup
strnlen
strnlen16
strnlen16_s
strnlen_s
strntolower
strntoupper
strnwidth
strnwidth16
strpbrk
strpbrk16
strptime
strrchr
strrchr16
strsak
strsak16
strsep
strsignal
strspn
strspn16
strstr
strstr16
strtod
strtodg
strtodI
strtof
strtoId
strtoIdd
strtoIf
strtoimax
strtoIx
strtok
strtok_r
strtol
strtold
strtoll
strtolower
strtonum
strtopd
strtopdd
strtopf
strtopx
strtord
strtordd
strtorf
strtorx
strtoul
strtoull
strtoumax
strtoupper
strverscmp
strwidth
strwidth16
__subvdi3
__subvsi3
__subvti3
symlink
symlinkat
sync
sync_file_range
sys_abort_nt
sys_chdir_nt
sys_close_nt
sys_dup3
sys_dup_nt
sys_execve
sys_execve_nt
sys_faccessat_nt
sys_fadvise_nt
sys_fchdir_nt
sys_fcntl_nt
sys_fdatasync_nt
sys_flock_nt
sys_fork_nt
sys_fstat
sys_fstat_metal
sys_fstat_nt
sys_fstatat
sys_fstatat_nt
sys_ftruncate_nt
sys_getcwd_nt
sys_getcwd_xnu
sys_getppid_nt
sys_getpriority_nt
sys_getrusage_nt
sys_getsetpriority_nt
sys_gettimeofday_nt
sys_isatty_nt
sys_kill_nt
sys_link_nt
sys_lseek_nt
sys_madvise_nt
sys_mkdirat_nt
sys_mmap
sys_mmap_metal
sys_mmap_nt
sys_msync_nt
sys_munmap_metal
sys_nanosleep_nt
sys_open_nt
sys_openat_metal
sys_pipe
sys_pipe2
sys_pipe_nt
sys_read_nt
sys_readv_metal
sys_readv_serial
sys_renameat_nt
sys_sched_yield_nt
sys_setitimer_nt
sys_setpriority_nt
sys_symlinkat_nt
sys_sync_nt
sys_sysinfo_nt
sys_truncate_nt
sys_unlinkat_nt
sys_utimensat
sys_utimensat_nt
sys_utimensat_xnu
sys_utimes_nt
sys_wait4_nt
sys_write_nt
sys_writev_metal
sys_writev_serial
sys_xinet_ntop
syscall
syscon_start
sysconf
sysinfo
system
systemexec
__systemfive
tan
tanf
tanh
tanhf
tanhl
tanl
tarjan
tcgetattr
tcgetpgrp
tcsetattr
tcsetpgrp
telldir
tempnam
__text_windows_start
time
time2posix
timegm
timelocal
timeoff
times
TimeSpecToFileTime
TimeToFileTime
TimeValToFileTime
timingsafe_memcmp
tinydivsi
tinystrlen
tinystrlen16
tinystrncmp
tinystrnlen
tinystrnlen16
tinywcslen
tinywcsnlen
tmpfile
tolower
touch
toupper
towlower
towupper
tpdecode
tpenc
tpencode
tprecode16to8
tprecode8to16
TrackMemoryInterval
triplf
trunc
truncate
truncf
truncl
ttyname
ttyname_r
tzcnt
tzcntl
tzcntll
tzset
__udivmodti4
uint128toarray_radix10
uint64toarray
uint64toarray_fixed16
uint64toarray_radix10
uint64toarray_radix16
uint64toarray_radix8
uname
unbing
unbingbuf
unbingstr
uncompress
uncompress2
undeflate
ungetc
ungray
unhexbuf
unhexstr
unhilbert
unlink
unlink_s
unlinkat
unlockpt
unmorton
unrijndaelinit
unsetenv
unsleb128
UntrackMemoryIntervals
usleep
utime
utimensat
utimes
valloc
vasprintf
vcls
vcscanf
vdprintf
verr
verrx
vflogf
vflogf_onfail
vfork
vfprintf
vfscanf
vmsplice
vprintf
vscanf
vsnprintf
vsprintf
vsscanf
vwarn
vwarnx
wait
wait3
wait4
waitpid
warn
warnx
wchomp
wcscasecmp
wcscat
wcschr
wcschrnul
wcscmp
wcscpy
wcscspn
wcsdup
wcsendswith
wcslen
wcsncasecmp
wcsncmp
wcsncpy
wcsnlen
wcsnlen_s
wcsnwidth
wcspbrk
wcsrchr
wcssak
wcsspn
wcsstartswith
wcsstr
wcstoimax
wcstol
wcswidth
wctob
wctomb
wctype
wcwidth
weakfree
__winerr
WinMainForked
winrandish
wmemchr
wmemcpy
wmemmove
wmempcpy
wmemrchr
wmemset
write
xasprintf
xbarf
xcalloc
xdie
xdirname
xdtoa
xdtoaf
xdtoal
xgetline
xiso8601ts
xiso8601tv
xjoinpaths
xmalloc
xmemalign
xmemalignzero
xrealloc
xsigaction
xslurp
xstrcat
xstrdup
xstrmul
xstrndup
xunbing
xunbinga
xvalloc
xvasprintf
xwrite
zcalloc
zcfree
zError
zipfindcentraldir
__zipos_close
__zipos_fstat
__zipos_get
__zipos_open
__zipos_parseuri
__zipos_read
__zipos_stat
zlibCompileFlags
zlibVersion

a64l

Converts base64 to 32-bit integer.

@param
char* s
@return
long

abort

Terminates 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.

@noreturn
@forcealignargpointer
@asyncsignalsafe

abs

Returns absolute value of x.

@param
int x
@return
int

accept

Creates client socket file descriptor for incoming connection.

@param
int fd
is the server socket file descriptor
void* out_addr
will receive the remote address
unsigned int* inout_addrsize
provides and receives addr's byte length
@return
int
client fd which needs close(), or -1 w/ errno
@asyncsignalsafe

access

Checks if effective user can access path in particular ways.

@param
char* path
is a filename or directory
int mode
can be R_OK, W_OK, X_OK, F_OK
@return
int
0 if ok, or -1 and sets errno
@asyncsignalsafe

acos

Returns arc cosine of 𝑥.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0

acosf

Returns arc cosine of 𝑥.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0

acosh

Returns inverse hyperbolic cosine of 𝑥.

@param
double x
@return
double

acoshf

Returns inverse hyperbolic cosine of 𝑥.

@param
float x
@return
float

acoshl

Returns inverse hyperbolic cosine of 𝑥.

@param
long double x
@return
long double

acosl

Returns arc cosine of 𝑥.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result of computation on FPU stack in %st
@define atan2(abs(sqrt((1-𝑥)*(1+𝑥))),𝑥)
@domain -1 ≤ 𝑥 ≤ 1
@mode long,legacy

AddressBirthAction

@param
void* addr
@return
void*

AddressDeathAction

@param
void* addr
@return
void*

__addvdi3

Returns 𝑥+𝑦, aborting on overflow.

@param
rdi
is int64 𝑥
rsi
is int64 𝑦
@return
rax is 𝑥+𝑦
@see -ftrapv

__addvsi3

Returns 𝑥+𝑦, aborting on overflow.

@param
edi
is int32 𝑥
esi
is int32 𝑦
@return
eax is 𝑥+𝑦
@see -ftrapv

__addvti3

Returns 𝑥+𝑦, aborting on overflow.

@param
rdi:rsi
is int128 𝑥
rdx:rcx
is int128 𝑦
@return
rdx:rax is 𝑥+𝑦
@see -ftrapv

adler32

Updates running Adler-32 checksum with the bytes buf[0..len-1] and return the updated checksum. If buf is Z_NULL, this function returns the required initial value for the checksum.

@return
unsigned long

adler32_combine

Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note that the off_t type (like off_t) is a signed integer. If len2 is negative, the result has no meaning or utility.

@return
unsigned long

adler32_z

Same as adler32(), but with a size_t length.

@return
unsigned long

alarm

Asks for single-shot SIGALRM to be raise()'d after interval.

@param
unsigned int seconds
until we get signal, or 0 to reset previous alarm()
@return
unsigned int
seconds previous alarm() had remaining, or -1u w/ errno
@see setitimer()
@asyncsignalsafe

arch_prctl

Don't bother.

@param
int code
long addr
...
@return
int

AreMemoryIntervalsOk

@param
struct _mmi* mm
@return
_Bool

asctime

Converts date time to string.

@param
ANONYMOUS-STRUCT* date
@return
char*
date time string in statically allocated buffer
@see asctime_r for reentrant version

asctime_r

Converts date time to string.

@param
struct tm* date
char* buf
needs to have 64 bytes
@return
char*
pointer to buf
@see asctime_r for reentrant version

asin

Returns arc sine of 𝑥.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0

asinf

Returns arc sine of 𝑥.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0

asinh

Returns inverse hyperbolic sine of 𝑥.

@param
double x
@return
double

asinhf

Returns inverse hyperbolic sine of 𝑥.

@param
float x
@return
float

asinhl

Returns inverse hyperbolic sine of 𝑥.

@param
long double x
@return
long double

asinl

Returns arc sine of 𝑥.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result of computation on FPU stack in %st
@define atan2(𝑥,sqrt((1-𝑥)*(1+𝑥)))
@domain -1 ≤ 𝑥 ≤ 1
@mode long,legacy

asprintf

Formats string, allocating needed memory.

@param
char** strp
char* fmt
...
@return
int
bytes written (excluding NUL) or -1 w/ errno
@see xasprintf() for a better API

__assert_fail

Handles failure of assert() macro.

@param
char* expr
char* file
int line
@noreturn

atan

Returns arc tangent of 𝑥.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0

atan2

Returns arc tangent of 𝑦/𝑥.

@param
𝑦
is double scalar in low half of %xmm0
𝑥
is double scalar in low half of %xmm1
@return
double scalar in low half of %xmm0
@note the greatest of all libm functions

atan2f

Returns arc tangent of 𝑦/𝑥.

@param
𝑦
is float scalar in low quarter of %xmm0
𝑥
is float scalar in low quarter of %xmm1
@return
float scalar in low quarter of %xmm0

atan2l

Returns arc tangent of 𝑦/𝑥.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
𝑦
is an 80-bit long double passed on stack in 16-bytes
@return
result of computation on FPU stack in %st

atanf

Returns arc tangent of 𝑥.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0

atanh

Returns inverse hyperbolic tangent of 𝑥.

@param
double x
@return
double

atanhf

Returns inverse hyperbolic tangent of 𝑥.

@param
float x
@return
float

atanhl

Returns inverse hyperbolic tangent of 𝑥.

@param
long double x
@return
long double

atanl

Returns arc tangent of 𝑥.

              1  3   1  5   1  7   1  9    1  11
atan(𝑥) = 𝑥 - - 𝑥  + - 𝑥  - - 𝑥  + - 𝑥  - -- 𝑥   ...
              3      5      7      9      11
@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result of computation on FPU stack in %st
@define atan(𝑥) = Σₙ₌₀₋∞ 2²ⁿ(𝑛!)²/(𝟸𝑛+𝟷)!(𝑥²ⁿ⁺¹/(𝑥²+𝟷)ⁿ⁺¹)

atexit

Adds global destructor.

Destructors are called in reverse order. They won't be called if the program aborts or _exit() is called. Invocations of this function are usually generated by the C++ compiler.

@param
void(*)() f
@return
int
0 on success or nonzero if out of space

atfork

Registers function to be called by fork() in child.

@param
void* fn
void* arg
@return
int
0 on success, or -1 w/ errno
@note vfork() won't invoke callbacks
@asyncsignalsafe

atof

Converts string to double.

@param
char* s
@return
double

atoi

Decodes decimal number from ASCII string.

@param
char* s
is a non-null NUL-terminated string
@return
int
the decoded signed saturated number
@note calling strtoimax() directly with base 0 permits greater flexibility in terms of inputs

atol

@param
char* s
@return
long

atoll

@param
char* s
@return
long

atomic_load

Atomically loads value.

This macro is intended to prevent things like compiler load tearing optimizations.

@param
void* p
unsigned long n
@return
long

atomic_store

Atomically stores value.

This macro is intended to prevent things like compiler store tearing optimizations.

@param
void* p
long x
unsigned long n
@return
long

attachdebugger

Launches GDB debugger GUI for current process.

This function abstracts the toilsome details of configuring the best possible UX for debugging your app, for varying levels of available information, on most of the various platforms.

Before calling this function, consider placing showcrashreports() in your main function and calling DebugBreak() wherever you want; it's safer. Also note the "GDB" environment variable can be set to empty string, as a fail-safe for disabling this behavior.

@param
long continuetoaddr
can be a code address, 0, or -1 for auto
@return
int
gdb pid if continuing, 0 if detached, or -1 w/ errno
@note this is called via eponymous spinlock macro wrapper

balloc

Allocates page-guarded buffer.

@param
struct GuardedBuffer* b
is metadata object owned by caller, initialized to zero for first call; subsequent calls will resize
unsigned int a
is alignment requirement in bytes, e.g. 1,2,4,8,16,...
unsigned long n
is buffer size in bytes
@return
void*
b->p
@see ralloc()
@deprecated

basename

Returns 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
char* path
is NUL-terminated UTF-8 path
@return
char*
pointer inside path or path itself

basename_n

Returns 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
char* path
is UTF-8 path
unsigned long size
is byte length of path
@return
char*
pointer inside path or path itself

bcmp

Compares memory.

This API was thought to be nearly extinct until recent versions of Clang (c. 2019) started generating synthetic calls to it.

@param
void* a
void* b
unsigned long n
@return
int
0 if a and b have equal contents, otherwise non-zero
@asyncsignalsafe

bcopy

Copies memory the legacy way.

@param
void* dst
void* src
unsigned long n
@return
void*

bfree

Frees memory return by balloc().

@param
struct GuardedBuffer* b
@return
void
@deprecated

bing

Turns binary octet into unicode glyph representation.

Cosmopolitan displays RADIX-256 numbers using these digits:

 0123456789abcdef
0 ☺☻♥♦♣♠•◘○◙♂♀♪♫☼
1►◄↕‼¶§▬↨↑↓→←∟↔▲▼
2 !"#$%&'()*+,-./
30123456789:;<=>?
4@ABCDEFGHIJKLMNO
5PQRSTUVWXYZ[\]^_
6`abcdefghijklmno
7pqrstuvwxyz{|}~⌂
8ÇüéâäàåçêëèïîìÄÅ
9ÉæÆôöòûùÿÖÜ¢£¥€ƒ
aáíóúñѪº¿⌐¬½¼¡«»
b░▒▓│┤╡╢╖╕╣║╗╝╜╛┐
c└┴┬├─┼╞╟╚╔╩╦╠═╬╧
d╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀
eαßΓπΣσμτΦΘΩδ∞φε∩
f≡±≥≤⌠⌡÷≈°∙·√ⁿ²■λ
IBM designed these glyphs for the PC to map onto the display bytes at (char *)0xb8000. Because IBM authorized buyers of its PCs to inspect and/or modify this region of memory, it became widely understood by many developers as a quick way to visualize arbitrary data that's so superior to hexdump -- a use-case that's lived on longer than the CGA graphics card for which it was designed.
@param
int b
is binary octet to pictorally represent
int intent
controls canonical multimappings: ∅␀ ,\n◙,ε∊∈€, λ,etc.
@return
int
@see unbing() for inverse

bingblit

@param
int ys
int xs
UNKNOWN M
int yn
int xn
@return
short*

bitreverse16

Reverses bits in 16-bit word.

@param
unsigned short x
@return
unsigned short

bitreverse32

Reverses bits in 32-bit word.

@param
unsigned int x
@return
unsigned int

bitreverse64

Reverses bits in 64-bit word.

@param
unsigned long x
@return
unsigned long

bitreverse8

Reverses bits in 8-bit word.

@param
unsigned char x
@return
unsigned char

brk

Sets 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
void* end
@return
int
0 on success or -1 w/ errno
@see mmap(), sbrk(), _end

bsearch

Searches sorted array for exact item in logarithmic time.

@param
void* key
void* base
unsigned long nmemb
unsigned long size
int(*)() cmp
@return
void*
@see bsearch_r(), bisectcarleft()

bsearch_r

Searches sorted array for exact item in logarithmic time.

@param
void* key
void* base
unsigned long nmemb
unsigned long size
int(*)() cmp
void* arg
@return
void*
@see bsearch(), bisectcarleft()

bsf

Returns position of first bit set.

                      ctz(𝑥)         31^clz(𝑥)   clz(𝑥)
  uint32 𝑥   bsf(𝑥) tzcnt(𝑥)   ffs(𝑥)   bsr(𝑥) lzcnt(𝑥)
0x00000000      wut       32        0      wut       32
0x00000001        0        0        1        0       31
0x80000001        0        0        1       31        0
0x80000000       31       31       32       31        0
0x00000010        4        4        5        4       27
0x08000010        4        4        5       27        4
0x08000000       27       27       28       27        4
0xffffffff        0        0        1       31        0
@param
int x
is a 32-bit integer
@return
int
number in range 0..31 or undefined if 𝑥 is 0

bsfl

Returns position of first bit set.

                      ctz(𝑥)         31^clz(𝑥)   clz(𝑥)
  uint32 𝑥   bsf(𝑥) tzcnt(𝑥)   ffs(𝑥)   bsr(𝑥) lzcnt(𝑥)
0x00000000      wut       32        0      wut       32
0x00000001        0        0        1        0       31
0x80000001        0        0        1       31        0
0x80000000       31       31       32       31        0
0x00000010        4        4        5        4       27
0x08000010        4        4        5       27        4
0x08000000       27       27       28       27        4
0xffffffff        0        0        1       31        0
@param
long x
@return
int
number in range 0..63 or undefined if 𝑥 is 0

bsfll

Returns position of first bit set.

                      ctz(𝑥)         31^clz(𝑥)   clz(𝑥)
  uint32 𝑥   bsf(𝑥) tzcnt(𝑥)   ffs(𝑥)   bsr(𝑥) lzcnt(𝑥)
0x00000000      wut       32        0      wut       32
0x00000001        0        0        1        0       31
0x80000001        0        0        1       31        0
0x80000000       31       31       32       31        0
0x00000010        4        4        5        4       27
0x08000010        4        4        5       27        4
0x08000000       27       27       28       27        4
0xffffffff        0        0        1       31        0
@param
long x
@return
int
number in range 0..63 or undefined if 𝑥 is 0

bsr

Returns binary logarithm of 𝑥.

                      ctz(𝑥)         31^clz(𝑥)   clz(𝑥)
  uint32 𝑥   bsf(𝑥) tzcnt(𝑥)   ffs(𝑥)   bsr(𝑥) lzcnt(𝑥)
0x00000000      wut       32        0      wut       32
0x00000001        0        0        1        0       31
0x80000001        0        0        1       31        0
0x80000000       31       31       32       31        0
0x00000010        4        4        5        4       27
0x08000010        4        4        5       27        4
0x08000000       27       27       28       27        4
0xffffffff        0        0        1       31        0
@param
int x
is a 32-bit integer
@return
int
number in range 0..31 or undefined if 𝑥 is 0

bsrl

Returns binary logarithm of 𝑥.

                      ctz(𝑥)         31^clz(𝑥)   clz(𝑥)
  uint32 𝑥   bsf(𝑥) tzcnt(𝑥)   ffs(𝑥)   bsr(𝑥) lzcnt(𝑥)
0x00000000      wut       32        0      wut       32
0x00000001        0        0        1        0       31
0x80000001        0        0        1       31        0
0x80000000       31       31       32       31        0
0x00000010        4        4        5        4       27
0x08000010        4        4        5       27        4
0x08000000       27       27       28       27        4
0xffffffff        0        0        1       31        0
@param
long x
is a 64-bit integer
@return
int
number in range 0..63 or undefined if 𝑥 is 0

bsrll

Returns binary logarithm of 𝑥.

                      ctz(𝑥)         31^clz(𝑥)   clz(𝑥)
  uint32 𝑥   bsf(𝑥) tzcnt(𝑥)   ffs(𝑥)   bsr(𝑥) lzcnt(𝑥)
0x00000000      wut       32        0      wut       32
0x00000001        0        0        1        0       31
0x80000001        0        0        1       31        0
0x80000000       31       31       32       31        0
0x00000010        4        4        5        4       27
0x08000010        4        4        5       27        4
0x08000000       27       27       28       27        4
0xffffffff        0        0        1       31        0
@param
long x
is a 64-bit integer
@return
int
number in range 0..63 or undefined if 𝑥 is 0

bsrmax

Returns binary logarithm of integer 𝑥.

  uint32 𝑥   bsf(𝑥) tzcnt(𝑥)   ffs(𝑥)   bsr(𝑥) lzcnt(𝑥)
0x00000000      wut       32        0      wut       32
0x00000001        0        0        1        0       31
0x80000001        0        0        1       31        0
0x80000000       31       31       32       31        0
0x00000010        4        4        5        4       27
0x08000010        4        4        5       27        4
0x08000000       27       27       28       27        4
0xffffffff        0        0        1       31        0
@param
rsi:rdi
is 128-bit unsigned 𝑥 value
@return
eax number in range [0,128) or undef if 𝑥 is 0
@see also treasure trove of nearly identical functions

bswap_64

Byte-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_free

Frees 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
void** array
unsigned long nelem
@return
unsigned long

bzero

Sets 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
rdi
is dest
rsi
is the number of bytes to set
@return
@see memset(), explicit_bzero()

c2rangr

Computes transcedental trigonometry op w/ reactive scaling.

@param
%rdx
points to op function
everything
else delegates
@return
@clob %ax
@see sin,cos,tan

callexitontermination

Installs default handlers for friendly kill signals.

@param
struct kSigsetEmpty* opt_out_exitsigs
@return
void
@see showcrashreports()

calloc

Allocates n * itemsize bytes, initialized to zero.

@param
rdi
is number of items (n)
rsi
is size of each item (itemsize)
@return
rax is memory address, or NULL w/ errno
@note overreliance on memalign is a sure way to fragment space
@see dlcalloc()

cancolor

Returns 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.txt
Ideally, 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
_Bool

carsort100

Sorts int32 key-value arrays of trivial size.

@param
unsigned long n
UNKNOWN a
@return
void
@see test/libc/alg/carsort_test.c
@see carsort1000() if larger

carsort1000

Sorts int32 key-value arrays of nontrivial size.

@param
unsigned long n
UNKNOWN A
@return
void
@see test/libc/alg/carsort_test.c
@see carsort100() if smaller

cbrt

Returns cube root of 𝑥.

@param
%xmm0
holds binary64 number
@return
%xmm0 holds binary64 result

__cbrt

Returns cube root of 𝑥.

@param
double x
@return
double

cbrtf

Returns cube root of 𝑥.

@param
%xmm0
holds binary32 number
@return
%xmm0 holds binary32 result

cbrtl

Returns cube root of 𝑥.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result of computation on FPU stack in %st

ceil

Returns smallest integral not less than 𝑥.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0
@see round(),rint(),nearbyint()
@see vroundsd $_MM_FROUND_TO_POS_INF|_MM_FROUND_NO_EXC,%xmm0,%xmm0,%xmm0

ceilf

Returns smallest integral not less than 𝑥.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0
@see round(),rint(),nearbyint()
@see vroundss $_MM_FROUND_TO_POS_INF|_MM_FROUND_NO_EXC,%xmm0,%xmm0,%xmm0

ceill

Returns smallest integral not less than 𝑥.

@param
𝑥
is long double passed on stack
@return
long double in %st

cescapec

Escapes 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
dil
contains byte to escape
@return
@see libc/nexgen32e/cescapec.c

chdir

Sets current directory.

@param
char* path
@return
int
@asyncsignalsafe
@see fchdir()

__check_fail

Handles failure of CHECK_xx() macros.

@param
char* suffix
char* opstr
unsigned long want
char* wantstr
unsigned long got
char* gotstr
char* file
int line
char* fmt
...
@return
void

___check_fail_ndebug

Handles 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
unsigned long want
unsigned long got
char* opchar
@return
void
@see libc/log/thunks/__check_fail_ndebug.S

CheckElfAddress

@param
struct Elf64_Ehdr* elf
unsigned long mapsize
long addr
unsigned long addrsize
@return
void

chmod

Changes permissions on file, e.g.:

CHECK_NE(-1, chmod("foo/bar.txt", 0644));
CHECK_NE(-1, chmod("o/default/program.com", 0755));
CHECK_NE(-1, chmod("privatefolder/", 0700));
The esoteric bits generally available on System Five are:

CHECK_NE(-1, chmod("/opt/", 01000));          // sticky bit
CHECK_NE(-1, chmod("/usr/bin/sudo", 04755));  // setuid bit
CHECK_NE(-1, chmod("/usr/bin/wall", 02755));  // setgid bit
This works on Windows NT if you ignore the error ;-)
@param
char* pathname
must exist
unsigned int mode
contains octal flags (base 8)
@return
int
@errors ENOENT, ENOTDIR, ENOSYS
@asyncsignalsafe
@see fchmod()

chomp

Mutates line to remove line-ending characters.

@param
char* line
is NULL-propagating
@return
char*
@see getline

chomp16

Mutates line to remove line-ending characters.

@param
unsigned short* line
is NULL-propagating
@return
unsigned short*
@see getline

chown

Changes owner and/or group of pathname.

@param
char* pathname
unsigned int uid
is user id, or -1u to not change
unsigned int gid
is group id, or -1u to not change
@return
int
0 on success, or -1 w/ errno
@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

clearenv

Removes all environment variables.

@return
int

clearerr

@param
struct FILE* f
@return
void

clock

Returns how much CPU program has consumed on time-sharing system.

@return
long
value that can be divided by CLOCKS_PER_SEC, or -1 w/ errno
@see clock_gettime()

clock_gettime

Returns nanosecond time.

This is a high-precision timer that supports multiple definitions of time. Among the more popular is CLOCK_MONOTONIC. This function has a zero syscall implementation of that on modern x86.

@param
int clockid
can be CLOCK_REALTIME, CLOCK_MONOTONIC, etc. noting that on Linux CLOCK_MONOTONIC is redefined to use the monotonic clock that's actually monotonic lool
ANONYMOUS-STRUCT* ts
is where the result is stored
@return
int
0 on success, or -1 w/ errno
@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_s

Closes file descriptor.

The caller's variable is made -1 so subsequent calls are no-ops.

@param
int* fdp
@return
int
0 on success, or -1 w/ errno
@asyncsignalsafe

closedir

Closes directory object returned by opendir().

@param
struct dirstream* dir
@return
int
0 on success or -1 w/ errno

CloseSymbolTable

Frees symbol table.

@param
struct SymbolTable** table
@return
int
0 on success or -1 on system error

cmpsb

Compares 8-bit signed integers.

@param
rdi
points to left integer
rsi
points to right integer
@return
<0, 0, or >0 based on comparison

cmpsl

Compares 32-bit signed integers.

@param
rdi
points to left integer
rsi
points to right integer
@return
<0, 0, or >0 based on comparison

cmpsq

Compares 64-bit signed integers.

@param
rdi
points to left integer
rsi
points to right integer
@return
<0, 0, or >0 based on comparison

cmpsw

Compares 16-bit signed integers.

@param
rdi
points to left integer
rsi
points to right integer
@return
<0, 0, or >0 based on comparison

cmpub

Compares 8-bit unsigned integers.

@param
rdi
points to left integer
rsi
points to right integer
@return
<0, 0, or >0 based on comparison

cmpul

Compares 32-bit unsigned integers.

@param
rdi
points to left integer
rsi
points to right integer
@return
<0, 0, or >0 based on comparison

cmpuq

Compares 64-bit unsigned integers.

@param
rdi
points to left integer
rsi
points to right integer
@return
<0, 0, or >0 based on comparison

cmpuw

Compares 16-bit unsigned integers.

@param
rdi
points to left integer
rsi
points to right integer
@return
<0, 0, or >0 based on comparison

cmpxchg

Compares and exchanges.

@param
void* ifthing
is uint𝑘_t[hasatleast 1] where 𝑘 ∈ {8,16,32,64}
long isequaltome
long replaceitwithme
unsigned long size
is automatically supplied by macro wrapper
@return
_Bool
true if value was exchanged, otherwise false
@see lockcmpxchg()

commandv

Resolves full pathname of executable.

@param
char* name
char* pathbuf
@return
char*
execve()'able path, or NULL w/ errno
@errno ENOENT, EACCES, ENOMEM
@see free(), execvpe()
@asyncsignalsafe
@vforksafe

commandvenv

Finds full executable path in overridable way.

This is a higher level version of the commandv() function. Programs that spawn subprocesses can use this function to determine the path at startup. Here's an example how you could use it:

if ((strace = commandvenv("STRACE", "strace"))) {
  strace = strdup(strace);
} else {
  fprintf(stderr, "error: please install strace\n");
  exit(1);
}
@param
char* var
is environment variable which may be used to override PATH search, and it can force a NULL result if it's empty
char* cmd
is name of program, which is returned asap if it's an absolute path
@return
char*
pointer to exe path string, or NULL if it couldn't be found or the environment variable was empty; noting that the caller should copy this string before saving it

compress

Compresses source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed data. compress() is equivalent to compress2() with a level parameter of Z_DEFAULT_COMPRESSION.

@return
int
Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer.

compress2

Compresses source buffer into the destination buffer. The level parameter has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed data.

@return
int
Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid.

compressBound

Returns an upper bound on the compressed size after compress() or compress2() on sourceLen bytes. It would be used before a compress() or compress2() call to allocate the destination buffer.

@return
unsigned long

_construct

Calls global initialization functions.

@param
r12
is argc
r13
is argv
r14
is environ
r15
is auxv
@return

convertmicros

@param
struct it_value* tv
long tick
@return
long

ConvertTicksToNanos

@param
unsigned long ticks
@return
long double

copy_file_range

Transfers data between files.

@param
int infd
long* inopt_out_inoffset
int outfd
should be a writable file, but not O_APPEND
long* inopt_out_outoffset
unsigned long uptobytes
unsigned int flags
is reserved for future use
@return
long
number of bytes actually copied, or -1 w/ errno
@see sendfile() for seekable → socket
@see splice() for fd ↔ pipe

copy_with_crc

@param
struct z_stream* strm
unsigned char* dst
long size
@return
void

copyfd

Copies data between file descriptors the slow way.

@param
int infd
long* inoutopt_inoffset
int outfd
long* inoutopt_outoffset
unsigned long size
unsigned int flags
@return
long
-1 on error/interrupt, 0 on eof, or [1..size] on success
@see copy_file_range() for file ↔ file
@see sendfile() for seekable → socket
@see splice() for fd ↔ pipe

copyfile

Copies file.

@param
char* src
char* dst
int flags
@return
int

copysign

Returns 𝑥 with same sign as 𝑦.

@param
𝑥
is double scalar in low half of %xmm0
𝑦
is double scalar in low half of %xmm1
@return
double scalar in low half of %xmm0

copysignf

Returns 𝑥 with same sign as 𝑦.

@param
𝑦
is float scalar in low quarter of %xmm0
𝑥
is float scalar in low quarter of %xmm1
@return
float scalar in low quarter of %xmm0

copysignl

Returns 𝑥 with same sign as 𝑦.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
𝑦
is the power, also pushed on stack, in reverse order
@return
result on FPU stack in %st

cos

Returns cosine of 𝑥.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0
@domain -(3π/8) < 𝑥 < 3π/8 for best accuracy

cosf

Returns cosine of 𝑥.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0
@domain -(3π/8) < 𝑥 < 3π/8 for best accuracy

cosh

Returns hyperbolic cosine of 𝑥.

@param
double x
@return
double

coshf

Returns hyperbolic cosine of 𝑥.

@param
float x
@return
float

coshl

Returns hyperbolic cosine of 𝑥.

@param
long double x
@return
long double

cosl

Returns cosine of 𝑥.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
%st stores result
@domain -(3π/8) < 𝑥 < 3π/8 for best accuracy

cosmo

Cosmopolitan runtime.

@param
edi
is argc
rsi
is argv
rdx
is environ
rcx
is auxv
@noreturn

cprojl

Projects into Rienmann sphere.

@param
z
is complex long double passed on stack
@return
@note needs sse3

crc32

Update a running CRC-32 with the bytes buf[0..len-1] and return the updated CRC-32. If buf is Z_NULL, this function returns the required initial value for the crc. Pre- and post-conditioning (one's complement) is performed within this function so it shouldn't be done by the application.

Usage example:

uLong crc = crc32(0L, Z_NULL, 0);
while (read_buffer(buffer, length) != EOF) {
  crc = crc32(crc, buffer, length);
}
if (crc != original_crc) error();
@return
unsigned long

crc32_combine

Combine two CRC-32 check values into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, CRC-32 check values were calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and len2.

@return
unsigned long

crc32_pclmul

Computes Phil Katz CRC-32 w/ carryless multiply isa.

This is support code that's abstracted by crc32_z().

@param
edi
is initial value
rsi
points to buffer
rdx
is bytes in buffer that's >=64 and %16==0
@return
eax is crc32
@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_z

Computes 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
unsigned int h
is initial value
void* data
unsigned long size
@return
unsigned int

crc32c

Computes 32-bit Castagnoli Cyclic Redundancy Check.

@param
edi
is the initial hash value (0 is fine)
rsi
points to the data
rdx
is the byte size of data
@return
eax is the new hash value
@note Used by ISCSI, TensorFlow, etc.

crc32c_pure

Computes Castagnoli CRC-32 on old computers.

@param
unsigned int init
void* data
unsigned long size
@return
unsigned int

crc32c_sse42

Hashes data with hardware acceleration at 10GBps.

@param
unsigned int init
void* data
unsigned long n
@return
unsigned int
@note needs Nehalem+ c. 2008 or Bulldozer+ c. 2011

crc32init

Generates 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
rdi
is pointer to uint32_t[256] array
esi
32-bit binary polynomial config
@return
@note imposes ~300ns one-time cost

crc_finalize

@param
struct DeflateState* s
@return
void

crc_reset

@param
struct DeflateState* s
@return
void

creat

Creates new file, returning open()'d file descriptor.

This function is shorthand for:

open(file, O_CREAT | O_WRONLY | O_TRUNC, mode)
@param
char* file
is a UTF-8 string, which is truncated if it exists
unsigned int mode
is an octal user/group/other permission, e.g. 0755
@return
int
a number registered with the system to track the open file, which must be stored using a 64-bit type in order to support both System V and Windows, and must be closed later on using close()
@see open(), touch()
@asyncsignalsafe

critbit0_allprefixed

Invokes callback for all items with prefix.

@param
struct critbit0* t
char* prefix
long(*)() callback
void* arg
@return
long
0 unless iteration was halted by CALLBACK returning nonzero, in which case that value is returned
@note h/t djb and agl

critbit0_clear

Removes all items from 𝑡.

@param
struct critbit0* t
tree
@return
void
@note h/t djb and agl

critbit0_contains

Returns non-zero iff 𝑢 ∈ 𝑡.

@param
struct critbit0* t
tree
char* u
NUL-terminated string
@return
_Bool
@note h/t djb and agl

critbit0_delete

Removes 𝑢 from 𝑡.

@param
struct critbit0* t
tree
char* u
NUL-terminated string
@return
_Bool
true if 𝑡 was mutated
@note h/t djb and agl

critbit0_emplace

Inserts 𝑢 into 𝑡 without copying.

@param
struct critbit0* t
tree
char* u
NUL-terminated string which must be 8+ byte aligned and becomes owned by the tree afterwards
unsigned long ulen
@return
_Bool
true if 𝑡 was mutated
@note h/t djb and agl

critbit0_get

Returns first item in 𝑡 with prefix 𝑢.

@param
struct critbit0* t
tree
char* u
NUL-terminated string
@return
char*
item or NULL if not found
@note h/t djb and agl

critbit0_insert

Inserts 𝑢 into 𝑡.

@param
struct critbit0* t
tree
char* u
NUL-terminated string
@return
_Bool
true if 𝑡 was mutated
@note h/t djb and agl

ctime

@param
long* timep
@return
char*

ctime_r

@param
long* timep
char* buf
@return
char*

__cxa_atexit

Adds global destructor.

Destructors are called in reverse order. They won't be called if the program aborts or _exit() is called. Invocations of this function are usually generated by the C++ compiler. Behavior is limitless if some other module has linked calloc().

@param
void* fp
is void(*)(T)
void* arg
is passed to callback
void* pred
can be non-null for things like dso modules
@return
int
0 on success or nonzero w/ errno
@note folks have forked libc in past just to unbloat atexit()

__cxa_finalize

Triggers global destructors.

They're called in LIFO order. If a destructor adds more destructors, then those destructors will be called immediately following, before iteration continues.

@param
void* pred
can be null to match all
@return
void

_d2ld2

Thunks double(*fn)(double,double) -> long double fn.

@param
%xmm0[0]
contains double param
@return
%xmm0[0] contains double result
@note 100% negligible overhead

__defer

Calls FN(ARG) when function returns.

@param
struct StackFrame* frame
void* fn
void* arg
@return
void

deflate

deflate compresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush.

The detailed semantics are as follows. deflate performs one or both of the following actions:

  • Compress more input starting at next_in and update next_in and
avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in and avail_in are updated and processing will resume at this point for the next call of deflate().

  • Generate more output starting at next_out and update next_out and
avail_out accordingly. This action is forced if the parameter flush is non zero. Forcing flush frequently degrades the compression ratio, so this parameter should be set only when necessary. Some output may be provided even if flush is zero.

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
int
Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if all input has been consumed and all output has been produced (only when flush is set to Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example if next_in or next_out was Z_NULL or the state was inadvertently written over by the application), or Z_BUF_ERROR if no progress is possible (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and deflate() can be called again with more input and more output space to continue compressing.

deflateBound

deflateBound() returns an upper bound on the compressed size after deflation of sourceLen bytes. It must be called after deflateInit() or deflateInit2(), and after deflateSetHeader(), if used. This would be used to allocate an output buffer for deflation in a single pass, and so would be called before deflate(). If that first deflate() call is provided the sourceLen input bytes, an output buffer allocated to the size returned by deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed to return Z_STREAM_END. Note that it is possible for the compressed size to be larger than the value returned by deflateBound() if flush options other than Z_FINISH or Z_NO_FLUSH are used.

@return
unsigned long

deflateCopy

Sets destination stream as a complete copy of the source stream.

This function can be useful when several compression strategies will be tried, for example when there are several ways of pre-processing the input data with a filter. The streams that will be discarded should then be freed by calling deflateEnd. Note that deflateCopy duplicates the internal compression state which can be quite large, so this strategy is slow and can consume lots of memory.

@return
int
Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and destination.

deflateEnd

All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output.

@return
int
Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent, Z_DATA_ERROR if the stream was freed prematurely (some input or output was discarded). In the error case, msg may be set but then points to a static string (which must not be deallocated).

deflateGetDictionary

Returns the sliding dictionary being maintained by deflate. dictLength is set to the number of bytes in the dictionary, and that many bytes are copied to dictionary. dictionary must have enough space, where 32768 bytes is always enough. If deflateGetDictionary() is called with dictionary equal to Z_NULL, then only the dictionary length is returned, and nothing is copied. Similary, if dictLength is Z_NULL, then it is not set.

deflateGetDictionary() may return a length less than the window size, even when more than the window size in input has been provided. It may return up to 258 bytes less in that case, due to how zlib's implementation of deflate manages the sliding window and lookahead for matches, where matches can be up to 258 bytes long. If the application needs the last window-size bytes of input, then that would need to be saved by the application outside of zlib.

@return
int
Z_OK on success, or Z_STREAM_ERROR if the stream state is inconsistent.

deflateInit

Initializes the internal stream state for compression. The fields zalloc, zfree and opaque must be initialized before by the caller. If zalloc and zfree are set to Z_NULL, deflateInit updates them to use default allocation functions.

The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6).

@return
int
Z_OK if success, Z_MEM_ERROR if there was not enough memory, or Z_STREAM_ERROR if level is not a valid compression level. msg is set to null if there is no error message. deflateInit does not perform any compression: this will be done by deflate().

deflateInit2

This is another version of deflateInit with more compression options. The fields next_in, zalloc, zfree and opaque must be initialized before by the caller.

The method parameter is the compression method. It must be Z_DEFLATED in this version of the library.

The windowBits parameter is the base two logarithm of the window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. Larger values of this parameter result in better compression at the expense of memory usage. The default value is 15 if deflateInit is used instead.

For the current implementation of deflate(), a windowBits value of 8 (a window size of 256 bytes) is not supported. As a result, a request for 8 will result in 9 (a 512-byte window). In that case, providing 8 to inflateInit2() will result in an error when the zlib header with 9 is checked against the initialization of inflate(). The remedy is to not use 8 with deflateInit2() with this initialization, or at least in that case use 9 with inflateInit2().

windowBits can also be -8..-15 for raw deflate. In this case, -windowBits determines the window size. deflate() will then generate raw deflate data with no zlib header or trailer, and will not compute a check value.

windowBits can also be greater than 15 for optional gzip encoding. Add 16 to windowBits to write a simple gzip header and trailer around the compressed data instead of a zlib wrapper. The gzip header will have no file name, no extra data, no comment, no modification time (set to zero), no header crc, and the operating system will be set to the appropriate value, if the operating system was determined at compile time. If a gzip stream is being written, strm->adler is a CRC-32 instead of an Adler-32.

For raw deflate or gzip encoding, a request for a 256-byte window is rejected as invalid, since only the zlib header provides a means of transmitting the window size to the decompressor.

The memLevel parameter specifies how much memory should be allocated for the internal compression state. memLevel=1 uses minimum memory but is slow and reduces compression ratio; memLevel=9 uses maximum memory for optimal speed. The default value is 8. See zconf.h for total memory usage as a function of windowBits and memLevel.

The strategy parameter is used to tune the compression algorithm. Use the value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no string match), or Z_RLE to limit match distances to one (run-length encoding). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect of Z_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications.

@return
int
Z_OK if success, Z_MEM_ERROR if there was not enough memory, or Z_STREAM_ERROR if any parameter is invalid (such as an invalid method). msg is set to null if there is no error message. deflateInit2 does not perform any compression: this will be done by deflate().

deflateParams

Dynamically update the compression level and compression strategy. The interpretation of level and strategy is as in deflateInit2(). This can be used to switch between compression and straight copy of the input data, or to switch to a different kind of input data requiring a different strategy. If the compression approach (which is a function of the level) or the strategy is changed, and if any input has been consumed in a previous deflate() call, then the input available so far is compressed with the old level and strategy using deflate(strm, Z_BLOCK). There are three approaches for the compression levels 0, 1..3, and 4..9 respectively. The new level and strategy will take effect at the next call of deflate().

If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does not have enough output space to complete, then the parameter change will not take effect. In this case, deflateParams() can be called again with the same parameters and more output space to try again.

In order to assure a change in the parameters on the first try, the deflate stream should be flushed using deflate() with Z_BLOCK or other flush request until strm.avail_out is not zero, before calling deflateParams(). Then no more input data should be provided before the deflateParams() call. If this is done, the old level and strategy will be applied to the data compressed before deflateParams(), and the new level and strategy will be applied to the the data compressed after deflateParams().

deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if there was not enough output space to complete the compression of the available input data before a change in the strategy or approach. Note that in the case of a Z_BUF_ERROR, the parameters are not changed. A return value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be retried with more output space.

@return
int

deflatePending

deflatePending() returns the number of bytes and bits of output that have been generated, but not yet provided in the available output. The bytes not provided would be due to the available output space having being consumed. The number of bits of output not provided are between 0 and 7, where they await more bits to join them in order to fill out a full byte. If pending or bits are Z_NULL, then those values are not set.

@return
int
Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent.

deflatePrime

deflatePrime() inserts bits in the deflate output stream. The intent is that this function is used to start off the deflate output with the bits leftover from a previous deflate stream when appending to it. As such, this function can only be used for raw deflate, and must be used before the first deflate() call after a deflateInit2() or deflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the output.

@return
int
Z_OK if success, Z_BUF_ERROR if there was not enough room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the source stream state was inconsistent.

deflateReset

This function is equivalent to deflateEnd followed by deflateInit, but does not free and reallocate the internal compression state. The stream will leave the compression level and any other attributes that may have been set unchanged.

deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL).

@return
int

deflateSetDictionary

Initializes the compression dictionary from the given byte sequence without producing any compressed output. When using the zlib format, this function must be called immediately after deflateInit, deflateInit2 or deflateReset, and before any call of deflate. When doing raw deflate, this function must be called either before any call of deflate, or immediately after the completion of a deflate block, i.e. after all input has been consumed and all output has been delivered when using any of the flush options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The compressor and decompressor must use exactly the same dictionary (see inflateSetDictionary).

The dictionary should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary.

Depending on the size of the compression data structures selected by deflateInit or deflateInit2, a part of the dictionary may in effect be discarded, for example if the dictionary is larger than the window size provided in deflateInit or deflateInit2. Thus the strings most likely to be useful should be put at the end of the dictionary, not at the front. In addition, the current implementation of deflate will use at most the window size minus 262 bytes of the provided dictionary.

Upon return of this function, strm->adler is set to the Adler-32 value of the dictionary; the decompressor may later use this value to determine which dictionary has been used by the compressor. (The Adler-32 value applies to the whole dictionary even if only a subset of the dictionary is actually used by the compressor.) If a raw deflate was requested, then the Adler-32 value is not computed and strm->adler is not set.

@return
int
Z_OK if success, or Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent (for example if deflate has already been called for this stream or if not at a block boundary for raw deflate). deflateSetDictionary does not perform any compression: this will be done by deflate().

deflateSetHeader

Provides gzip header information for when a gzip stream is requested by deflateInit2(). deflateSetHeader() may be called after deflateInit2() or deflateReset() and before the first call of deflate(). The text, time, os, extra field, name, and comment information in the provided gz_header structure are written to the gzip header (xflag is ignored -- the extra flags are set according to the compression level). The caller must assure that, if not Z_NULL, name and comment are terminated with a zero byte, and that if extra is not Z_NULL, that extra_len bytes are available there. If hcrc is true, a gzip header crc is included. Note that the current versions of the command-line version of gzip (up through version 1.3.x) do not support header crc's, and will report that it is a "multi-part gzip file" and give up.

If deflateSetHeader is not used, the default gzip header has text false, the time set to zero, and os set to 255, with no extra, name, or comment fields. The gzip header is returned to the default state by deflateReset().

deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent.

@return
int

deflateTune

Fine tune deflate's internal compression parameters. This should only be used by someone who understands the algorithm used by zlib's deflate for searching for the best matching string, and even then only by the most fanatic optimizer trying to squeeze out the last compressed bit for their specific input data. Read the deflate.c source code for the meaning of the max_lazy, good_length, nice_length, and max_chain parameters.

deflateTune() can be called after deflateInit() or deflateInit2(), and returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.

@return
int

describeos

@param
char* buf
unsigned long size
@return
char*

deserializednsheader

Serializes DNS message header to wire.

@param
struct header* header
unsigned char* buf
unsigned long size
@return
int
number of bytes read (always 12) or -1 w/ errno

devrand

Reads random bytes from system pseudo random number api.

@param
void* buf
unsigned long size
@return
int
0 on success or -1 w/ errno

__die

Aborts process after printing a backtrace.

If a debugger is present then this will trigger a breakpoint.

@noreturn

difftime

@param
long x
long y
@return
double

dirfd

Returns file descriptor associated with DIR object.

@param
struct dirstream* dir
@return
int

dirname

Returns directory portion of path.

@param
char* s
is mutated
@return
char*

div

@param
int num
int den
@return
struct div_t

div1000000000int64

Divides 64-bit signed integer by 1,000,000,000.

@param
rdi
is number to divide
@return
quotient

div1000000int64

Divides 64-bit signed integer by 1,000,000.

@param
rdi
is number to divide
@return
quotient

div10000int64

Divides 64-bit signed integer by 10,000.

@param
rdi
is number to divide
@return
truncated quotient

div1000int64

Divides 64-bit signed integer by 1,000.

@param
rdi
is number to divide
@return
quotient

div100int64

Divides 64-bit signed integer by 100.

@param
rdi
is number to divide
@return
rax has quotient

div10int64

Divides 64-bit signed integer by 10.

@param
rdi
is number to divide
@return
quotient

__divmodti4

Divides 128-bit signed integers w/ remainder.

@param
__int128 a
is numerator
__int128 b
is denominator
unsigned __int128* opt_out_rem
receives euclidean division remainder if not null
@return
__int128
quotient or result of division
@note rounds towards zero

__divti3

Divides 128-bit signed integers.

@param
__int128 a
is numerator
__int128 b
is denominator
@return
__int128
quotient or result of division
@note rounds towards zero

djbsort

D.J. Bernstein's outrageously fast integer sorting algorithm.

@param
int* a
unsigned long n
@return
void

djbsort_avx2

D.J. Bernstein's outrageously fast integer sorting algorithm.

@param
rdi
is int32 array
rsi
is number of elements in rdi
@return
@note public domain
@see en.wikipedia.org/wiki/Sorting_network

dl_iterate_phdr

@param
int(*)() callback
void* data
@return
int

dlcalloc

@param
unsigned long n_elements
unsigned long elem_size
@return
void*

dlclose

@param
void* handle
@return
int

dlerror

@return
char*

dlfree

@param
void* mem
@return
void

dlindependent_calloc

independent_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
unsigned long n_elements
unsigned long elem_size
void** chunks
@return
void**

dlindependent_comalloc

independent_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
unsigned long n_elements
unsigned long* sizes
void** chunks
@return
void**

dlmalloc

@param
unsigned long bytes
@return
void*

dlmalloc_dispose_chunk

@param
struct MallocState* m
struct mchunk* p
unsigned long psize
@return
void


dlmalloc_stats

Prints 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
struct res*
struct MallocState* m
@return
struct res

dlmalloc_sys_trim

@param
struct MallocState* m
unsigned long pad
@return
int

dlmalloc_trim

If possible, gives memory back to the system (via negative arguments to sbrk) if there is unused memory at the high end of the malloc pool or in unused MMAP segments. You can call this after freeing large blocks of memory to potentially reduce the system-level memory requirements of a program. However, it cannot guarantee to reduce memory. Under some allocation patterns, some large free blocks of memory will be locked between two used chunks, so they cannot be given back to the system.

The pad argument to malloc_trim represents the amount of free trailing space to leave untrimmed. If this argument is zero, only the minimum amount of memory to maintain internal data structures will be left. Non-zero arguments can be supplied to maintain enough trailing space to service future expected allocations without having to re-obtain memory from the system.

@param
unsigned long pad
@return
int
1 if it actually released any memory, else 0

dlmalloc_try_realloc_chunk

@param
struct MallocState* m
struct mchunk* p
unsigned long nb
int can_move
@return
struct mchunk*

dlmalloc_usable_size

@param
void* mem
@return
unsigned long

dlmemalign

@param
unsigned long alignment
unsigned long bytes
@return
void*

dlopen

@param
char* file
int mode
@return
void*

dlposix_memalign

@param
void** pp
unsigned long alignment
unsigned long bytes
@return
int

dlpvalloc

@param
unsigned long bytes
@return
void*

dlrealloc

@param
void* oldmem
unsigned long bytes
@return
void*

dlrealloc_in_place

@param
void* oldmem
unsigned long bytes
@return
void*

dlsym

@param
void* handle
char* name
@return
void*

dlvalloc

@param
unsigned long bytes
@return
void*

dnsnamecmp

Compares DNS hostnames in reverse lexicographical asciibetical order.

@param
char* A
char* B
@return
int
<0, 0, or >0
@see test/libc/dns/dnsnamecmp_test.c (the code that matters)

do_check_free_chunk

@param
struct MallocState* m
struct mchunk* p
@return
void

do_check_inuse_chunk

@param
struct MallocState* m
struct mchunk* p
@return
void

do_check_malloc_state

@param
struct MallocState* m
@return
void

do_check_malloced_chunk

@param
struct MallocState* m
void* mem
unsigned long s
@return
void

do_check_mmapped_chunk

@param
struct MallocState* m
struct mchunk* p
@return
void

do_check_top_chunk

@param
struct MallocState* m
struct mchunk* p
@return
void

__dos2errno

Translates Windows error using superset of consts.sh.

@param
unsigned int error
@return
int

DosDateTimeToUnix

Converts MS-DOS timestamp to UNIX.

@param
unsigned int date
unsigned int time
@return
long
@note type signature supports dates greater than 2100
@see PKZIP, FAT

dprintf

Formats string directly to file descriptor.

@param
int fd
char* fmt
...
@return
int

drem

remainder(𝑥,𝑦) means (𝑥 rem 𝑦) w/ rint()-style rounding.

@param
𝑥
is double passed in lower half of %xmm0
𝑦
is double passed in lower half of %xmm1
@return
remainder ∈ (-|𝑦|,|𝑦|) in %xmm0
@define 𝑥-rint(𝑥/𝑦)*𝑦
@see fmod(), emod(), operator%

dsleep

Sleeps w/ higher precision.

@param
long double secs
@return
long double

dtime

Returns seconds since epoch w/ high-precision.

@param
int clockid
can be CLOCK_{REALTIME,MONOTONIC}, etc.
@return
long double

dtoa

@param
double d0
int mode
int ndigits
int* decpt
int* sign
char** rve
@return
char*

dup

Duplicates file descriptor/handle.

@param
int fd
remains open afterwards
@return
int
some arbitrary new number for fd
@asyncsignalsafe
@vforksafe

dup2

Duplicates file descriptor, granting it specific number.

@param
int oldfd
isn't closed afterwards
int newfd
if already assigned, is silently closed beforehand; unless it's equal to oldfd, in which case dup2() is a no-op
@return
int
new file descriptor, or -1 w/ errno
@asyncsignalsafe
@vforksafe

dup3

Duplicates 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
int oldfd
isn't closed afterwards
int newfd
if already assigned, is silently closed beforehand; unless it's equal to oldfd, in which case dup2() is a no-op
int flags
@return
int
@flags can have O_CLOEXEC
@see dup(), dup2()

eai2str

Turns getaddrinfo() return code into string.

@param
int code
@return
char*

ecvt

@param
double value
int ndigit
int* decpt
int* sign
@return
char*

endgrent

@return
void

endpwent

@return
void

endswith

Returns true if s has suffix.

@param
char* s
is a NUL-terminated string
char* suffix
is also NUL-terminated
@return
_Bool

endswith16

Returns true if s has suffix.

@param
unsigned short* s
is a NUL-terminated string
unsigned short* suffix
is also NUL-terminated
@return
_Bool

erf

Returns error function of 𝑥.

@param
double x
@return
double

erfc

Returns complementary error function of 𝑥.

@param
double x
@return
double

err

@param
int eval
char* fmt
...
@noreturn

errno

Global variable for last error.

The system call wrappers update this with WIN32 error codes. Unlike traditional libraries, Cosmopolitan error codes are defined as variables. By convention, system calls and other functions do not update this variable when nothing's broken.

@return
@see libc/sysv/consts.sh
@see libc/sysv/errfuns.h
@see __errno_location() stable abi

__errno_location

Returns address of errno variable.

@return
@note this isn't a universal definition

errx

@param
int eval
char* fmt
...
@noreturn

escapedos

Escapes command so DOS can run it.

@param
unsigned short* buffer
unsigned int buflen
unsigned short* unquoted
unsigned int len
@return
_Bool
@see Iain Patterson's NSSM for original code in public domain

execl

Executes program, with current environment.

The current process is replaced with the executed one.

@param
char* exe
char* arg
...
@return
int
doesn't return on success, otherwise -1 w/ errno
@asyncsignalsafe
@vforksafe

execle

Executes program, with custom environment.

The current process is replaced with the executed one.

@param
char* exe
char* arg
...
@return
int
doesn't return on success, otherwise -1 w/ errno
@asyncsignalsafe
@vforksafe

execlp

Executes program, with PATH search and current environment.

The current process is replaced with the executed one.

@param
char* prog
is program to launch (may be PATH searched)
char* arg
...
@return
int
doesn't return on success, otherwise -1 w/ errno
@asyncsignalsafe
@vforksafe

execv

Replaces process with specific program, using default environment.

@param
char* exe
char** argv
@return
int
@asyncsignalsafe
@vforksafe

execve

Replaces current process with program.

@param
char* program
will not be PATH searched, see commandv()
char** argv
char** envp
@return
int
doesn't return, or -1 w/ errno
@asyncsignalsafe
@vforksafe

execvp

Replaces process, with path search, using default environment.

@param
char* file
char** argv
@return
int
@asyncsignalsafe
@vforksafe

execvpe

Executes program, with path environment search.

The current process is replaced with the executed one.

@param
char* prog
is the program to launch
char** argv
is [file,argv₁..argvₙ₋₁,NULL]
char** envp
is ["key=val",...,NULL]
@return
int
doesn't return on success, otherwise -1 w/ errno
@asyncsignalsafe
@vforksafe

exit

Exits process with grace.

This calls functions registered by atexit() before terminating the current process, and any associated threads. It also calls all the legacy linker registered destructors in reeverse order

@param
int exitcode
is masked with 255
@noreturn
@see _Exit()

_exit

Terminates process, ignoring destructors and atexit() handlers.

When running on bare metal, this function will reboot your computer by hosing the interrupt descriptors and triple faulting the system.

@param
int exitcode
is masked with 255
@noreturn
@asyncsignalsafe
@vforksafe

exp

Returns 𝑒^x.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0

exp10

Returns 10^x.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0
@see pow(), exp()

exp10f

Returns 10^x.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0

exp10l

Returns 10^x.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result of exponentiation on FPU stack in %st

exp2

Returns 2^𝑥.

@param
𝑥
is a double passed in the lower quadword of %xmm0
@return
result in lower quadword of %xmm0

exp2f

Returns 2^𝑥.

@param
𝑥
is a float passed in the lower quarter of %xmm0
@return
result in lower quarter of %xmm0

exp2l

Returns 2^𝑥.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result of exponentiation on FPU stack in %st

expf

Returns 𝑒^x.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0

expl

Returns 𝑒^x.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result of exponentiation on FPU stack in %st

explicit_bzero

Sets 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
rdi
is dest
rsi
is the number of bytes to set
@return

expm1

Returns 𝑒^x-1.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0

expm1f

Returns 𝑒^x-1.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0

expm1l

Returns 𝑒^x-1.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result of exponentiation on FPU stack in %st

_f2ld2

Thunks float(*fn)(float,float) -> long double fn.

@param
%xmm0[0]
contains float param
@return
%xmm0[0] contains float result
@note 100% negligible overhead

fabs

Returns absolute value of 𝑥.

@param
𝑥
is double passed in lower half on %xmm0
@return
absolute value in %xmm0

fabsf

Returns absolute value of 𝑥.

@param
𝑥
is float passed in lower quarter on %xmm0
@return
absolute value in %xmm0

fabsl

Returns absolute value of 𝑥.

@param
𝑥
long double passed on stack
@return
absolute value in %st

faccessat

Checks if effective user can access path in particular ways.

@param
int dirfd
is normally AT_FDCWD but if it's an open directory and file is a relative path, then file is opened relative to dirfd
char* path
is a filename or directory
int mode
can be R_OK, W_OK, X_OK, F_OK
unsigned int flags
should be 0
@return
int
0 if ok, or -1 and sets errno
@asyncsignalsafe

fadvise

Drops hints to O/S about intended I/O behavior.

It makes a huge difference. For example, when copying a large file, it can stop the system from persisting GBs of useless memory content.

@param
int fd
unsigned long offset
unsigned long len
0 means ‘til end of file
int advice
can be MADV_SEQUENTIAL, MADV_RANDOM, etc.
@return
int
-1 on error

favail

Returns number of bytes available in stream buffer.

@param
struct FILE* f
@return
unsigned int

__fbufsize

Returns capacity of stdio stream buffer.

@param
struct FILE* f
@return
unsigned long

fchdir

Sets current directory based on file descriptor.

@param
int dirfd
@return
int
@see open(path, O_DIRECTORY)
@asyncsignalsafe

fchmod

Changes 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 bit
This works on Windows NT if you ignore the error ;-)
@param
int fd
unsigned int mode
contains octal flags (base 8)
@return
int
@errors ENOSYS
@asyncsignalsafe
@see chmod()

fchown

Changes owner and/or group of file, via open()'d descriptor.

@param
int fd
unsigned int uid
is user id, or -1u to not change
unsigned int gid
is group id, or -1u to not change
@return
int
0 on success, or -1 w/ errno
@see /etc/passwd for user ids
@see /etc/group for group ids

fchownat

Changes owner and/or group of pathname.

@param
int dirfd
is open()'d relative-to directory, or AT_FDCWD, etc.
char* pathname
unsigned int uid
is user id, or -1 to not change
unsigned int gid
is group id, or -1 to not change
unsigned int flags
can have AT_SYMLINK_NOFOLLOW, etc.
@return
int
0 on success, or -1 w/ errno
@see chown(), lchown() for shorthand notation
@see /etc/passwd for user ids
@see /etc/group for group ids
@asyncsignalsafe

fclose

Closes standard i/o stream and its underlying thing.

@param
struct FILE* f
is the file object, which is always free if it's heap, otherwise its resources are released and fields updated
@return
int
0 on success or -1 on error, which can be a trick for differentiating between EOF and real errors during previous i/o calls, without needing to call ferror()
@see fclose_s()

fclose_s

Closes standard i/o stream and its underlying thing.

@param
struct FILE** fp
@return
int
0 on success or -1 on error, which can be a trick for differentiating between EOF and real errors during previous i/o calls, without needing to call ferror()

fcntl

Does things with file descriptor, via re-imagined hourglass api, e.g.

CHECK_NE(-1, fcntl(fd, F_SETFD, FD_CLOEXEC));
@param
int fd
int cmd
can be F_{GET,SET}{FD,FL}, etc.
...
@return
int
0 on success, or -1 w/ errno
@asyncsignalsafe

fcvt

@param
double value
int ndigit
int* decpt
int* sign
@return
char*

fdatasync

Blocks until kernel flushes non-metadata buffers for fd to disk.

@param
int fd
@return
int
0 on success, or -1 w/ errno
@see fsync(), sync_file_range()
@asyncsignalsafe

fdopen

Allocates stream object for already-opened file descriptor.

@param
int fd
existing file descriptor or -1 for plain old buffer
char* mode
is passed to fopenflags()
@return
struct FILE*
new stream or NULL w/ errno
@error ENOMEM

fdopendir

Creates directory object for file descriptor.

@param
int fd
gets owned by this function, if it succeeds
@return
struct dirstream*
new directory object, which must be freed by closedir(), or NULL w/ errno
@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

feof

Returns true if stream is in end-of-file state.

@param
struct FILE* f
@return
int

ferror

Returns nonzero if stream is in error state.

@param
struct FILE* f
@return
int
@note EOF doesn't count
@see feof()

fflush

Blocks until data from stream buffer is written out.

@param
struct FILE* f
is the stream handle
@return
int
number of bytes written or -1 on error

ffs

Finds 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
edi
is the input number
@return
number in range [1,32] or 0 if no bits set
@see also treasure trove of nearly identical functions
@asyncsignalsafe

ffsl

Finds 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
rdi
is the input number
@return
number in range [1,64] or 0 if no bits set
@see also treasure trove of nearly identical functions
@asyncsignalsafe

ffsll

Finds 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
rdi
is the input number
@return
number in range [1,64] or 0 if no bits set
@see also treasure trove of nearly identical functions
@asyncsignalsafe

fgetc

Reads uint8_t from stream.

@param
struct FILE* f
@return
int

fgetpos

@param
struct FILE* stream
unsigned long* pos
@return
int

fgets

Reads 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
char* s
int size
struct FILE* f
@return
char*

fgetwc

Reads UTF-8 character from stream.

@param
struct FILE* f
@return
unsigned int
wide character or -1 on EOF or error

fgetws

Reads UTF-8 content from stream into UTF-32 buffer.

@param
int* s
int size
struct FILE* f
@return
int*

filecmp

Compares contents of files with memcmp().

@param
char* pathname1
char* pathname2
@return
int
≤0, 0, or ≥0 based on comparison; or ≠0 on error, in which case we make our best effort to sift failing filenames rightward, and errno can be set to 0 beforehand to differentiate errors

fileexists

Returns 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
char* path
@return
_Bool

fileno

Returns file descriptor associated with stream.

@param
struct FILE* f
@return
int

filetimetotime

@param
struct ft ft
@return
long

FileTimeToTimeSpec

Converts Windows COBOL timestamp to UNIX epoch in nanoseconds.

@param
struct ft ft
@return
ANONYMOUS-STRUCT

FileTimeToTimeVal

@param
struct ru_stime* tv
struct ft ft
@return
void

FindComBinary

Returns path of binary without debug information, or null.

@return
char*
path to non-debug binary, or -1 w/ errno

FindDebugBinary

Returns path of binary with the debug information, or null.

@return
char*
path to debug binary, or -1 w/ errno

FindMemoryInterval

@param
struct _mmi* mm
int x
@return
unsigned int

__fixupnewfd

Applies file descriptor fixups on XNU or old Linux.

@param
int fd
int flags
@return
int
@see __fixupnewsockfd() for socket file descriptors

__flbf

Returns nonzero if stream is line buffered.

@param
struct FILE* f
@return
int

flock

Acquires lock on file.

@param
int fd
int op
can have LOCK_{SH,EX,NB,UN} for shared, exclusive, non-blocking, and unlocking
@return
int
0 on success, or -1 w/ errno

flockfile

Does nothing since Cosmopolitan currently doesn't support threads.

@param
struct FILE* f
@return
void

flogf

Writes formatted message w/ timestamp to log.

@param
unsigned int level
char* file
int line
struct FILE* f
char* fmt
...
@return
void
@see vflogf()

floor

Returns largest integral not greater than 𝑥.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0

floorf

Returns largest integral not greater than 𝑥.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0

floorl

Returns largest integral not greater than 𝑥.

@param
𝑥
is long double passed on stack
@return
float scalar in low quarter of %xmm0

_flushlbf

Flushes all line-buffered streams.

@return
void

fmax

Returns maximum of two doubles.

If one argument is NAN then the other is returned. This function is designed to do the right thing with signed zeroes.

@param
double x
double y
@return
double

fmaxf

Returns maximum of two floats.

If one argument is NAN then the other is returned. This function is designed to do the right thing with signed zeroes.

@param
float x
float y
@return
float

fmaxl

Returns maximum of two long doubles.

If one argument is NAN then the other is returned. This function is designed to do the right thing with signed zeroes.

@param
long double x
long double y
@return
long double

fmemopen

Opens buffer as stream.

@param
void* buf
becomes owned by this function, and is allocated if NULL
unsigned long size
char* mode
@return
struct FILE*
new stream or NULL w/ errno

fmin

Returns minimum of two doubles.

If one argument is NAN then the other is returned. This function is designed to do the right thing with signed zeroes.

@param
double x
double y
@return
double

fminf

Returns 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
float x
float y
@return
float

fminl

Returns minimum of two long doubles.

If one argument is NAN then the other is returned. This function is designed to do the right thing with signed zeroes.

@param
long double x
long double y
@return
long double

fmod

fmod [sic] does (𝑥 rem 𝑦) w/ round()-style rounding.

@param
𝑥
is double passed in lower half of %xmm0
𝑦
is double passed in lower half of %xmm1
@return
remainder ∈ (-|𝑦|,|𝑦|) in %xmm0
@define 𝑥-trunc(𝑥/𝑦)*𝑦
@see emod()

fmodl

fmod [sic] does (𝑥 rem 𝑦) w/ round()-style rounding.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
𝑦
is the power, also pushed on stack, in reverse order
@return
remainder ∈ (-|𝑦|,|𝑦|) in %st
@define 𝑥-truncl(𝑥/𝑦)*𝑦
@see emod()

fnmatch

Matches filename.

  • * for wildcard
  • ? for single character
  • [abc] to match character within set
  • [!abc] to match character not within set
  • \*\?\[\] for escaping above special syntax
@param
char* pat
char* str
int flags
@return
int
@see glob()

fopen

Opens file as stream object.

@param
char* pathname
is a utf-8 ideally relative filename
char* mode
is the string mode/flag DSL see fopenflags()
@return
struct FILE*
new object to be free'd by fclose() or NULL w/ errno
@note microsoft unilaterally deprecated this function lool

fopenflags

Turns stdio flags description string into bitmask.

@param
char* mode
@return
int

fork

Creates new process zygote style.

@return
int
0 to child, child pid to parent, or -1 on error
@asyncsignalsafe

__fpending

Returns number of pending output bytes.

@param
struct FILE* f
@return
unsigned long

fprintf

@param
struct FILE* f
char* fmt
...
@return
int

__fpurge

Discards contents of stream buffer.

@param
struct FILE* f
@return
void

fputc

Writes byte to stream.

@param
int c
struct FILE* f
@return
int
c (as unsigned char) if written or -1 w/ errno
@see putc() if called within loop

fputcfb

Writes byte to stream.

@param
int c
struct FILE* f
@return
int
c (as unsigned char) if written or -1 w/ errno

fputs

Writes string to stream.

Writing stops at the NUL-terminator, which isn't included in output. This function blocks until the full string is written, unless an unrecoverable error happens.

@param
char* s
is a NUL-terminated string that's non-NULL
struct FILE* f
is an open stream
@return
int
strlen(s) or -1 w/ errno on error

fputwc

Writes wide character to stream.

@param
int wc
struct FILE* f
@return
unsigned int
wc if written or -1 w/ errno

fputws

Writes wide character string to stream.

Writing stops at the NUL-terminator, which isn't included in output. This function blocks until the full string is written, unless an unrecoverable error happens.

@param
int* s
is a NUL-terminated string that's non-NULL
struct FILE* f
is an open stream
@return
int
strlen(s) or -1 w/ errno on error

fread

Reads data from stream.

@param
void* buf
unsigned long stride
specifies the size of individual items
unsigned long count
is the number of strides to fetch
struct FILE* f
@return
unsigned long
count on success, [0,count) on eof, or 0 on error or count==0

__freadable

Returns nonzero if stream allows reading.

@param
struct FILE* f
@return
int

__freading

Returns nonzero if stream is read only.

@param
struct FILE* f
@return
int

free

Free memory returned by malloc() & co.

Releases the chunk of memory pointed to by p, that had been previously allocated using malloc or a related routine such as realloc. It has no effect if p is null. If p was not malloced or already freed, free(p) will by default cuase the current program to abort.

@param
rdi
is allocation address, which may be NULL
@return
@see dlfree()

free_s

@param
void* v
@return
void

freeaddrinfo

Frees addresses returned by getaddrinfo().

@param
struct addrinfo* addrs
@return
int

freedtoa

@param
char* s
@return
void

freehoststxt

Frees HOSTS.TXT data structure populated by parsehoststxt().

@param
struct HostsTxt** ht
@return
void

freeresolvconf

Frees resolv.conf data structure populated by parseresolvconf().

@param
struct ResolvConf** rvp
@return
void

freopen

Overwrites existing stream.

This function can be used in two ways. The first is sort of a mutating assignment. The second behavior, if pathname is NULL, is just changing the mode of an already open file descriptor.

@param
char* pathname
is the file to open or NULL
char* mode
is the mode string flags, see fopenflags()
struct FILE* stream
is the existing allocated stream memory, which is flushed and closed if already open
@return
struct FILE*
stream object if successful, or NULL w/ errno

fscanf

Decodes data from stream.

To read a line of data from a well-formed trustworthy file:

int x, y;
char text[256];
fscanf(f, "%d %d %s\n", &x, &y, text);
Please note that this function is brittle by default, which makes it a good fit for yolo coding. With some toil it can be used in a way that makes it reasonably hardened although getline() may be better.
@param
struct FILE* stream
char* fmt
...
@return
int
@see libc/fmt/vcscanf.c

fseek

Repositions open file stream.

This function flushes the buffer (unless it's currently in the EOF state) and then calls lseek() on the underlying file. If the stream is in the EOF state, this function can be used to restore it without needing to reopen the file.

@param
struct FILE* f
is a non-null stream handle
long offset
is the byte delta
int whence
can be SEET_SET, SEEK_CUR, or SEEK_END
@return
long
@returns new offset or -1 on error

__fsetlocking

Does nothing and returns FSETLOCKING_BYCALLER.

@param
struct FILE* f
int type
@return
int

fsetpos

@param
struct FILE* stream
unsigned long* pos
@return
int

fstat

Returns information about file, via open()'d descriptor.

@param
int fd
struct stat* st
@return
int
@asyncsignalsafe

fstatat

Returns information about thing.

@param
int dirfd
is normally AT_FDCWD but if it's an open directory and file is a relative path, then file becomes relative to dirfd
char* path
struct stat* st
is where result is stored
unsigned int flags
can have AT_{EMPTY_PATH,NO_AUTOMOUNT,SYMLINK_NOFOLLOW}
@return
int
0 on success, or -1 w/ errno
@see S_ISDIR(st.st_mode), S_ISREG()
@asyncsignalsafe

fsync

Blocks until kernel flushes buffers for fd to disk.

@param
int fd
@return
int
0 on success, or -1 w/ errno
@see fdatasync(), sync_file_range()
@asyncsignalsafe

ftell

Returns current position of stream.

@param
struct FILE* stream
is a non-null stream handle
@return
long
@returns current byte offset from beginning of file, or -1

ftoa

Formats floating point number.

@param
int(*)() out
void* arg
long double value
int prec
unsigned long width
unsigned long flags
@return
int
@see xdtoa() for higher precision at the cost of bloat
@see palandprintf() which is intended caller

ftrace

Prints 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
void

ftrace_init

Enables plaintext function tracing if --ftrace flag is passed.

The --ftrace CLI arg is removed before main() is called. This code is intended for diagnostic purposes and assumes binaries are trustworthy and stack isn't corrupted. Logging plain text allows program structure to easily be visualized and hotspots identified w/ sed | sort | uniq -c | sort. A compressed trace can be made by appending --ftrace 2>&1 | gzip -4 >trace.gz to the CLI arguments.

@param
int argc
char** argv
@return
int
@see libc/runtime/_init.S for documentation

ftruncate

Changes size of file.

@param
int fd
must be open for writing
long length
may be greater than current current file size, in which case System V guarantees it'll be zero'd but Windows NT doesn't; since the prior extends logically and the latter physically
@return
int
0 on success, or -1 w/ errno
@asyncsignalsafe

ftrylockfile

Does nothing since Cosmopolitan currently doesn't support threads.

@param
struct FILE* f
@return
int

funlockfile

Does nothing since Cosmopolitan currently doesn't support threads.

@param
struct FILE* f
@return
void

futimens

Sets atime/mtime on file descriptor.

@param
int fd
struct timespec* ts
is atime/mtime, or null for current time
@return
int
@note better than microsecond precision on most platforms
@see fstat() for reading timestamps

futimes

Sets atime/mtime on file descriptor.

@param
int fd
struct it_value* tv
@return
int
@note better than microsecond precision on most platforms
@see fstat() for reading timestamps

futimesat

Changes last accessed/modified times on file.

@param
int dirfd
char* pathname
struct it_value* tv
@return
int
0 on success or -1 w/ errno
@see utimensat() which uses nanos

__fwritable

Returns nonzero if stream allows reading.

@param
struct FILE* f
@return
int

fwrite

Writes data to stream.

@param
void* data
unsigned long stride
specifies the size of individual items
unsigned long count
is the number of strides to fetch
struct FILE* f
@return
unsigned long
count on success, [0,count) on EOF, 0 on error or count==0

__fwriting

Returns nonzero if stream is write only.

@param
struct FILE* f
@return
int

g_ddfmt

@param
char* buf
double* dd0
int ndig
unsigned long bufsize
@return
char*

g_ddfmt_p

@param
char* buf
double* dd0
int ndig
unsigned long bufsize
int nik
@return
char*

g_dfmt

@param
char* buf
double* d
int ndig
unsigned long bufsize
@return
char*

g_dfmt_p

@param
char* buf
double* d
int ndig
unsigned long bufsize
int nik
@return
char*

g_ffmt

@param
char* buf
float* f
int ndig
unsigned long bufsize
@return
char*

g_ffmt_p

@param
char* buf
float* f
int ndig
unsigned long bufsize
int nik
@return
char*

g_xfmt

@param
char* buf
void* V
int ndig
unsigned long bufsize
@return
char*

g_xfmt_p

@param
char* buf
void* V
int ndig
unsigned long bufsize
int nik
@return
char*

__gc

Invokes deferred function calls.

This offers behavior similar to std::unique_ptr. Functions overwrite their return addresses jumping here, and pushing exactly one entry on the shadow stack below. Functions may repeat that process multiple times, in which case the body of this gadget loops and unwinds as a natural consequence.

@param
rax,rdx,xmm0,xmm1,st0,st1
is return value
@return
@see test/libc/runtime/gc_test.c <LIMBO>

gclongjmp

Same as longjmp() but runs gc() / defer() destructors.

@return
void

gdbexec

Attachs GDB temporarilly, to do something like print a variable.

@param
char* cmd
@return
int

gdtoa

@param
struct FPI* fpi
int be
unsigned int* bits
int* kindp
int mode
int ndigits
int* decpt
char** rve
@return
char*

get_current_dir_name

Returns current working directory.

If the PWD environment variable is set, that'll be returned (since it's faster than issuing a system call).

@return
char*
pointer that must be free()'d, or NULL w/ errno

__get_virtual

Returns pointer to page table entry for page at virtual address. Additional page tables are allocated if needed as a side-effect.

@param
struct mman* mm
unsigned long* t
long vaddr
_Bool maketables
@return
unsigned long*


getaddrinfo

Resolves address for internet name.

@param
char* name
is either an ip string or a utf-8 hostname
char* service
is the port number as a string
struct addrinfo* hints
may be passed to specialize behavior (optional)
struct addrinfo** res
receives a pointer that must be freed with freeaddrinfo(), and won't be modified if -1 is returned
@return
int
0 on success or EAI_xxx value

getauxval

Returns 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
unsigned long at
@return
unsigned long
@see libc/sysv/consts.sh
@see System Five Application Binary Interface § 3.4.3
@asyncsignalsafe

getcachesize

Returns CPU cache size.

@param
int type
1=data, 2=instruction, 3=unified
int level
starts at 1
@return
unsigned int
size in bytes, or 0 if unknown

getchar

Reads uint8_t from standard input.

@return
%al has result w/ rest of %rax cleared

getcwd

Returns current working directory.

@param
char* buf
is where UTF-8 NUL-terminated path string gets written, which may be NULL to ask this function to malloc a buffer
unsigned long size
is number of bytes available in buf, e.g. PATH_MAX, which may be 0 if buf NULL
@return
char*
buf containing system-normative path or NULL w/ errno
@see get_current_dir_name() which is better
@error ERANGE, EINVAL

getdelim

Reads string from stream.

@param
char** line
is the caller's buffer (in/out) which is extended automatically. *line may be NULL but only if *n is 0; NUL-termination is guaranteed FTMP
unsigned long* n
is the capacity of line (in/out)
int delim
is the stop char (and NUL is implicitly too)
struct FILE* f
@return
long
number of bytes read, including delim, excluding NUL, or -1 w/ errno on EOF or error; see ferror() and feof()
@note this function can't punt EINTR to caller
@see getline(), gettok_r()

getdomainname

@param
char* name
unsigned long len
@return
int

GetDosArgv

Tokenizes and transcodes Windows NT CLI args, thus avoiding CommandLineToArgv() schlepping in forty megs of dependencies.

@param
unsigned short* cmdline
char* buf
is where we'll store double-NUL-terminated decoded args
unsigned long size
is how many bytes are available in buf
char** argv
is where we'll store the decoded arg pointer array, which is guaranteed to be NULL-terminated if max>0
unsigned long max
specifies the item capacity of argv, or 0 to do scanning
@return
int
number of args written, excluding the NULL-terminator; or, if the output buffer wasn't passed, or was too short, then the number of args that *would* have been written is returned; and there are currently no failure conditions that would have this return -1 since it doesn't do system calls
@see test/libc/dosarg_test.c
@see libc/runtime/ntspawn.c
@note kudos to Simon Tatham for figuring out quoting behavior

GetDosEnviron

Transcodes NT environment variable block from UTF-16 to UTF-8.

@param
unsigned short* env
is a double NUL-terminated block of key=values
char* buf
is the new environment which gets double-nul'd
unsigned long size
is the byte capacity of buf
char** envp
stores NULL-terminated string pointer list (optional)
unsigned long max
is the pointer count capacity of envp
@return
int
number of variables decoded, excluding NULL-terminator

GetElfSectionAddress

@param
struct Elf64_Ehdr* elf
unsigned long mapsize
struct Elf64_Shdr* shdr
@return
void*

GetElfSectionHeaderAddress

@param
struct Elf64_Ehdr* elf
unsigned long mapsize
unsigned short i
@return
struct Elf64_Shdr*

GetElfSectionName

@param
struct Elf64_Ehdr* elf
unsigned long mapsize
struct Elf64_Shdr* shdr
@return
char*

GetElfSectionNameStringTable

@param
struct Elf64_Ehdr* elf
unsigned long mapsize
@return
char*

GetElfSegmentHeaderAddress

@param
struct Elf64_Ehdr* elf
unsigned long mapsize
unsigned int i
@return
struct Elf64_Phdr*

GetElfString

@param
struct Elf64_Ehdr* elf
unsigned long mapsize
char* strtab
unsigned int rva
@return
char*

GetElfStringTable

@param
struct Elf64_Ehdr* elf
unsigned long mapsize
@return
char*

GetElfSymbolTable

@param
struct Elf64_Ehdr* elf
unsigned long mapsize
unsigned long* out_count
@return
struct Elf64_Sym*

GetElfVirtualAddressRange

@param
struct Elf64_Ehdr* elf
unsigned long elfsize
long* out_start
long* out_end
@return
void

getentropy

Returns random seeding bytes, the XNU/OpenBSD way.

@param
void* buf
unsigned long size
@return
int
@see getrandom()

getenv

Returns value of environment variable, or NULL if not found.

Environment variables can store empty string on Unix but not Windows.

@param
char* s
@return
char*

getfiledescriptorsize

Determines size of open file.

@param
int fd
@return
unsigned long
file byte length, or -1ul w/ errno
@asyncsignalsafe

GetFileSize

Returns the byte length of file by path.

@param
char* pathname
@return
unsigned long
number of bytes, or -1ul w/ errno
@see getfiledescriptorsize

GetGdbPath

@return
char*

getgid

Returns real group id of process.

This never fails. On Windows, which doesn't really have this concept, we return a deterministic value that's likely to work. On Linux, this is fast.

@return
unsigned int
@asyncsignalsafe

getgrent

@return
struct gr*

getgrgid

@param
unsigned int gid
@return
struct gr*

getgrgid_r

@param
unsigned int gid
struct gr* gr
char* buf
unsigned long size
struct gr** res
@return
int

getgrnam

@param
char* name
@return
struct gr*

getgrnam_r

@param
char* name
struct gr* gr
char* buf
unsigned long size
struct gr** res
@return
int

getgrouplist

@param
char* user
unsigned int gid
unsigned int* groups
int* ngroups
@return
int

gethostname

Returns name of host system, e.g.

pheidippides.domain.example
^^^^^^^^^^^^
@param
char* name
unsigned long len
@return
int

gethostname_bsd

@param
char* name
unsigned long len
@return
int

gethostname_linux

@param
char* name
unsigned long len
@return
int

gethostname_nt

@param
char* name
unsigned long len
@return
int

gethoststxt

Returns parsed sorted singleton hardcoded hostname→ip4 map.

@return
struct ht*
@note yoinking realloc() ensures there's no size limits

getitimer

Retrieves last setitimer() value, correcting for remaining time.

@param
int which
can be ITIMER_REAL, ITIMER_VIRTUAL, etc.
struct itimerval* curvalue
@return
int
0 on success or -1 w/ errno

getline

Reads 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
char** line
is the caller's buffer (in/out) which is extended automatically. *line may be NULL but only if *n is 0; NUL-termination is guaranteed FTMP
unsigned long* n
struct FILE* f
@return
long
number of bytes read, including delim, excluding NUL, or -1 w/ errno on EOF or error; see ferror() and feof()
@see xgetline(), getdelim(), gettok_r()

getntnameservers

Extracts DNS nameserver IPs from Windows Registry.

@param
struct ResolvConf* resolv
points to a ResolvConf object, which should be zero initialized by the caller; or if it already contains items, this function will append
@return
int
number of nameservers appended, or -1 w/ errno

__getntsyspath

Obtains WIN32 magic path, e.g. GetTempPathA.

@param
rax
is address of ANSI path provider function
rdi
is output buffer
rdx
is output buffer size in bytes that's >0
@return
eax is string length w/ NUL that's ≤ edx
rdi is rdi+edx

getopt

Parses argc/argv argument vector, e.g.

while ((opt = getopt(argc, argv, "hvx:")) != -1) {
  switch (opt) {
    case 'x':
      x = atoi(optarg);
      break;
    case 'v':
      ++verbose;
      break;
    case 'h':
      PrintUsage(EXIT_SUCCESS, stdout);
    default:
      PrintUsage(EX_USAGE, stderr);
  }
}
@param
int nargc
char** nargv
char* ostr
@return
int
@see optind
@see optarg

getpid

Returns process id.

@return
int
@asyncsignalsafe
@vforksafe

getppid

Returns parent process id.

@return
int
@asyncsignalsafe

getpriority

Returns nice value of thing.

@param
int which
can be PRIO_PROCESS, PRIO_PGRP, PRIO_USER
unsigned int who
is the pid, pgid, or uid (0 means current)
@return
int
value ∈ [-NZERO,NZERO) or -1 w/ errno
@see setpriority(), nice()

GetProcAddressModule

Returns address of function in a DLL that's already loaded.

@param
char* module
char* symbol
@return
void*

getpwent

@return
struct pw*

getpwnam

@param
char* name
@return
struct pw*

getpwnam_r

@param
char* name
struct pw* pw
char* buf
unsigned long size
struct pw** res
@return
int

getpwuid

@param
unsigned int uid
@return
struct pw*

getpwuid_r

@param
unsigned int uid
struct pw* pw
char* buf
unsigned long size
struct pw** res
@return
int

getrandom

Returns random bytes appropriate for random seeding.

@param
void* buf
unsigned long size
should be the smallest value that meets your requirements
unsigned int flags
may be GRND_{RANDOM,NONBLOCK}
@return
long
number of bytes copied on success; or -1 w/ errno, which indicates only that the request couldn't be serviced by the host kernel; this wrapper will still fill the buffer with random bytes from fallback sources no matter what

getresolvconf

Returns singleton with DNS server address.

@return
struct rv*

getrlimit

Gets resource limit for current process.

@param
int resource
can be RLIMIT_{CPU,FSIZE,DATA,STACK,CORE,RSS,etc.}
struct rlimit* rlim
receives result, modified only on success
@return
int
0 on success or -1 w/ errno
@see libc/sysv/consts.sh

getrusage

Returns resource usage statistics.

@param
int who
can be RUSAGE_{SELF,CHILDREN,THREAD}
struct rusage* usage
@return
int
0 on success, or -1 w/ errno

gets

@param
char* s
@return
char*

getsid

Creates session and sets the process group id.

@param
int pid
@return
unsigned int

GetSymbolTable

Returns debug binary symbol table, as global singleton.

@return
struct SymbolTable*
symbol table, or NULL w/ errno on first call

GetTempPathA_flunk

Calls GetTempPathA() w/ different API.

@return
@see GetSystemDirectoryA(), GetWindowsDirectoryA()

gettid

Returns current thread id.

@return
unsigned int
@asyncsignalsafe

gettimeofday

Returns system wall time in microseconds.

@param
struct it_value* tv
points to timeval that receives result if non-NULL
struct timezone* tz
receives UTC timezone if non-NULL
@return
int
always zero
@see clock_gettime() for nanosecond precision
@see strftime() for string formatting

getttycols

Shorthand 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
unsigned short defaultcols
@return
unsigned short
terminal width or defaultcols on error

getttysize

Returns 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
int fd
struct winsize* out
stores determined dimensions, only on success
@return
int
@returns -1 on error or something else on success

getuid

Returns real user id of process.

This never fails. On Windows, which doesn't really have this concept, we return a deterministic value that's likely to work. On Linux, this is fast.

@return
unsigned int
@asyncsignalsafe

getutf16

Decodes UTF-16 character.

@param
unsigned short* p
unsigned int* wc
@return
unsigned int
number of bytes (NUL counts as 1) or -1 w/ errno
@note synchronization is performed to skip leading continuations; canonicalization and validation are performed to some extent
@todo delete

getwchar

Reads Thompson-Pike encoded varint from standard input.

@return
%eax has result w/ rest of %rax cleared

getx86processormodel

Identifies microarchitecture of host processor.

@param
short key
can be kX86ProcessorModelKey for host info
@return
struct X86ProcessorModel*
@see https://en.wikichip.org/wiki/intel/cpuid
@see https://a4lg.com/tech/x86/database/x86-families-and-models.en.html

glob

Finds pathnames matching pattern.

For example:

glob_t g = {.gl_offs = 2};
glob("*.*", GLOB_DOOFFS, NULL, &g);
glob("../.*", GLOB_DOOFFS | GLOB_APPEND, NULL, &g);
g.gl_pathv[0] = "ls";
g.gl_pathv[1] = "-l";
execvp("ls", &g.gl_pathv[0]);
globfree(g);
@param
char* pat
can have star wildcard see fnmatch()
int flags
int(*)() errfunc
struct glob_t* g
will receive matching entries and needs globfree()
@return
int
0 on success or GLOB_NOMATCH, GLOB_NOSPACE on OOM, or GLOB_ABORTED on read error

globfree

Frees entries allocated by glob().

@param
struct glob_t* g
@return
void

gmtime

@param
long* timep
@return
struct mytm*

gmtime_r

@param
long* timep
struct mytm* tmp
@return
struct mytm*

grantpt

@param
int fd
@return
int

gray

Returns gray code for x.

@param
unsigned int x
@return
unsigned int
@see https://en.wikipedia.org/wiki/Gray_code
@see ungray()

__grow

Grows array.

@param
void* pp
unsigned long* capacity
unsigned long itemsize
unsigned long extra
@return
_Bool
@deprecated favor realloc

gzbuffer

Sets internal buffer size used by this library's functions. The default buffer size is 8192 bytes. This function must be called after gzopen() or gzdopen(), and before any other calls that read or write the file. The buffer memory allocation is always deferred to the first read or write. Three times that size in buffer space is allocated. A larger buffer size of, for example, 64K or 128K bytes will noticeably increase the speed of decompression (reading).

The new buffer size also affects the maximum length for gzprintf().

@return
int
Z_OK on success, or -1 on failure, such as being called too late.

gzclearerr

Clears the error and end-of-file flags for file. This is analogous to the clearerr() function in stdio. This is useful for continuing to read a gzip file that is being written concurrently.

@return
void

gzclose

Flushes all pending output if necessary, closes the compressed file and deallocates the (de)compression state. Note that once file is closed, you cannot call gzerror with file, since its structures have been deallocated. gzclose must not be called more than once on the same file, just as free must not be called more than once on the same allocation.

@return
int
Z_STREAM_ERROR if file is not valid, Z_ERRNO on a file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the last read ended in the middle of a gzip stream, or Z_OK on success.

gzclose_r

Same as gzclose(), but gzclose_r() is only for use when reading, and gzclose_w() is only for use when writing or appending. The advantage to using these instead of gzclose() is that they avoid linking in zlib compression or decompression code that is not used when only reading or only writing respectively. If gzclose() is used, then both compression and decompression code will be included the application when linking to a static zlib library.

@return
int

gzdirect

Returns true (1) if file is being copied directly while reading, or false (0) if file is a gzip stream being decompressed.

If the input file is empty, gzdirect() will return true, since the input does not contain a gzip stream.

If gzdirect() is used immediately after gzopen() or gzdopen() it will cause buffers to be allocated to allow reading the file to determine if it is a gzip file. Therefore if gzbuffer() is used, it should be called before gzdirect().

When writing, gzdirect() returns true (1) if transparent writing was requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: gzdirect() is not needed when writing. Transparent writing must be explicitly requested, so the application already knows the answer. When linking statically, using gzdirect() will include all of the zlib code for gzip file reading and decompression, which may not be desired.)

@return
int

gzdopen

Associates gzFile with the file descriptor.

File descriptors are obtained from calls like open, dup, creat, pipe or fileno (if the file has been previously opened with fopen). The mode parameter is as in gzopen.

The next call of gzclose on the returned gzFile will also close the file descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, mode);. The duplicated descriptor should be saved to avoid a leak, since gzdopen does not close fd if it fails. If you are using fileno() to get the file descriptor from a FILE *, then you will have to use dup() to avoid double-close()ing the file descriptor. Both gzclose() and fclose() will close the associated file descriptor, so they need to have different file descriptors.

@return
struct gzFile_s*
Z_OK if there was insufficient memory to allocate the gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided), or if fd is -1. The file descriptor is not used until the next gz* read, write, seek, or close operation, so gzdopen will not detect if fd is invalid (unless fd is -1).

gzeof

Returns true (1) if the end-of-file indicator has been set while reading, false (0) otherwise. Note that the end-of-file indicator is set only if the read tried to go past the end of the input, but came up short. Therefore, just like feof(), gzeof() may return false even if there is no more data to read, in the event that the last read request was for the exact number of bytes remaining in the input file. This will happen if the input file size is an exact multiple of the buffer size.

If gzeof() returns true, then the read functions will return no more data, unless the end-of-file indicator is reset by gzclearerr() and the input file has grown since the previous end of file was detected.

@return
int

gzerror

Returns the error message for the last error which occurred on the given compressed file. errnum is set to zlib error number. If an error occurred in the file system and not in the compression library, errnum is set to Z_ERRNO and the application may consult errno to get the exact error code.

The application must not modify the returned string. Future calls to this function may invalidate the previously returned string. If file is closed, then the string previously returned by gzerror will no longer be available.

gzerror() should be used to distinguish errors from end-of-file for those functions above that do not distinguish those cases in their return values.

@return
char*

gzflush

Flushes all pending output into the compressed file. The parameter flush is as in the deflate() function. The return value is the zlib error number (see function gzerror below). gzflush is only permitted when writing.

If the flush parameter is Z_FINISH, the remaining data is written and the gzip stream is completed in the output. If gzwrite() is called again, a new gzip stream will be started in the output. gzread() is able to read such concatenated gzip streams.

gzflush should be called only when strictly necessary because it will degrade compression if called too often.

@return
int

gzfread

Read up to nitems items of size size from file to buf, otherwise operating as gzread() does. This duplicates the interface of stdio's fread(), with size_t request and return types. If the library defines size_t, then size_t is identical to size_t. If not, then size_t is an unsigned integer type that can contain a pointer.

gzfread() returns the number of full items read of size size, or zero if the end of the file was reached and a full item could not be read, or if there was an error. gzerror() must be consulted if zero is returned in order to determine if there was an error. If the multiplication of size and nitems overflows, i.e. the product does not fit in a size_t, then nothing is read, zero is returned, and the error state is set to Z_STREAM_ERROR.

In the event that the end of file is reached and only a partial item is available at the end, i.e. the remaining uncompressed data length is not a multiple of size, then the final partial item is nevetheless read into buf and the end-of-file flag is set. The length of the partial item read is not provided, but could be inferred from the result of gztell(). This behavior is the same as the behavior of fread() implementations in common libraries, but it prevents the direct use of gzfread() to read a concurrently written file, reseting and retrying on end-of-file, when size is not 1.

@return
unsigned long

gzfwrite

Writes nitems items of size size from buf to file, duplicating the interface of stdio's fwrite(), with size_t request and return types. If the library defines size_t, then size_t is identical to size_t. If not, then size_t is an unsigned integer type that can contain a pointer.

gzfwrite() returns the number of full items written of size size, or zero if there was an error. If the multiplication of size and nitems overflows, i.e. the product does not fit in a size_t, then nothing is written, zero is returned, and the error state is set to Z_STREAM_ERROR.

@return
unsigned long

gzgetc

Reads one byte from the compressed file. gzgetc returns this byte or -1 in case of end of file or error. This is implemented as a macro for speed. As such, it does not do all of the checking the other functions do. I.e. it does not check to see if file is NULL, nor whether the structure file points to has been clobbered or not.

@return
int

gzgets

Reads bytes from the compressed file until len-1 characters are read, or a newline character is read and transferred to buf, or an end-of-file condition is encountered. If any characters are read or if len == 1, the string is terminated with a null character. If no characters are read due to an end-of-file or len < 1, then the buffer is left untouched.

@return
char*
buf which is a null-terminated string, or it returns NULL for end-of-file or in case of error. If there was an error, the contents at buf are indeterminate.

gzoffset

Returns current offset in the file being read or written. This offset includes the count of bytes that precede the gzip stream, for example when appending or when using gzdopen() for reading. When reading, the offset does not include as yet unused buffered input. This information can be used for a progress indicator. On error, gzoffset() returns -1.

@return
long

gzopen

Opens a gzip (.gz) file for reading or writing.

The mode parameter is as in fopen ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression as in "wb9F". (See the description of deflateInit2 for more information about the strategy parameter.) 'T' will request transparent writing or appending with no compression and not using the gzip format.

"a" can be used instead of "w" to request that the gzip stream that will be written be appended to the file. "+" will result in an error, since reading and writing to the same gzip file is not supported. The addition of "x" when writing will create the file exclusively, which fails if the file already exists. On systems that support it, the addition of "e" when reading or writing will set the flag to close the file on an execve() call.

These functions, as well as gzip, will read and decode a sequence of gzip streams in a file. The append function of gzopen() can be used to create such a file. (Also see gzflush() for another way to do this.) When appending, gzopen does not test whether the file begins with a gzip stream, nor does it look for the end of the gzip streams to begin appending. gzopen will simply append a gzip stream to the existing file.

gzopen can be used to read a file which is not in gzip format; in this case gzread will directly read from the file without decompression. When reading, this will be detected automatically by looking for the magic two- byte gzip header.

@return
struct gzFile_s*
Z_OK if the file could not be opened, if there was insufficient memory to allocate the gzFile state, or if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). errno can be checked to determine if the reason gzopen failed was that the file could not be opened.

gzprintf

Converts, formats, and writes the arguments to the compressed file under control of the format string, as in fprintf. gzprintf returns the number of uncompressed bytes actually written, or a negative zlib error code in case of error. The number of uncompressed bytes written is limited to 8191, or one less than the buffer size given to gzbuffer(). The caller should assure that this limit is not exceeded. If it is exceeded, then gzprintf() will return an error (0) with nothing written. In this case, there may also be a buffer overflow with unpredictable consequences, which is possible only if zlib was compiled with the insecure functions sprintf() or vsprintf() because the secure snprintf() or vsnprintf() functions were not available. This can be determined using zlibCompileFlags().

@param
...
@return
int

gzputc

Writes character converted to an unsigned char into compressed file.

@return
int
value that was written, or -1 on error

gzputs

Writes the given null-terminated string to the compressed file, excluding the terminating null character.

@return
int
Z_OK number of characters written, or -1 in case of error.

gzread

Reads given number of uncompressed bytes from the compressed file. If the input file is not in gzip format, gzread copies the given number of bytes into the buffer directly from the file.

After reaching the end of a gzip stream in the input, gzread will continue to read, looking for another gzip stream. Any number of gzip streams may be concatenated in the input file, and will all be decompressed by gzread(). If something other than a gzip stream is encountered after a gzip stream, that remaining trailing garbage is ignored (and no error is returned).

gzread can be used to read a gzip file that is being concurrently written. Upon reaching the end of the input, gzread will return with the available data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then gzclearerr can be used to clear the end of file indicator in order to permit gzread to be tried again. Z_OK indicates that a gzip stream was completed on the last gzread. Z_BUF_ERROR indicates that the input file ended in the middle of a gzip stream. Note that gzread does not return -1 in the event of an incomplete gzip stream. This error is deferred until gzclose(), which will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip stream. Alternatively, gzerror can be used before gzclose to detect this case.

@return
int
Z_OK number of uncompressed bytes actually read, less than len for end of file, or -1 for error. If len is too large to fit in an int, then nothing is read, -1 is returned, and the error state is set to Z_STREAM_ERROR.

gzrewind

Rewinds file.

This function is supported only for reading.

@return
int
@note gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)

gzseek

Sets starting position for the next gzread or gzwrite on the given compressed file. The offset represents a number of bytes in the uncompressed data stream. The whence parameter is defined as in lseek(2); the value SEEK_END is not supported.

If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position.

@return
long
resulting offset location as measured in bytes from the beginning of the uncompressed stream, or -1 in case of error, in particular if the file is opened for writing and the new starting position would be before the current position.

gzsetparams

Dynamically update the compression level or strategy. See the description of deflateInit2 for the meaning of these parameters. Previously provided data is flushed before the parameter change.

@return
int
Z_OK if success, Z_STREAM_ERROR if the file was not opened for writing, Z_ERRNO if there is an error writing the flushed data, or Z_MEM_ERROR if there is a memory allocation error.

gztell

Returns starting position for the next gzread or gzwrite on the given compressed file. This position represents a number of bytes in the uncompressed data stream, and is zero when starting, even if appending or reading a gzip stream from the middle of a file using gzdopen().

@return
long
@note gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)

gzungetc

Pushes one character back onto the stream to be read as the first character on the next read. At least one character of push-back is allowed. gzungetc() returns the character pushed, or -1 on failure. gzungetc() will fail if c is -1, and may fail if a character has been pushed but not read yet. If gzungetc is used immediately after gzopen or gzdopen, at least the output buffer size of pushed characters is allowed. (See gzbuffer above.) The pushed character will be discarded if the stream is repositioned with gzseek() or gzrewind().

@return
int

gzwrite

Writes given number of uncompressed bytes into the compressed file. gzwrite returns the number of uncompressed bytes written or 0 in case of error.

@return
int

hamming

Counts number of different bits.

@param
unsigned long x
unsigned long y
@return
unsigned long
@see https://en.wikipedia.org/wiki/Hamming_code

hextoint

Converts ASCII hexadecimal character to integer case-insensitively.

@param
int c
@return
int
integer or 0 if c ∉ [0-9A-Fa-f]

HighwayHash64

@param
unsigned char* data
unsigned long size
unsigned long* key
@return
unsigned long

hilbert

Generates Hilbert space-filling curve.

@param
long n
long y
long x
@return
long
@see https://en.wikipedia.org/wiki/Hilbert_curve
@see unhilbert()

__hook

Rewrites 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
void* ifunc
struct SymbolTable* symbols
@return
void
@see ape/ape.lds

hypot

Returns euclidean distance.

@param
double a
double b
@return
double

hypotf

Returns euclidean distance.

@param
float a
float b
@return
float

hypotl

Returns euclidean distance.

@param
long double a
long double b
@return
long double

iconv

@param
void* cd
char** in
unsigned long* inb
char** out
unsigned long* outb
@return
unsigned long

iconv_close

@param
void* cd
@return
int

iconv_open

@param
char* to
char* from
@return
void*

identity

The identity() function.

@return
first argument

ilogb

Returns log₂𝑥 exponent part of double.

@param
𝑥
is double passed in %xmm0
@return
result in %eax
@note needs sse3

ilogbf

Returns log₂x exponent part of float.

@param
𝑥
is float passed in %xmm0
@return
result in %eax
@note needs sse3

ilogbl

Returns log₂x exponent part of long double.

@param
𝑥
is long double passed on stack
@return
result in %eax
@note needs sse3

imapxlatab

Identity maps 256-byte translation table.

@param
char
(*rdi)[256]
@return
@speed 90mBps
@mode long

imaxabs

@param
__int128 x
@return
__int128

index

Returns pointer to first instance of character, the BSD way.

@param
char* s
is a NUL-terminated string
int c
@return
char*
is pointer to first instance of c or NULL if not found, noting that c being NUL will return a pointer to terminator

IndexDoubleNulString

@param
char* s
unsigned int i
@return
char*

inet_addr

Converts dotted IPv4 address string to network order binary.

@param
char* s
@return
unsigned int
@see inet_aton()

inet_aton

Converts dotted IPv4 address string to network order binary.

@param
char* s0
ANONYMOUS-STRUCT* dest
@return
int

inet_ntoa

Converts IPv4 network address to array.

@param
struct in in
@return
char*

inet_ntop

Formats internet address to string.

@param
int af
can be AF_INET
void* src
is the binary-encoded address, e.g. &addr->sin_addr
char* dst
is the output string buffer
unsigned int size
is bytes in dst, which needs 16+ for IPv4
@return
char*
dst on success or NULL w/ errno

inflate

inflate decompresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush.

The detailed semantics are as follows. inflate performs one or both of the following actions:

  • Decompress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), then next_in and avail_in are updated accordingly, and processing will resume at this point for the next call of inflate().
  • Generate more output starting at next_out and update next_out and avail_out accordingly. inflate() provides as much output as possible, until there is no more input data or no more space in the output buffer (see below about the flush parameter).
Before the call of inflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating the next_* and avail_* values accordingly. If the caller of inflate() does not provide both available input and available output space, it is possible that there will be no progress made. The application can consume the uncompressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of inflate(). If inflate 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.

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
int
Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if the end of the compressed data has been reached and all uncompressed output has been produced, Z_NEED_DICT if a preset dictionary is needed at this point, Z_DATA_ERROR if the input data was corrupted (input stream not conforming to the zlib format or incorrect check value, in which case strm->msg points to a string with a more specific error), Z_STREAM_ERROR if the stream structure was inconsistent (for example next_in or next_out was Z_NULL, or the state was inadvertently written over by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if no progress was possible or if there was not enough room in the output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and inflate() can be called again with more input and more output space to continue decompressing. If Z_DATA_ERROR is returned, the application may then call inflateSync() to look for a good compression block if a partial recovery of the data is to be attempted.

inflate_fast

Decodes 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 < 8
On 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 data
Some 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
struct z_stream* strm
unsigned int start
inflate() starting value for strm->avail_out
@return
void

inflate_table

Builds 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
enum type type
unsigned short* lens
unsigned int codes
struct here** table
unsigned int* bits
unsigned short* work
@return
int

inflateBack

inflateBack() does a raw inflate with a single call using a call-back interface for input and output. This is potentially more efficient than inflate() for file i/o applications, in that it avoids copying between the output and the sliding window by simply making the window itself the output buffer. inflate() can be faster on modern CPUs when used with large buffers. inflateBack() trusts the application to not change the output buffer passed by the output function, at least until inflateBack() returns.

inflateBackInit() must be called first to allocate the internal state and to initialize the state with the user-provided window buffer. inflateBack() may then be used multiple times to inflate a complete, raw deflate stream with each call. inflateBackEnd() is then called to free the allocated state.

A raw deflate stream is one with no zlib or gzip header or trailer. This routine would normally be used in a utility that reads zip or gzip files and writes out uncompressed files. The utility would decode the header and process the trailer on its own, hence this routine expects only the raw deflate stream to decompress. This is different from the default behavior of inflate(), which expects a zlib header and trailer around the deflate stream.

inflateBack() uses two subroutines supplied by the caller that are then called by inflateBack() for input and output. inflateBack() calls those routines until it reads a complete deflate stream and writes out all of the uncompressed data, or until it encounters an error. The function's parameters and return types are defined above in the in_func and out_func typedefs. inflateBack() will call in(in_desc, &buf) which should return the number of bytes of provided input, and a pointer to that input in buf. If there is no input available, in() must return zero -- buf is ignored in that case -- and inflateBack() will return a buffer error. inflateBack() will call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() should return zero on success, or non-zero on failure. If out() returns non-zero, inflateBack() will return with an error. Neither in() nor out() are permitted to change the contents of the window provided to inflateBackInit(), which is also the buffer that out() uses to write from. The length written by out() will be at most the window size. Any non-zero amount of input may be provided by in().

For convenience, inflateBack() can be provided input on the first call by setting strm->next_in and strm->avail_in. If that input is exhausted, then in() will be called. Therefore strm->next_in must be initialized before calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in must also be initialized, and then if strm->avail_in is not zero, input will initially be taken from strm->next_in[0 .. strm->avail_in - 1].

The in_desc and out_desc parameters of inflateBack() is passed as the first parameter of in() and out() respectively when they are called. These descriptors can be optionally used to pass any information that the caller- supplied in() and out() functions need to do their job.

On return, inflateBack() will set strm->next_in and strm->avail_in to pass back any unused input that was provided by the last in() call. The return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR if in() or out() returned an error, Z_DATA_ERROR if there was a format error in the deflate stream (in which case strm->msg is set to indicate the nature of the error), or Z_STREAM_ERROR if the stream was not properly initialized. In the case of Z_BUF_ERROR, an input or output error can be distinguished using strm->next_in which will be Z_NULL only if in() returned an error. If strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning non-zero. (in() will always be called before out(), so strm->next_in is assured to be defined if out() returns non-zero.) Note that inflateBack() cannot return Z_OK.

@return
int

inflateBackEnd

All memory allocated by inflateBackInit() is freed.

@return
int
Z_OK on success, or Z_STREAM_ERROR if the stream state was inconsistent.

inflateBackInit

Initialize internal stream state for decompression using inflateBack() calls. The fields zalloc, zfree and opaque in strm must be initialized before the call. If zalloc and zfree are Z_NULL, then the default library- derived memory allocation routines are used. windowBits is the base two logarithm of the window size, in the range 8..15. window is a caller supplied buffer of that size. Except for special applications where it is assured that deflate was used with small window sizes, windowBits must be 15 and a 32K byte window must be supplied to be able to decompress general deflate streams.

See inflateBack() for the usage of these routines.

@return
int
Z_OK on success, Z_STREAM_ERROR if any of the parameters are invalid, or Z_MEM_ERROR if the internal state could not be allocated.

inflateCopy

Sets the destination stream as a complete copy of the source stream.

This function can be useful when randomly accessing a large stream. The first pass through the stream can periodically record the inflate state, allowing restarting inflate at those points when randomly accessing the stream.

@return
int
Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and destination.

inflateEnd

All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output.

@return
int
Z_OK or Z_STREAM_ERROR if stream state inconsistent

inflateGetDictionary

Returns the sliding dictionary being maintained by inflate. dictLength is set to the number of bytes in the dictionary, and that many bytes are copied to dictionary. dictionary must have enough space, where 32768 bytes is always enough. If inflateGetDictionary() is called with dictionary equal to Z_NULL, then only the dictionary length is returned, and nothing is copied. Similary, if dictLength is Z_NULL, then it is not set.

@return
int
Z_OK on success, or Z_STREAM_ERROR if the stream state is inconsistent.

inflateGetHeader

inflateGetHeader() requests that gzip header information be stored in the provided gz_header structure. inflateGetHeader() may be called after inflateInit2() or inflateReset(), and before the first call of inflate(). As inflate() processes the gzip stream, head->done is zero until the header is completed, at which time head->done is set to one. If a zlib stream is being decoded, then head->done is set to -1 to indicate that there will be no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be used to force inflate() to return immediately after header processing is complete and before any actual data is decompressed.

The text, time, xflags, and os fields are filled in with the gzip header contents. hcrc is set to true if there is a header CRC. (The header CRC was valid if done is set to one.) If extra is not Z_NULL, then extra_max contains the maximum number of bytes to write to extra. Once done is true, extra_len contains the actual extra field length, and extra contains the extra field, or that field truncated if extra_max is less than extra_len. If name is not Z_NULL, then up to name_max characters are written there, terminated with a zero unless the length is greater than name_max. If comment is not Z_NULL, then up to comm_max characters are written there, terminated with a zero unless the length is greater than comm_max. When any of extra, name, or comment are not Z_NULL and the respective field is not present in the header, then that field is set to Z_NULL to signal its absence. This allows the use of deflateSetHeader() with the returned structure to duplicate the header. However if those fields are set to allocated memory, then the application will need to save those pointers elsewhere so that they can be eventually freed.

If inflateGetHeader is not used, then the header information is simply discarded. The header is always checked for validity, including the header CRC if present. inflateReset() will reset the process to discard the header information. The application would need to call inflateGetHeader() again to retrieve the header from the next gzip stream.

@return
int
Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent.

inflateInit

Initializes the internal stream state for decompression. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. In the current version of inflate, the provided input is not read or consumed. The allocation of a sliding window will be deferred to the first call of inflate (if the decompression does not complete on the first call). If zalloc and zfree are set to Z_NULL, inflateInit updates them to use default allocation functions.

@return
int
Z_OK if success, Z_MEM_ERROR if there was not enough memory, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit does not perform any decompression. Actual decompression will be done by inflate(). So next_in, and avail_in, next_out, and avail_out are unused and unchanged. The current implementation of inflateInit() does not process any header information -- that is deferred until inflate() is called.

inflateInit2

This is another version of inflateInit with an extra parameter. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller.

The windowBits parameter is the base two logarithm of the maximum window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. The default value is 15 if inflateInit is used instead. windowBits must be greater than or equal to the windowBits value provided to deflateInit2() while compressing, or it must be equal to 15 if deflateInit2() was not used. If a compressed stream with a larger window size is given as input, inflate() will return with the error code Z_DATA_ERROR instead of trying to allocate a larger window.

windowBits can also be zero to request that inflate use the window size in the zlib header of the compressed stream.

windowBits can also be -8..-15 for raw inflate. In this case, -windowBits determines the window size. inflate() will then process raw deflate data, not looking for a zlib or gzip header, not generating a check value, and not looking for any check values for comparison at the end of the stream. This is for use with other formats that use the deflate compressed data format such as zip. Those formats provide their own check values. If a custom format is developed using the raw deflate format for compressed data, it is recommended that a check value such as an Adler-32 or a CRC-32 be applied to the uncompressed data as is done in the zlib, gzip, and zip formats. For most applications, the zlib format should be used as is. Note that comments above on the use in deflateInit2() applies to the magnitude of windowBits.

windowBits can also be greater than 15 for optional gzip decoding. Add 32 to windowBits to enable zlib and gzip decoding with automatic header detection, or add 16 to decode only the gzip format (the zlib format will return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see below), inflate() will not automatically decode concatenated gzip streams. inflate() will return Z_STREAM_END at the end of the gzip stream. The state would need to be reset to continue decoding a subsequent gzip stream.

@return
int
Z_OK if success, Z_MEM_ERROR if there was not enough memory, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit2 does not perform any decompression apart from possibly reading the zlib header if present: actual decompression will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unused and unchanged.) The current implementation of inflateInit2() does not process any header information -- that is deferred until inflate() is called.

inflateMark

Returns two values, one in the lower 16 bits of the return value, and the other in the remaining upper bits, obtained by shifting the return value down 16 bits. If the upper value is -1 and the lower value is zero, then inflate() is currently decoding information outside of a block. If the upper value is -1 and the lower value is non-zero, then inflate is in the middle of a stored block, with the lower value equaling the number of bytes from the input remaining to copy. If the upper value is not -1, then it is the number of bits back from the current bit position in the input of the code (literal or length/distance pair) currently being processed. In that case the lower value is the number of bytes already emitted for that code.

A code is being processed if inflate is waiting for more input to complete decoding of the code, or if it has completed decoding but is waiting for more output space to write the literal or match data.

inflateMark() is used to mark locations in the input data for random access, which may be at bit positions, and to note those cases where the output of a code may span boundaries of random access blocks. The current location in the input stream can be determined from avail_in and data_type as noted in the description for the Z_BLOCK flush parameter for inflate.

@return
long
the value noted above, or -65536 if the provided source stream state was inconsistent.

inflatePrime

This function inserts bits in the inflate input stream. The intent is that this function is used to start inflating at a bit position in the middle of a byte. The provided bits will be used before any bytes are used from next_in. This function should only be used with raw inflate, and should be used before the first inflate() call after inflateInit2() or inflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the input.

If bits is negative, then the input stream bit buffer is emptied. Then inflatePrime() can be called again to put bits in the buffer. This is used to clear out bits leftover after feeding inflate a block description prior to feeding inflate codes.

@return
int
Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent.

inflateReset

This function is equivalent to inflateEnd followed by inflateInit, but does not free and reallocate the internal decompression state. The stream will keep attributes that may have been set by inflateInit2.

@return
int
Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL).

inflateReset2

This function is the same as inflateReset, but it also permits changing the wrap and window size requests. The windowBits parameter is interpreted the same as it is for inflateInit2. If the window size is changed, then the memory allocated for the window is freed, and the window will be reallocated by inflate() if needed.

@return
int
Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL), or if the windowBits parameter is invalid.

inflateSetDictionary

Initializes the decompression dictionary from the given uncompressed byte sequence. This function must be called immediately after a call of inflate, if that call returned Z_NEED_DICT. The dictionary chosen by the compressor can be determined from the Adler-32 value returned by that call of inflate. The compressor and decompressor must use exactly the same dictionary (see deflateSetDictionary). For raw inflate, this function can be called at any time to set the dictionary. If the provided dictionary is smaller than the window and there is already data in the window, then the provided dictionary will amend what's there. The application must insure that the dictionary that was used for compression is provided.

@return
int
Z_OK if success, Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the expected one (incorrect Adler-32 value). inflateSetDictionary does not perform any decompression: this will be done by subsequent calls of inflate().

inflateSync

Skips invalid compressed data until a possible full flush point (see above for the description of deflate with Z_FULL_FLUSH) can be found, or until all available input is skipped. No output is provided.

inflateSync searches for a 00 00 FF FF pattern in the compressed data. All full flush points have this pattern, but not all occurrences of this pattern are full flush points.

@return
int
Z_OK if a possible full flush point has been found, Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the success case, the application may save the current current value of total_in which indicates where valid compressed data was found. In the error case, the application may repeatedly call inflateSync, providing more input each time, until success or end of the input data.

_init

Decentralized function for process initialization.

Modules may inject cheap data structure initialization code into this function using the .init.start and .init.end macros. That code can use the LODS and STOS instructions to initialize memory that's restricted to read-only after initialization by PIRO.

This is fast, since the linker is able to roll-up initialization for large codebases comprised of many modules, into a perfectly linear order. It also enables a common pattern we use, which we call “Referencing Is Initialization” (RII).

C/C++ code should favor using ordinary constructors, since under normal circumstances the compiler will clobber RDI and RSI which are granted special meanings within this function.

@param
r12
is argc (still callee saved)
r13
is argv (still callee saved)
r14
is envp (still callee saved)
r15
is envp (still callee saved)
@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

__init_bss_start

Decentralized 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

__init_rodata_start

Decentralized section for packed data structures & initializers.

@return
@see .initro (libc/macros.internal.inc)
@see ape/ape.lds

_init_systemfive_jmptab

Initializes 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
%r15
is auxv
@return
@note OpenBSD devs: let us know if you start using auxv

insertionsort

Sorts array of signed 32-bit integers.

@param
int* a
unsigned long n
@return
void
@see djbsort()

int128toarray_radix10

Converts signed 128-bit integer to string.

@param
__int128 i
char* a
needs at least 41 bytes
@return
unsigned long
bytes written w/o nul

int64toarray

@param
long i
char* a
int r
@return
unsigned long

int64toarray_radix10

Converts signed 64-bit integer to string.

@param
long i
char* a
needs at least 21 bytes
@return
unsigned long
bytes written w/o nul

interruptiblecall

Calls function that may be cancelled by a signal.

@param
struct InterruptibleCall* icall
long(*)() callback
long p1
long p2
long p3
long p4
@return
long
the value returned by callback or -1 on interrupt; they may be differentiated using the state→returnval filed, which is only modified by this function when callbacks succeed

ioctl

Controls settings on device.

@param
int fd
unsigned long request
void* memory
@return
int
@vforksafe

ioctl_tcgets

Returns information about terminal.

@param
int fd
struct linux* tio
@return
int
@see tcgetattr(fd, tio) dispatches here
@see ioctl(fd, TCGETS, tio) dispatches here
@see ioctl(fd, TIOCGETA, tio) dispatches here

ioctl_tcgets_nt

@param
int ignored
struct termios* tio
@return
int

ioctl_tcsets

Changes terminal behavior.

@param
int fd
unsigned long request
struct linux* tio
@return
int
@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_tcsets_nt

@param
int ignored
unsigned long request
struct linux* tio
@return
int

ioctl_tiocgwinsz

Returns width and height of terminal.

@param
int fd
struct winsize* ws
@return
int
@see ioctl(fd, TIOCGWINSZ, ws) dispatches here

ioctl_tiocgwinsz_nt

@param
int fd
struct winsize* ws
@return
int

ioctl_tiocswinsz

Returns width and height of terminal.

@param
int fd
struct winsize* ws
@return
int
@see ioctl(fd, TIOCSWINSZ, ws) dispatches here

ioctl_tiocswinsz_nt

@param
int fd
struct winsize* ws
@return
int

isabspath

Returns 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
char* path
@return
_Bool

isalnum

Returns nonzero if c is lower, alpha, or digit.

@param
int c
@return
int

isalpha

Returns nonzero if c is upper or lower.

@param
int c
@return
int

isascii

Returns nonzero if c is ascii.

@param
int c
@return
int

isatty

Returns true if file descriptor is backed by a terminal device.

@param
int fd
@return
int
@asyncsignalsafe

isblank

Returns nonzero if c is space or tab.

@param
int c
@return
int

ischardev

Returns true if file descriptor is backed by character i/o.

@param
int fd
@return
int

iscntrl

Returns nonzero if c is C0 ASCII control code or DEL.

@param
int c
@return
int

IsDebuggerPresent

Determines if gdb, strace, windbg, etc. is controlling process.

@param
_Bool force
@return
int
non-zero if attached, otherwise 0

isdigit

Returns nonzero if c is decimal digit.

@param
int c
@return
int

isdirectory

Returns true if file exists and is a directory.

@param
char* path
@return
_Bool

IsElf64Binary

@param
struct Elf64_Ehdr* elf
unsigned long mapsize
@return
_Bool

IsElfSymbolContent

@param
struct Elf64_Sym* sym
@return
_Bool

isexecutable

Returns true if file exists and is executable.

@param
char* path
@return
_Bool
@see access(exe, X_OK) which is more accurate on NT
@asyncsignalsafe

isgraph

Returns nonzero if c is printable ascii that isn't space.

@param
int c
@return
int

isheap

Returns true if address isn't stack and was malloc'd or mmap'd.

@param
void* p
@return
_Bool
@assume stack addresses are always greater than heap addresses
@assume stack memory isn't stored beneath %rsp (-mno-red-zone)

islower

Returns nonzero if c is lowercase alpha ascii character.

@param
int c
@return
int

isprint

Returns nonzero if c is printable ascii including space.

@param
int c
@return
int

ispunct

Returns nonzero if c ∈ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

@param
int c
@return
int

isregularfile

Returns true if file exists and is a regular file

@param
char* path
@return
_Bool

IsRunningUnderMake

Returns true if current process was spawned by GNU Make.

@return
_Bool


isspace

Returns true if c is space, \t, \r, \n, \f, or \v.

@param
int c
@return
int

IsTerminalInarticulate

Checks if we're probably running inside Emacs.

@return
_Bool

isupper

Returns nonzero if c is uppercase alpha ascii character.

@param
int c
@return
int

iswalnum

@param
unsigned int wc
@return
int

iswalpha

@param
unsigned int wc
@return
int

iswblank

@param
unsigned int wc
@return
int

iswcntrl

Returns nonzero if wc is C0 or C1 control code.

@param
unsigned int wc
@return
int

iswctype

@param
unsigned int wc
unsigned int type
@return
int

iswdigit

@param
unsigned int wc
@return
int

iswgraph

@param
unsigned int wc
@return
int

iswlower

@param
unsigned int wc
@return
int

iswprint

@param
unsigned int wc
@return
int

iswpunct

@param
unsigned int wc
@return
int

iswspace

@param
unsigned int wc
@return
int

iswupper

@param
unsigned int wc
@return
int

iswxdigit

@param
unsigned int wc
@return
int

isxdigit

Returns true if c is hexadecimal digit.

@param
int c
@return
int

itoa

@param
int value
char* str
int radix
@return
char*

_jmpstack

Switches stack.

@param
rdi
is new rsp, passed as malloc(size) + size
rsi
is function to call in new stack space
rdx,rcx,r8,r9
get passed as args to rsi
@noreturn

kCp437

ibm cp437 unicode table w/ string literal safety

        ░▄██▒▄█ ▐██ ░░░     ▀▀████▒▀█▄
       ▐███▓██░ ██▌            ▀████▄■█▄
      ▐█▓███▀█░██▀   ░          ░▀█████▓▄
     ▐█▓██▀▄█▒██▀  ▄▄░  ▄▄▄ ░░░   ░▀████▒▄
    ▐████▀▄█■█▀      ▀▀             ░█████░
   ▐█▓█▀████▀          ░             ▐▓███▒
   █░███▀▀     ░░░    ▄█       ░░░    █████
  ▐█▓█░▀▀  ░░▄█▄▄▄▄▄  ▀▄ ▌▄▄▄░▄▄▄▄▄   ▐████░
  ▐███▌   ▄▀█████████▄ ▌▐▄████████▄   ▐▓███░
  ▐███░░░▀▄█▀▄▄████▄▀░  ▐████████▒ ▀   ░███░
  ░████░ ▓▀ ▄███████▀▌   ▀▄■████▀▀█▀   ██▀█
   ▓███░ ░▄▀▀░░░ ▀  ░░▌   ▄▀▀▄░░▀░▄▀▄ ▐██▀▄
   ░███░  ▄▓▓▄▄░▀▀█▀█ ▌░░  ▀█▀█▀▀     ▐██▀
 █▀▄▐██   ▀░░   ▄▀ ▐ █    ▀ ▄▄▄░     ░▀▄█▄▀█
 ▌▄  █▓ ▒      ░  █▄█▄▀▄▄▄███▄▀▄ ░░   ░ ▀  █▌
  █▌▄░▌      ░░░▄▀█▀███████▄▀▄▀▄▀▀▄▄▄  █▀█░▐
   ██▄     ░░░▄█▄▀██▄█■██████▄█▄█▄■▀█░  ▐░▐
    ▀██░   ░▄██████████████████▄█▄█ ░█ ░ ▄▀
    ▀▓█▄▓░░  ▒█▀█████████████████████▒ ██▀
     ▀███ ▓▒   ██████████████▀▀▀▀█▄▀ ░▄█▒
      ▀███ ▀█▄▀▄█████▀▀  ▓▓▓▄░   ▐  ░▄██
        ▀██ ▄███████▄████████▀░░   ░▄██
  ▄██▀▀▄ █▄▀▄██▒▒███████████▀▀▀▄░ ░███░
▄██▀▄▄░░▀▐▄████▄ █████▀▄░░█▀▄▀░░  ▄██░
█████▄▄▄███▀░█▌██▄▀▀█████▄▄░░░▄▄███▀██▄ ▄▀▀▀▄▄
 ▀██████▀■▄█▄▄ ░▀███████████████▓▓░░▄██▀▄████▄▄▀▄

█▀█ █  █▀█ █▀█ █▄▀ ▐▀█▀▌█▀█ █▀█ █▄ █ ▀█▀ █▀█ █▀▀
█▀▄ █  █ █ █   █ ▀▄  █  █▀▄ █ █ █ ▀█  █  █   ▀▀█
█▄█ █▄▌█▄█ █▄█ █  █  █  █ █ █▄█ █  █ ▄█▄ █▄█ █▄█

THERE WILL BE BLOCKS               march 01 2017
@return
@see libc/str/str.h
@see kCp437i[]

kCpuids

Teleports code fragment inside _init().

@type
unsigned int[4][7]

kill

Sends signal to process.

The impact of this action can be terminating the process, or interrupting it to request something happen.

@param
int pid
can be: >0 signals one process by id =0 signals all processes in current process group -1 signals all processes possible (except init) <-1 signals all processes in -pid process group
int sig
can be: >0 can be SIGINT, SIGTERM, SIGKILL, SIGUSR1, etc. =0 is for error checking
@return
int
0 if something was accomplished, or -1 w/ errno
@asyncsignalsafe

killpg

Sends signal to process group.

@param
int pgrp
int sig
@return
int

kNtSystemDirectory

RII constant holding 'C:/WINDOWS/SYSTEM32' directory.

@return
@note guarantees trailing slash if non-empty

kNtWindowsDirectory

RII constant holding 'C:/WINDOWS' directory.

@return
@note guarantees trailing slash if non-empty

kStartTsc

Stores CPU Timestamp Counter at startup.

It can be useful as an added source of seeding information.

@return
@note rdtsc is a 25 cycle instruction

kTmpPath

RII constant holding /tmp/ directory.

@return
@note on win32 this is firstNonNull($TMP, $TEMP, $PWD)
@note guarantees trailing slash if non-empty

kToLower

ASCII uppercase → lowercase translation tables.

char kToLower[256]; char16_t kToLower16[256];

@return
@note kToLower16 saves 128kb; CMOVcc can't even 8-bit

l64a

Converts 32-bit integer to base64.

@param
long x
@return
char*

labs

@param
long x
@return
long

lchown

Changes owner and/or group of pathname, w/o dereferencing symlinks.

@param
char* pathname
unsigned int uid
is user id, or -1u to not change
unsigned int gid
is group id, or -1u to not change
@return
int
0 on success, or -1 w/ errno
@see chown() which dereferences symbolic links
@see /etc/passwd for user ids
@see /etc/group for group ids

ldexp

Returns 𝑥 × 2ʸ.

@param
𝑥
is double passed in %xmm0
𝑦
is exponent via %edi
@return
double in %xmm0

ldexpf

Returns 𝑥 × 2ʸ.

@param
𝑥
is float passed in %xmm0
𝑦
is exponent via %edi
@return
float in %xmm0

ldexpl

Returns 𝑥 × 2ʸ.

@param
𝑥
is long double passed on stack
𝑦
is exponent via %edi
@return
result in %st0

ldiv

@param
long num
long den
@return
struct ldiv_t

lgamma

Returns natural logarithm of absolute value of gamma function.

@param
double x
@return
double

lgamma_r

@param
double x
int* signgamp
@return
double


llabs

@param
long x
@return
long

lldiv

@param
long num
long den
@return
struct lldiv_t

llog10

Fast log₁₀ when 𝑥 is an integer.

@param
rdi
is uint64 𝑥
@return
@domain 0<𝑥<2⁶⁴ ∧ 𝑥∊ℤ

llround

Rounds to nearest integer, away from zero.

@param
𝑥
is double scalar in low half of %xmm0
@return
64-bit signed integer in %rax
@see round(), lrint()

llroundf

Rounds to nearest integer, away from zero.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
64-bit signed integer in %rax
@see round()

loadxmm

Loads XMM registers from buffer.

@param
%rdi
points to &(forcealign(16) uint8_t[256])[128]
@return
@note modern cpus have out-of-order execution engines

localeconv

@return
struct kLocaleConv*

localtime

@param
long* timep
@return
struct mytm*

localtime_r

@param
long* timep
struct mytm* tmp
@return
struct mytm*

lockcmpxchg

Compares and exchanges w/ lock prefix.

@param
void* ifthing
is uint𝑘_t[hasatleast 1] where 𝑘 ∈ {8,16,32,64}
long isequaltome
long replaceitwithme
unsigned long size
is automatically supplied by macro wrapper
@return
_Bool
true if value was exchanged, otherwise false
@see cmpxchg()

lockxchg

Compares and exchanges w/ lock prefix.

@param
void* memory
is uint𝑘_t[hasatleast 1] where 𝑘 ∈ {8,16,32,64}
void* localvar
unsigned long size
is automatically supplied by macro wrapper
@return
long
true if value was exchanged, otherwise false
@see xchg()

log

Returns natural logarithm of 𝑥.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0

log10

Calculates log₁₀𝑥.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0

log10f

Calculates log₁₀𝑥.

@param
𝑥
is double scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0

log10l

Calculates log₁₀𝑥.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result in %st

log1p

Returns log(𝟷+𝑥).

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0

log1pf

Returns log(𝟷+𝑥).

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0

log1pl

Returns log(𝟷+𝑥).

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result of exponentiation on FPU stack in %st

log2

Calculates log₂𝑥.

@param
𝑥
is a double passed in the lower quadword of %xmm0
@return
result in lower quadword of %xmm0

log2f

Calculates log₂𝑥.

@param
𝑥
is a float passed in the lower quarter of %xmm0
@return
result in lower quarter of %xmm0

log2l

Calculates log₂𝑥.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result in %st
@see ilogbl()

__log_file

Log level for compile-time DCE.

@type
struct FILE*

logb

Returns log₂ₓ exponent part of double.

@param
𝑥
is double passed in %xmm0
@return
result in %xmm0

logbf

Returns log₂ₓ exponent part of float.

@param
𝑥
is float passed in %xmm0
@return
result in %xmm0

logbl

Returns log₂ₓ exponent part of long double.

@param
𝑥
is long double passed on stack
@return
result in %st0

logf

Returns natural logarithm of 𝑥.

@param
𝑥
is double scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0

logl

Returns natural logarithm of 𝑥.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result on FPU stack in %st

_longjmp

Loads previously saved processor state.

@param
rdi
points to the jmp_buf
esi
is returned by setjmp() invocation (coerced nonzero)
@noreturn
@assume system five nexgen32e abi conformant
@note code built w/ microsoft abi compiler can't call this
@see gclongjmp() unwinds gc() destructors

longjmp

Loads previously saved processor state.

@param
rdi
points to the jmp_buf
esi
is returned by setjmp() invocation (coerced nonzero)
@noreturn
@assume system five nexgen32e abi conformant
@note code built w/ microsoft abi compiler can't call this
@see gclongjmp() unwinds gc() destructors

lround

Rounds to nearest integer, away from zero.

@param
𝑥
is double scalar in low half of %xmm0
@return
64-bit signed integer in %rax
@see round(), lrint()

lroundf

Rounds to nearest integer, away from zero.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
64-bit signed integer in %rax
@see round()

lseek

Changes current position of file descriptor/handle.

@param
int fd
is a number returned by open()
long offset
is the relative byte count
unsigned int whence
can be SEEK_SET, SEEK_CUR, or SEEK_END
@return
long
new position relative to beginning, or -1 on error
@asyncsignalsafe

lstat

Returns information about file, w/o traversing symlinks.

@param
char* pathname
struct stat* st
@return
int
@asyncsignalsafe

lz4check

@param
void* data
@return
unsigned char*

lz4cpy

Decompresses LZ4 block.

This is a 103 byte implementation of the LZ4 algorithm. Please note LZ4 files are comprised of multiple frames, which may be decoded together using the wrapper function lz4decode().

@param
void* dest
void* blockdata
unsigned long blocksize
@return
void*
@see rldecode() for a 16-byte decompressor

lz4decode

Decompresses LZ4 file.

We assume (1) the file is mmap()'d or was copied into into memory beforehand; and (2) folks handling untrustworthy data shall place 64kb of guard pages on the ends of each buffer, see mapanon(). We don't intend to support XXHASH; we recommend folks needing checks against data corruption consider crc32c(), or gzip since it's the best at file recovery. Dictionaries are supported; by convention, they are passed in the ≤64kb bytes preceding src.

@param
void* dest
void* src
@return
void*
pointer to end of decoded data, similar to mempcpy()
@see mapanon(), lz4check()

lzcnt

Finds 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
edi
is 32-bit unsigned 𝑥 value
@return
eax number in range [0,32) or 32 if 𝑥 is 0
@see also treasure trove of nearly identical functions

lzcntl

Finds 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
rdi
is 64-bit unsigned 𝑥 value
@return
rax number in range [0,64) or 64 if 𝑥 is 0
@see also treasure trove of nearly identical functions

lzcntll

Finds 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
rdi
is 64-bit unsigned 𝑥 value
@return
rax number in range [0,64) or 64 if 𝑥 is 0
@see also treasure trove of nearly identical functions

madvise

Drops hints to O/S about intended access patterns of mmap()'d memory.

@param
void* addr
unsigned long length
int advice
can be MADV_WILLNEED, MADV_SEQUENTIAL, MADV_FREE, etc.
@return
int
0 on success, or -1 w/ errno
@see libc/sysv/consts.sh
@see fadvise()

makedirs

Recursively creates directory a.k.a. folder.

@param
char* path
is a UTF-8 string, preferably relative w/ forward slashes
unsigned int mode
can be, for example, 0755
@return
int
0 on success or -1 w/ errno
@see mkdir()

mallinfo

Returns (by copy) a struct containing various summary statistics:

  • arena: current total non-mmapped bytes allocated from system
  • ordblks: the number of free chunks
  • smblks: always zero.
  • hblks: current number of mmapped regions
  • hblkhd: total bytes held in mmapped regions
  • usmblks: the maximum total allocated space. This will be greater than current total if trimming has occurred.
  • fsmblks: always zero
  • uordblks: current total allocated space (normal or mmapped)
  • fordblks: total free space
  • keepcost: the maximum number of bytes that could ideally be released back to system via malloc_trim. ("ideally" means that it ignores page restrictions etc.)
Because these fields are ints, but internal bookkeeping may be kept as longs, the reported values may wrap around zero and thus be inaccurate.
@param
struct nm*
@return
struct nm

malloc

Allocates uninitialized memory.

Returns a pointer to a newly allocated chunk of at least n bytes, or null if no space is available, in which case errno is set to ENOMEM on ANSI C systems.

If n is zero, malloc returns a minimum-sized chunk. (The minimum size is 32 bytes on 64bit systems.) 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
rdi
is number of bytes needed
@return
new memory, or NULL w/ errno
@note malloc(0) → malloc(32)
@see dlmalloc()

malloc_footprint

Returns 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
unsigned long

malloc_footprint_limit

Returns 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
unsigned long

malloc_inspect_all

Traverses 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
void(*)() handler
void* arg
@return
void

malloc_max_footprint

Returns 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
unsigned long

malloc_set_footprint_limit

Sets 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
unsigned long bytes
@return
unsigned long


malloc_trim

Releases freed memory back to system.

@param
rdi
specifies bytes of memory to leave available
@return
1 if it actually released any memory, else 0

malloc_usable_size

Returns the number of bytes you can actually use in an allocated chunk, which may be more than you requested (although often not) due to alignment and minimum size constraints.

You can use this many bytes without worrying about overwriting other allocated objects. This is not a particularly great programming practice. malloc_usable_size can be more useful in debugging and assertions, for example:

p = malloc(n)
assert(malloc_usable_size(p) >= 256)
@param
rdi
is address of allocation
@return
rax is total number of bytes
@see dlmalloc_usable_size()

mallopt

Sets 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
int param_number
int value
@return
int

__map_phdrs

Maps APE-defined ELF program headers into memory and clears BSS.

@param
struct mman* mm
unsigned long* pml4t
unsigned long b
@return
void

mapanon

Helper function for allocating anonymous mapping.

This function is equivalent to:

mmap(NULL, mapsize, PROT_READ | PROT_WRITE,
     MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
Except it offers a small saving on code size.
@param
unsigned long mapsize
@return
void*

MarsagliaXorshift32

@param
unsigned int* state
@return
unsigned int

MarsagliaXorshift64

@param
unsigned long* state
@return
unsigned long

mbrtowc

@param
int* pwc
char* src
unsigned long n
unsigned int* ps
@return
unsigned long

mbsrtowcs

@param
int* dest
char** src
unsigned long len
unsigned int* ps
@return
unsigned long

mbstowcs

@param
int* pwc
char* s
unsigned long wn
@return
unsigned long

mbtowc

@param
int* wc
char* s
unsigned long n
@return
int

memalign

Allocates aligned memory.

Returns a pointer to a newly allocated chunk of n bytes, aligned in accord with the alignment argument. The alignment argument 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
rdi
is alignment in bytes
rsi
(newsize) is number of bytes needed
@return
rax is memory address, or NULL w/ errno
@note overreliance on memalign is a sure way to fragment space
@see dlmemalign()

memccpy

Copies at most N bytes from SRC to DST until 𝑐 is encountered.

This is little-known C Standard Library approach, dating back to the Fourth Edition of System Five, for copying a C strings to fixed-width buffers, with added generality.

For example, strictly:

char buf[16];
CHECK_NOTNULL(memccpy(buf, s, '\0', sizeof(buf)));
Or unstrictly:

if (!memccpy(buf, s, '\0', sizeof(buf))) strcpy(buf, "?");
Are usually more sensible than the following:

char cstrbuf[16];
snprintf(cstrbuf, sizeof(cstrbuf), "%s", CSTR);
@param
void* dst
void* src
int c
is search character and is masked with 255
unsigned long n
@return
void*
DST + idx(c) + 1, or NULL if 𝑐 ∉ 𝑠₀․․ₙ₋₁
@note DST and SRC can't overlap
@asyncsignalsafe

memchr

Returns pointer to first instance of character.

@param
void* m
is memory to search
int c
is search byte which is masked with 255
unsigned long n
is byte length of p
@return
void*
is pointer to first instance of c or NULL if not found
@asyncsignalsafe

memchr16

Returns pointer to first instance of character in range.

@param
rdi
is a non-null pointer to memory
esi
is the search word
rdx
is length of memory in shorts
@return
rax points to word if found or NULL
@asyncsignalsafe

memcmp

Compares memory.

@param
void* a
void* b
unsigned long n
@return
int
unsigned char subtraction at stop index
@asyncsignalsafe

memcpy

Copies memory.

DEST and SRC must not overlap, unless DEST≤SRC.

@param
rdi
is dest
rsi
is src
rdx
is number of bytes
@return
original rdi copied to rax
@mode long
@asyncsignalsafe

MemCpy

Copies memory w/ minimal impact ABI.

@param
rdi
is dest
rsi
is src
rdx
is number of bytes
@return
@clob flags,rcx,xmm3,xmm4
@mode long

memeqmask

Creates bit mask of which bytes are the same.

@param
%rdi
points to bit mask (write-only)
%rsi
points to first buffer (read-only)
%rdx
points to second buffer (read-only)
%rcx
is byte length of both %rsi and %rdx
@return
%rax is set to %rdi
@note buffers should be 128-byte aligned

memfrob

Memfrob implements a crypto algorithm proven to be unbreakable, without meeting its requirements concerning secrecy or length.

@param
void* buf
unsigned long size
@return
void*

meminfo

Prints memory mappings.

@param
int fd
@return
void

memjmpinit

Initializes jump table for memset() and memcpy().

@param
!ZF
if required cpu vector extensions are available
rdi
is address of 64-bit jump table
rsi
is address of 8-bit jump initializers
rdx
is address of indirect branch
ecx
is size of jump table
@return

memmem

Searches for fixed-length substring in memory region.

@param
void* haystack
is the region of memory to be searched
unsigned long haystacklen
is its character count
void* needle
contains the memory for which we're searching
unsigned long needlelen
is its character count
@return
void*
pointer to first result or NULL if not found

memmove

Copies memory.

DEST and SRC may overlap.

@param
rdi
is dest
rsi
is src
rdx
is number of bytes
@return
original rdi copied to rax
@clob flags,rcx
@asyncsignalsafe

memmove_pure

Copies memory.

DST and SRC may overlap.

@param
void* dst
is destination
void* src
is memory to copy
unsigned long n
is number of bytes to copy
@return
void*
dst
@asyncsignalsafe

mempcpy

Copies memory.

DEST and SRC must not overlap unless DEST ≤ SRC.

@param
rdi
is dest
rsi
is src
rdx
is number of bytes
@return
original rdi + rdx copied to rax

memrchr

Searches for last instance of byte in memory region.

@param
rdi
points to data to search
esi
is treated as unsigned char
rdx
is byte length of rdi
@return
rax is address of last %sil in %rdi, or NULL
@note AVX2 requires Haswell (2014+) or Excavator (2015+)
@asyncsignalsafe

memrchr16

Searches for last instance of uint16_t in memory region.

@param
rdi
points to data to search
esi
is treated as uint16_t
rdx
is short count in rdi
@return
rax is address of last %si in %rdi, or NULL
@note AVX2 requires Haswell (2014+) or Excavator (2015+)

memset

Sets memory.

@param
rdi
is dest
esi
is the byte to set
edx
is the number of bytes to set
@return
original rdi copied to rax
@mode long
@asyncsignalsafe

MemSet

Sets memory w/ minimal-impact ABI.

@param
rdi
is dest
esi
is the byte to set
edx
is the number of bytes to set
@return
@clob flags,rcx,xmm3
@mode long

memset16

Sets wide memory.

@param
unsigned short* dest
unsigned short c
unsigned long count
@return
unsigned short*
@asyncsignalsafe

memset_pure

Sets memory.

@param
void* p
is memory address
int c
is masked with 255 and used as repeated byte
unsigned long n
is byte length
@return
void*
p
@asyncsignalsafe

memsummary

@param
int fd
@return
void

MetalPrintf

Prints string to serial port.

This only supports %d and %s. It'll will work even if .rodata hasn't been loaded into memory yet.

@param
char* fmt
...
@return
void

mkdir

Creates directory a.k.a. folder.

mkdir o               →  0
mkdir o/yo/yo/yo      → -1 w/ ENOENT
if o/yo is file       → -1 w/ ENOTDIR
if o/yo/yo/yo is dir  → -1 w/ EEXIST
if o/yo/yo/yo is file → -1 w/ EEXIST
@param
char* path
is a UTF-8 string, preferably relative w/ forward slashes
unsigned int mode
can be, for example, 0755
@return
int
0 on success or -1 w/ errno
@error EEXIST, ENOTDIR, ENAMETOOLONG, EACCES
@asyncsignalsafe
@see makedirs()

mkdirat

Creates directory a.k.a. folder.

@param
int dirfd
is normally AT_FDCWD but if it's an open directory and path is relative, then path becomes relative to dirfd
char* path
is a UTF-8 string, preferably relative w/ forward slashes
unsigned int mode
can be, for example, 0755
@return
int
0 on success or -1 w/ errno
@error EEXIST, ENOTDIR, ENAMETOOLONG, EACCES, ENOENT
@asyncsignalsafe
@see makedirs()

mkfifo

Creates named pipe.

@param
char* pathname
unsigned int mode
is octal, e.g. 0600 for owner-only read/write
@return
int
@asyncsignalsafe

mknod

Creates filesystem inode.

@param
char* path
unsigned int mode
is octal mode, e.g. 0600; needs to be or'd with one of: S_IFDIR: directory S_IFIFO: named pipe S_IFREG: regular file S_IFSOCK: named socket S_IFBLK: block device (root has authorization) S_IFCHR: character device (root has authorization)
unsigned long dev
it's complicated
@return
int
0 on success, or -1 w/ errno
@asyncsignalsafe

mkntcmdline

Converts 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
unsigned short* cmdline
is output buffer
char* prog
is used as argv[0]
char** argv
is an a NULL-terminated array of UTF-8 strings
@return
int
freshly allocated lpCommandLine or NULL w/ errno
@kudos Daniel Colascione for teaching how to quote
@see libc/runtime/dosargv.c

mkntenvblock

Copies sorted environment variable block for Windows.

This is designed to meet the requirements of CreateProcess().

@param
unsigned short* envvars
receives sorted double-NUL terminated string list
char** envp
is an a NULL-terminated array of UTF-8 strings
char* extravar
is a VAR=val string we consider part of envp or NULL
@return
int
0 on success, or -1 w/ errno
@error E2BIG if total number of shorts exceeded ARG_MAX (0x8000)

__mkntpath2

Copies 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
char* path
unsigned short* path16
is shortened so caller can prefix, e.g. \\.\pipe\, and due to a plethora of special-cases throughout the Win32 API
int flags
is used by open()
@return
int
short count excluding NUL on success, or -1 w/ errno
@error ENAMETOOLONG

mkostemp

@param
char* template
unsigned int flags
@return
int

mkostemps

Delegates to mkotempsm() w/ owner-only non-execute access.

@param
char* template
int suffixlen
unsigned int flags
@return
int

mkostempsm

Opens unique temporary file.

The substring XXXXXX is replaced with a pseudorandom number that's seeded automatically and grants 30 bits of randomness to each value. Retries are made in the unlikely event of collisions.

@param
char* template
is a pathname relative to current directory by default, that needs to have "XXXXXX" at the end of the string
int suffixlen
may be nonzero to permit characters after the XXXXXX
unsigned int flags
can have O_APPEND, O_CLOEXEC, etc.
int mode
is conventionally 0600, for owner-only non-exec access
@return
int
exclusive open file descriptor for generated pathname, or -1 w/ errno
@see kTmpPath

mkostempsmi

@param
char* tpl
int slen
unsigned int flags
unsigned long* rando
int mode
int(*)() openit
@return
int

mkstemp

@param
char* template
@return
int

mkstemps

@param
char* template
int suffixlen
@return
int

mktemp

Generates 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
char* template
@return
char*

mktime

@param
struct mytm* tmp
@return
long

mmap

Beseeches system for page-table entries.

char *p = mmap(NULL, 65536, PROT_READ | PROT_WRITE,
               MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
munmap(p, 65536);
@param
void* addr
optionally requests a particular virtual base address, which needs to be 64kb aligned if passed (for NT compatibility)
unsigned long size
must be >0 and needn't be a multiple of FRAMESIZE
int prot
can have PROT_READ, PROT_WRITE, PROT_EXEC, PROT_NONE, etc.
int flags
can have MAP_ANONYMOUS, MAP_SHARED, MAP_PRIVATE, etc.
int fd
is an open()'d file descriptor whose contents shall be mapped, and is ignored if MAP_ANONYMOUS is specified
long off
specifies absolute byte index of fd's file for mapping, should be zero if MAP_ANONYMOUS is specified, and sadly needs to be 64kb aligned too
@return
void*
virtual base address of new mapping, or MAP_FAILED w/ errno

morton

Interleaves bits.

@param
unsigned long y
unsigned long x
@return
unsigned long
@see https://en.wikipedia.org/wiki/Z-order_curve
@see unmorton()

mprotect

Modifies restrictions on virtual memory address range.

@param
void* addr
unsigned long len
int prot
can have PROT_{NONE,READ,WRITE,EXEC,GROWSDOWN}
@return
int
0 on success, or -1 w/ errno
@see mmap()

mpsadbw

Computes 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
unsigned short* c
unsigned char* b
unsigned char* a
unsigned char control
@return
void
@note goes fast w/ sse4 cf. core c. 2006 cf. bulldozer c. 2011
@mayalias

__mpsadbws

Jump table for mpsadbw() with non-constexpr immediate parameter.

@return
@note needs sse4 cf. core c. 2006 cf. bulldozer c. 2011
@see mpsadbw()

mremap

@param
void* old_address
unsigned long old_size
unsigned long new_size
int flags
void* new_address
@return
void*

msync

Synchronize 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
void* addr
unsigned long size
int flags
needs MS_ASYNC or MS_SYNC and can have MS_INVALIDATE
@return
int
0 on success or -1 w/ errno

__mulvdi3

Returns 𝑥*𝑦, aborting on overflow.

@param
rdi
is int64 𝑥
rdi
is int64 𝑥
@return
rax is 𝑥*𝑦
@see -ftrapv

__mulvsi3

Returns 𝑥*𝑦, aborting on overflow.

@param
edi
is int32 𝑥
esi
is int32 𝑦
@return
eax is 𝑥*𝑦
@see -ftrapv

__mulvti3

Returns 𝑥*𝑦, aborting on overflow.

@param
rdi:rsi
is int128 𝑥
rdx:rcx
is int128 𝑦
@return
rdx:rax is 𝑥*𝑦
@see -ftrapv

munmap

Releases memory pages.

This function may be used to punch holes in existing mappings, but your mileage may vary on Windows.

@param
void* addr
is a pointer within any memory mapped region the process has permission to control, such as address ranges returned by mmap(), the program image itself, etc.
unsigned long size
is the amount of memory to unmap, which needs to be a multiple of FRAMESIZE for anonymous mappings, because windows and for files size needs to be perfect to the byte bc openbsd
@return
int
0 on success, or -1 w/ errno

nanosleep

Sleeps for a particular amount of time.

@param
struct st_ctim* req
struct st_ctim* rem
@return
int

__negvdi2

Returns -𝑥, aborting on overflow (two's complement bane).

@param
rdi
is int64 𝑥
@return
rax is -𝑥
@see -ftrapv

__negvsi2

Returns -𝑥, aborting on overflow (two's complement bane).

@param
edi
is int32 𝑥
@return
eax is -𝑥
@see -ftrapv

__negvti2

Returns -𝑥, aborting on overflow.

@param
rdi:rsi
is int128 𝑥
@return
rdx:rax is -𝑥
@see -ftrapv

__new_page

Allocates new page of physical memory.

@param
struct mman* mm
@return
unsigned long

newaddrinfo

@param
unsigned short port
@return
struct addrinfo*

nextafter

@param
double x
double y
@return
double

nextafterf

@param
float x
float y
@return
float

nextafterl

@param
long double x
long double y
@return
long double

nice

Changes process priority.

@param
int delta
is added to current priority w/ clamping
@return
int
new priority, or -1 w/ errno
@see Linux claims ioprio_set() is tuned automatically by this

nowl

Returns timestamp without needing system calls.

@return
seconds since unix epoch in %st0
@note uses microsecond scale fallback on k8 or vm

nowl_art

@return
long double

nowl_sys

@return
long double

__nt2sysv

Translates function call from code built w/ MS-style compiler.

This wraps WinMain() and callback functions passed to Win32 API. Please note an intermediary jump slot is needed to set %rax.

@param
%rax
is function address
@return
%rax,%xmm0
@note slower than __sysv2nt
@see NT2SYSV() macro

ntaccesscheck

Asks Microsoft if we're authorized to use a folder or file.

Implementation Details: MSDN documentation imposes no limit on the internal size of SECURITY_DESCRIPTOR, which we are responsible for allocating. We've selected 1024 which shall hopefully be adequate.

@param
unsigned short* pathname
unsigned int flags
can have R_OK, W_OK, X_OK, etc.
@return
int
0 if authorized, or -1 w/ errno
@kudos Aaron Ballman for teaching this
@see libc/sysv/consts.sh

ntcontext2linux

@param
struct ucontext_t* ctx
struct NtContext* cr
@return
void


ntoa

@param
int(*)() out
void* arg
struct __va_list* va
unsigned char signbit
unsigned long log2base
unsigned long prec
unsigned long width
unsigned char flags
char* lang
@return
int

ntoa2

@param
int(*)() out
void* arg
unsigned __int128 value
_Bool neg
unsigned int log2base
unsigned int prec
unsigned int width
unsigned int flags
char* alphabet
@return
int

ntreturn

Exitpoint for Windows NT system calls.

@param
unsigned int status
@return
long

ntsetprivilege

Sets NT permission thing, e.g.

int64_t htoken;
if (OpenProcessToken(GetCurrentProcess(),
                     kNtTokenAdjustPrivileges | kNtTokenQuery,
                     &htoken)) {
  ntsetprivilege(htoken, u"SeManageVolumePrivilege",
                 kNtSePrivilegeEnabled);
  CloseHandle(htoken);
}
@param
long token
unsigned short* name
unsigned int attrs
@return
int

ntspawn

Spawns process on Windows NT.

This function delegates to CreateProcess() with UTF-8 → UTF-16 translation and argv escaping. Please note this will NOT escape command interpreter syntax.

@param
char* prog
won't be PATH searched
char** argv
specifies prog arguments
char** envp
char* extravar
is added to envp to avoid setenv() in caller
struct kNtIsInheritable* opt_lpProcessAttributes
struct kNtIsInheritable* opt_lpThreadAttributes
int bInheritHandles
means handles already marked inheritable will be inherited; which, assuming the System V wrapper functions are being used, should mean (1) all files and sockets that weren't opened with O_CLOEXEC; and (2) all memory mappings
unsigned int dwCreationFlags
unsigned short* opt_lpCurrentDirectory
struct NtStartupInfo* lpStartupInfo
struct NtProcessInformation* opt_out_lpProcessInformation
can be used to return process and thread IDs to parent, as well as open handles that need close()
@return
int
0 on success, or -1 w/ errno
@see spawnve() which abstracts this function

offset2overlap

@param
long opt_offset
struct NtOverlapped* mem
@return
struct NtOverlapped*

__on_arithmetic_overflow

Arithmetic overflow handler.

@return
@see -ftrapv

__oncrash

Crashes in a developer-friendly human-centric way.

We first try to launch GDB if it's an interactive development session. Otherwise we show a really good crash report, sort of like Python, that includes filenames and line numbers. Many editors, e.g. Emacs, will even recognize its syntax for quick hopping to the failing line. That's only possible if the the .com.dbg file is in the same folder. If the concomitant debug binary can't be found, we simply print addresses which may be cross-referenced using objdump.

This function never returns, except for traps w/ human supervision.

@param
int sig
struct siginfo_t* si
struct ucontext_t* ctx
@return
void

__onfork

Triggers callbacks registered by atfork().

@return
void
@note only fork() should call this
@asyncsignalsafe

open

Opens file.

@param
char* file
is a UTF-8 string, preferably relative w/ forward slashes
int flags
should be O_RDONLY, O_WRONLY, or O_RDWR, and can be or'd with O_CREAT, O_TRUNC, O_APPEND, O_EXCL, O_CLOEXEC, O_TMPFILE
...
@return
int
number needing close(), or -1 w/ errno
@asyncsignalsafe
@vforksafe

openanon

Creates anonymous file.

@param
char* name
is purely informative
unsigned int flags
can have O_CLOEXEC
@return
int
fd of file with no name, needing close(), or -1 w/ errno
@see memfd_create() if disk-paranoid
@see mkostempsm() for named files

openat

Opens file.

@param
int dirfd
is normally AT_FDCWD but if it's an open directory and file is a relative path, then file is opened relative to dirfd
char* file
is a UTF-8 string, preferably relative w/ forward slashes
int flags
should be O_RDONLY, O_WRONLY, or O_RDWR, and can be or'd with O_CREAT, O_TRUNC, O_APPEND, O_EXCL, O_CLOEXEC, O_TMPFILE
...
@return
int
number needing close(), or -1 w/ errno
@asyncsignalsafe
@vforksafe

opendir

Opens directory, e.g.

DIR *d;
struct dirent *e;
CHECK((d = opendir(path)));
while ((e = readdir(d))) {
  printf("%s/%s\n", path, e->d_name);
}
LOGIFNEG1(closedir(d));
@param
char* name
@return
struct dirstream*
@returns newly allocated DIR object, or NULL w/ errno
@errors ENOENT, ENOTDIR, EACCES, EMFILE, ENFILE, ENOMEM
@see glob()

openpty

Opens new pseudo teletypewriter.

@param
int* ilduce
receives controlling tty rw fd on success
int* aworker
receives subordinate tty rw fd on success
char* name
struct termios* termp
may be passed to tune a century of legacy behaviors
struct winsize* winp
may be passed to set terminal display dimensions
@return
int
file descriptor, or -1 w/ errno
@params flags is usually O_RDWR|O_NOCTTY

OpenSymbolTable

Maps debuggable binary into memory and indexes symbol addresses.

@param
char* filename
@return
struct SymbolTable*
object freeable with CloseSymbolTable(), or NULL w/ errno

optarg

Argument associated with option.

@type
char*
@see getopt()

opterr

If error message should be printed.

@type
int
@see getopt()

optind

Index into parent argv vector.

@type
int
@see getopt()

optopt

Character checked for validity.

@type
int
@see getopt()

optreset

Reset getopt.

@type
int
@see getopt()

pabsb

Converts signed bytes to absolute values, 𝑎ᵢ ← |𝑏ᵢ|.

@param
unsigned char* a
char* b
@return
void
@note goes fast w/ ssse3 (intel c. 2004, amd c. 2011)

pabsd

Converts shorts to absolute values, 𝑎ᵢ ← |𝑏ᵢ|.

@param
unsigned int* a
int* b
@return
void
@note goes fast w/ ssse3 (intel c. 2004, amd c. 2011)

pabsw

Converts shorts to absolute values, 𝑎ᵢ ← |𝑏ᵢ|.

@param
unsigned short* a
short* b
@return
void
@note goes fast w/ ssse3 (intel c. 2004, amd c. 2011)

packssdw

Casts ints to shorts w/ saturation.

@param
short* a
int* b
int* c
@return
void
@mayalias

packsswb

Casts shorts to signed chars w/ saturation.

𝑎 ← {CLAMP[𝑏ᵢ]|𝑖∈[0,4)} ║ {CLAMP[𝑐ᵢ]|𝑖∈[4,8)}

@param
char* a
short* b
short* c
@return
void
@see packuswb()
@mayalias

packusdw

Casts ints to shorts w/ saturation.

@param
unsigned short* a
int* b
int* c
@return
void
@mayalias

packuswb

Casts shorts to unsigned chars w/ saturation.

𝑎 ← {CLAMP[𝑏ᵢ]|𝑖∈[0,4)} ║ {CLAMP[𝑐ᵢ]|𝑖∈[4,8)}

@param
unsigned char* a
short* b
short* c
@return
void
@see packsswb()
@mayalias

paddb

Adds 8-bit integers.

@param
char* a
char* b
char* c
@return
void
@mayalias

paddd

Adds 32-bit integers.

@param
int* a
int* b
int* c
@return
void
@mayalias

paddq

Adds 64-bit integers.

@param
long* a
long* b
long* c
@return
void
@mayalias

paddsb

Adds signed 8-bit integers w/ saturation.

@param
char* a
char* b
char* c
@return
void
@mayalias

paddsw

Adds signed 16-bit integers w/ saturation.

@param
short* a
short* b
short* c
@return
void
@mayalias

paddusb

Adds unsigned 8-bit integers w/ saturation.

@param
unsigned char* a
unsigned char* b
unsigned char* c
@return
void
@mayalias

paddusw

Adds unsigned 16-bit integers w/ saturation.

@param
unsigned short* a
unsigned short* b
unsigned short* c
@return
void
@mayalias

paddw

Adds 16-bit integers.

@param
short* a
short* b
short* c
@return
void
@note shorts can't overflow so ubsan won't report it when it happens
@see paddsw()
@mayalias

palandprintf

Implements {,v}{,s{,n},{,{,x}as},f,d}printf domain-specific language.

Type Specifiers

  • %s char * (thompson-pike unicode)
  • %ls wchar_t * (32-bit unicode → thompson-pike unicode)
  • %hs char16_t * (16-bit unicode → thompson-pike unicode)
  • %b int (radix 2 binary)
  • %o int (radix 8 octal)
  • %d int (radix 10 decimal)
  • %x int (radix 16 hexadecimal)
  • %X int (radix 16 hexadecimal uppercase)
  • %u unsigned
  • %f double
  • %Lf long double
  • %p pointer (48-bit hexadecimal)
Size Modifiers

  • %hhd char (8-bit)
  • %hd short (16-bit)
  • %ld long (64-bit)
  • %lu unsigned long (64-bit)
  • %lx unsigned long (64-bit hexadecimal)
  • %jd intmax_t (128-bit)
Width Modifiers

  • %08d fixed columns w/ zero leftpadding
  • %8d fixed columns w/ space leftpadding
  • %*s variable column string (thompson-pike)
Precision Modifiers

  • %.8s supplied byte length (obeys nul terminator)
  • %.*s supplied byte length argument (obeys nul terminator)
  • %`.*s supplied byte length argument c escaped (ignores nul term)
  • %#.*s supplied byte length argument visualized (ignores nul term)
  • %.*hs supplied char16_t length argument (obeys nul terminator)
  • %.*ls supplied wchar_t length argument (obeys nul terminator)
Formatting Modifiers

  • %,d thousands separators
  • %'s escaped c string literal
  • %`c c escaped character
  • %`'c c escaped character quoted
  • %`s c escaped string
  • %`'s c escaped string quoted
  • %`s escaped double quoted c string literal
  • %`c escaped double quoted c character literal
  • %+d plus leftpad if positive (aligns w/ negatives)
  • % d space leftpad if positive (aligns w/ negatives)
  • %#s datum (radix 256 null-terminated ibm cp437)
  • %#x int (radix 16 hexadecimal w/ 0x prefix if not zero)
@param
void* fn
void* arg
char* format
struct __va_list* va
@return
int
@note implementation detail of printf(), snprintf(), etc.
@see printf() for wordier documentation
@asyncsignalsafe
@vforksafe

palignr

Overlaps vectors.

𝑖= 0 means 𝑐←𝑎
0<𝑖<16 means 𝑐←𝑎║𝑏
𝑖=16 means 𝑐←𝑏
16<𝑖<32 means 𝑐←𝑏║0
𝑖≥32 means 𝑐←0
@param
void* c
void* b
void* a
unsigned long i
@return
void
@note not compatible with mmx
@see pvalignr()
@mayalias

__palignrs

Jump table for palignr() with non-constexpr immediate parameter.

@return
@note needs ssse3 cf. prescott c. 2004 cf. bulldozer c. 2011
@see palignr()

pand

Ands 128-bit integers.

@param
unsigned long* a
unsigned long* b
unsigned long* c
@return
void
@mayalias

pandn

Nands 128-bit integers.

@param
unsigned long* a
unsigned long* b
unsigned long* c
@return
void
@mayalias

parsehoststxt

Parses HOSTS.TXT contents.

Hostnames were invented by Peggy Karp; her format looks like this:

# this is a comment
# IP            CANON [ALT...]
203.0.113.1     lol.example. lol
203.0.113.2     cat.example. cat
@param
struct HostsTxt* ht
struct FILE* f
is the file content; see fopen() and fmemopen()
@return
int
0 on success, or -1 w/ errno
@see hoststxtsort() which is the logical next step

parseport

@param
char* service
@return
int

parseresolvconf

Parses /etc/resolv.conf file.

The content of the file usually looks like this:

nameserver 8.8.8.8
nameserver 8.8.4.4
@param
struct ResolvConf* resolv
points to a ResolvConf object, which should be zero initialized by the caller; or if it already contains items, this function will append
struct FILE* f
is an open stream with file content
@return
int
number of nameservers appended, or -1 w/ errno

pascalifydnsname

Writes dotted hostname to DNS message wire.

The wire format is basically a sequence of Pascal strings, for each label in the name. We only do enough validation to maintain protocol invariants.

@param
unsigned char* buf
unsigned long size
char* name
is a dotted NUL-terminated hostname string
@return
int
bytes written (excluding NUL) or -1 w/ errno

pause

Waits 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
int
should always be -1 w/ EINTR
@see sigsuspend()

pavgb

Averages packed 8-bit unsigned integers w/ rounding.

@param
unsigned char* a
unsigned char* b
unsigned char* c
@return
void
@mayalias

pavgw

Averages packed 16-bit unsigned integers w/ rounding.

@param
unsigned short* a
unsigned short* b
unsigned short* c
@return
void
@mayalias

pclose

Closes stream created by popen().

@param
struct FILE* f
@return
int
termination status of subprocess, or -1 w/ ECHILD

pcmpeqb

Compares signed 8-bit integers w/ equal to predicate.

@param
unsigned char* a
unsigned char* b
unsigned char* c
@return
void
@mayalias

pcmpeqd

Compares signed 32-bit integers w/ equal to predicate.

@param
int* a
int* b
int* c
@return
void
@mayalias

pcmpeqw

Compares signed 16-bit integers w/ equal to predicate.

@param
short* a
short* b
short* c
@return
void
@mayalias

pcmpgtb

Compares signed 8-bit integers w/ greater than predicate.

Note that operands can be xor'd with 0x80 for unsigned compares.

@param
char* a
char* b
char* c
@return
void
@mayalias

pcmpgtd

Compares signed 32-bit integers w/ greater than predicate.

@param
int* a
int* b
int* c
@return
void
@mayalias

pcmpgtw

Compares signed 16-bit integers w/ greater than predicate.

@param
short* a
short* b
short* c
@return
void
@mayalias

pdep

Parallel bit deposit.

@param
unsigned long x
unsigned long mask
@return
unsigned long

perror

Writes error messages to standard error.

@param
char* message
@return
void

pext

Parallel bit extract.

@param
unsigned long x
unsigned long mask
@return
unsigned long

phaddd

Adds adjacent 32-bit integers.

@param
int* a
int* b
int* c
@return
void
@note goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@mayalias

phaddsw

Adds adjacent shorts w/ saturation.

@param
short* a
short* b
short* c
@return
void
@note goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@mayalias

phaddw

Adds adjacent 16-bit integers.

@param
short* a
short* b
short* c
@return
void
@note goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@mayalias

phsubd

Subtracts adjacent 32-bit integers.

@param
int* a
int* b
int* c
@return
void
@note goes fast w/ ssse3
@mayalias

phsubsw

Subtracts adjacent shorts w/ saturation.

@param
short* a
short* b
short* c
@return
void
@note goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@mayalias

phsubw

Subtracts adjacent 16-bit integers.

@param
short* a
short* b
short* c
@return
void
@note goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@mayalias

pipe

Creates file-less file descriptors for interprocess communication.

@param
int* pipefd
@return
int
0 on success or -1 w/ errno
@asyncsignalsafe
@see pipe2()

pipe2

Creates file-less file descriptors for interprocess communication.

@param
int* pipefd
is used to return (reader, writer) file descriptors
int flags
can have O_CLOEXEC, O_NONBLOCK, O_DIRECT
@return
int
0 on success, or -1 w/ errno and pipefd isn't modified

pmaddubsw

Multiplies bytes and adds adjacent results w/ short saturation.

𝑤ᵢ ← CLAMP[ 𝑏₂ᵢ𝑐₂ᵢ + 𝑏₍₂ᵢ₊₁₎𝑐₍₂ᵢ₊₁₎ ]
@param
short* w
unsigned char* b
char* c
@return
void
@note SSSE3 w/ Prescott c. 2004, Bulldozer c. 2011
@note greatest simd op, like, ever
@mayalias

pmaddwd

Multiplies 16-bit signed integers and adds adjacent results.

@param
int* a
short* b
short* c
@return
void
@mayalias

pmaxsw

Gets maximum of signed 16-bit integers.

@param
short* a
short* b
short* c
@return
void
@mayalias

pmaxub

Returns minimum of 8-bit unsigned integers.

@param
unsigned char* a
unsigned char* b
unsigned char* c
@return
void
@mayalias

pminsw

Gets minimum of signed 16-bit integers.

@param
short* a
short* b
short* c
@return
void
@mayalias

pminub

Returns minimum of 8-bit unsigned integers.

@param
unsigned char* a
unsigned char* b
unsigned char* c
@return
void
@mayalias

pmovmskb

Turns result of byte comparison into bitmask.

@param
unsigned char* p
@return
unsigned int
@see pcmpeqb(), bsf(), etc.

pmulhrsw

Multiplies Q15 numbers.

@param
short* a
short* b
short* c
@return
void
@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

pmulhuw

Multiplies 16-bit unsigned integers and stores high word.

@param
unsigned short* a
unsigned short* b
unsigned short* c
@return
void
@mayalias

pmulhw

Multiplies 16-bit signed integers and stores high word.

@param
short* a
short* b
short* c
@return
void
@mayalias

pmulld

Multiplies 32-bit signed integers.

@param
int* a
int* b
int* c
@return
void
@see pmuludq()
@mayalias

pmullw

Multiplies 16-bit signed integers.

@param
short* a
short* b
short* c
@return
void
@mayalias

pmuludq

Multiplies 32-bit unsigned integers w/ promotion.

@param
unsigned long* a
unsigned int* b
unsigned int* c
@return
void
@see pmulld()
@mayalias

pochisq

@param
double ax
int df
@return
double

popcnt

Returns number of bits set in integer.

@param
unsigned long x
@return
unsigned long

popen

Spawns subprocess and returns pipe stream.

@param
char* cmdline
char* mode
@return
struct FILE*
@see pclose()

por

Ors 128-bit integers.

@param
unsigned long* a
unsigned long* b
unsigned long* c
@return
void
@mayalias

posix2time

@param
long t
@return
long

posix_fadvise

@param
int fd
unsigned long offset
unsigned long len
int advice
@return
int

posix_madvise

@param
void* addr
unsigned long len
int advice
@return
int

posix_memalign

Allocates aligned memory the POSIX way.

Allocates a chunk of n bytes, aligned in accord with the alignment argument. Differs from memalign only in that it (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
rdi
is void **pp
rsi
is size_t align
rdx
is size_t size
@return
eax

posix_openpt

Opens new pseudo teletypewriter.

@param
int flags
@return
int
file descriptor, or -1 w/ errno
@params flags is usually O_RDWR|O_NOCTTY

pow

Returns 𝑥^𝑦.

@param
𝑥
is double scalar in low half of %xmm0
𝑦
is double scalar in low half of %xmm1
@return
double scalar in low half of %xmm0

pow10

Returns 10^x.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0
@see pow(), exp()

pow10f

Returns 10^x.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0

pow10l

Returns 10^x.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result of exponentiation on FPU stack in %st

__pow_finite

Returns 𝑥^𝑦.

@param
𝑥
is double scalar in low half of %xmm0
𝑦
is double scalar in low half of %xmm1
@return
double scalar in low half of %xmm0

powf

Returns 𝑥^𝑦.

@param
𝑦
is float scalar in low quarter of %xmm0
𝑥
is float scalar in low quarter of %xmm1
@return
float scalar in low quarter of %xmm0

__powf_finite

Returns 𝑥^𝑦.

@param
𝑦
is float scalar in low quarter of %xmm0
𝑥
is float scalar in low quarter of %xmm1
@return
float scalar in low quarter of %xmm0

powi

Returns 𝑥^𝑦.

@param
𝑥
is double scalar in low half of %xmm0
𝑦
is int passed in %edi
@return
double scalar in low half of %xmm0

powif

Returns 𝑥^𝑦.

@param
𝑥
is float scalar in low quarter of %xmm0
𝑦
is int passed in %edi
@return
double scalar in low half of %xmm0

powil

Returns 𝑥^𝑦.

@param
𝑥
is long double passed on stack
𝑦
is int passed in %edi
@return
%st

pread

Reads from file at offset, thus avoiding superfluous lseek().

@param
int fd
is something open()'d earlier, noting pipes might not work
void* buf
is copied into, cf. copy_file_range(), sendfile(), etc.
unsigned long size
in range [1..0x7ffff000] is reasonable
long offset
is bytes from start of file at which read begins
@return
long
[1..size] bytes on success, 0 on EOF, or -1 w/ errno; with exception of size==0, in which case return zero means no error
@see pwrite(), write()
@asyncsignalsafe
@vforksafe

preadv

Reads data from multiple buffers from file descriptor at offset.

@param
int fd
struct iovec* iovec
int count
is recommended to be 16 or fewer; if it exceeds IOV_MAX then the extra buffers are simply ignored
long off
@return
long
number of bytes actually read, or -1 w/ errno
@asyncsignalsafe
@vforksafe

__print

Prints 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
void* data
unsigned long len
can be computed w/ tinystrlen()
@return
void
@clob nothing except flags

PrintBacktraceUsingSymbols

Prints stack frames with symbols.

PrintBacktraceUsingSymbols(STDOUT_FILENO, NULL, GetSymbolTable());

@param
int fd
struct StackFrame* bp
is rbp which can be NULL to detect automatically
struct SymbolTable* st
is open symbol table for current executable
@return
int
-1 w/ errno if error happened

printf

Formats and writes string to stdout.

Cosmopolitan supports most of the standard formatting behaviors described by man 3 printf, in addition to the following:

  • %jd, %jx, etc. are {,u}intmax_t which in Cosmopolitan is 128-bit.
  • %'d or %,d may be used to insert thousands separators. The prior is consistent with C; the latter is consistent with Python.
  • %m inserts strerror(errno) into the formatted output. This is consistent with glibc, musl, and uclibc.
  • %n inserts "\n" on non-Windows and "\r\n" on Windows. This is the same behavior as Java. It's incompatible with glibc's behavior, since that's problematic according to Android's security team.
  • %hs converts UTF-16/UCS-2 → UTF-8, which can be helpful on Windows. Formatting (e.g. %-10hs) will use monospace display width rather than string length or codepoint count.
  • %ls (or %Ls) converts UTF-32 → UTF-8. Formatting (e.g. %-10ls) will use monospace display width rather than string length.
  • The %#s and %#c alternate forms display values using the standard IBM standard 256-letter alphabet. Using %#.*s to specify length will allow true binary (i.e. with NULs) to be formatted.
  • The %'s and %'c alternate forms are Cosmopolitan extensions for escaping string literals for C/C++ and Python. The outer quotation marks can be added automatically using %`s. If constexpr format strings are used, we can avoid linking cescapec() too.
  • The backtick modifier (%`s and %`c) and repr() directive (%r) both ask the formatting machine to represent values as real code rather than using arbitrary traditions for displaying values. This means it implies the quoting modifier, wraps the value with {,u,L}['"] quotes, displays NULL as "NULL" rather than "(null)".
@param
char* fmt
...
@return
int
@see palandprintf() for intuitive reference documentation
@see {,v}{,s{,n},{,{,x}as},f,d}printf

PrintMemoryIntervals

@param
int fd
struct _mmi* mm
@return
void

__prot2nt

Converts System Five memory protection flags to Windows NT, Part 1.

@param
int prot
int flags
@return
unsigned int
@see libc/sysv/consts.sh

psadbw

Computes sum of absolute differences.

@param
unsigned long* a
unsigned char* b
unsigned char* c
@return
void
@mayalias

pshufb

Shuffles and/or clears 8-bit integers.

@param
unsigned char* a
unsigned char* b
unsigned char* c
@return
void
@note goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@note doesn't perfectly emulate mmx
@mayalias

pshufd

Shuffles int vector.

@param
int* b
int* a
unsigned char m
@return
void
@mayalias

pshufhw

Shuffles lower half of word vector.

@param
short* b
short* a
unsigned char m
@return
void
@mayalias

pshuflw

Shuffles lower half of word vector.

@param
short* b
short* a
unsigned char m
@return
void
@mayalias

pshufw

Shuffles mmx vector.

@param
short* b
short* a
unsigned char m
@return
void
@mayalias

psignb

Conditionally negates or zeroes signed bytes.

@param
char* a
char* b
char* c
@return
void
@note goes fast w/ ssse3 (intel c. 2004, amd c. 2011)

psignd

Conditionally negates or zeroes ints.

@param
int* a
int* b
int* c
@return
void
@note goes fast w/ ssse3 (intel c. 2004, amd c. 2011)

psignw

Conditionally negates or zeroes shorts.

@param
short* a
short* b
short* c
@return
void
@note goes fast w/ ssse3 (intel c. 2004, amd c. 2011)

pslld

Multiplies ints by two power.

@param
unsigned int* a
unsigned int* b
unsigned char c
@return
void
@note c needs to be a literal, asmconstexpr, or linkconstsym
@mayalias

pslldq

Shifts vector right by n bytes w/ zero-fill.

@param
unsigned char* b
receives output
unsigned char* a
is input vector
unsigned long n
@return
void
@mayalias

pslldv

Multiplies ints by two power.

@param
unsigned int* a
unsigned int* b
unsigned long* c
@return
void
@mayalias

psllq

Multiplies longs by two power.

@param
unsigned long* a
unsigned long* b
unsigned char c
@return
void
@note c needs to be a literal, asmconstexpr, or linkconstsym
@mayalias

psllqv

Multiplies longs by two power.

@param
unsigned long* a
unsigned long* b
unsigned long* c
@return
void
@mayalias

psllw

Multiplies shorts by two power.

@param
unsigned short* a
unsigned short* b
unsigned char c
@return
void
@note c needs to be a literal, asmconstexpr, or linkconstsym
@mayalias

psllwv

Multiplies shorts by two power.

@param
unsigned short* a
unsigned short* b
unsigned long* c
@return
void
@mayalias

psrad

Divides ints by two power.

@param
int* a
int* b
unsigned char k
@return
void
@note c needs to be a literal, asmconstexpr, or linkconstsym
@note arithmetic shift right will sign extend negatives
@mayalias

psradv

Divides shorts by two powers.

@param
int* a
int* b
unsigned long* c
@return
void
@note arithmetic shift right will sign extend negatives
@mayalias

psraw

Divides shorts by two power.

@param
short* a
short* b
unsigned char k
@return
void
@note c needs to be a literal, asmconstexpr, or linkconstsym
@note arithmetic shift right will sign extend negatives
@mayalias

psrawv

Divides shorts by two power.

@param
short* a
short* b
unsigned long* c
@return
void
@note arithmetic shift right will sign extend negatives
@mayalias

psrld

Divides unsigned ints by two power.

@param
unsigned int* a
unsigned int* b
unsigned char c
@return
void
@note c needs to be a literal, asmconstexpr, or linkconstsym
@note logical shift does not sign extend negatives
@mayalias

psrldq

Shifts vector left by n bytes w/ zero-fill.

@param
unsigned char* b
receives output
unsigned char* a
is input vector
unsigned long n
@return
void
@mayalias

psrldv

Divides ints by two power.

@param
unsigned int* a
unsigned int* b
unsigned long* c
@return
void
@note logical shift does not sign extend negatives
@mayalias

psrlq

Divides unsigned longs by two power.

@param
unsigned long* a
unsigned long* b
unsigned char c
@return
void
@note c needs to be a literal, asmconstexpr, or linkconstsym
@note logical shift does not sign extend negatives
@mayalias

psrlqv

Divides unsigned longs by two power.

@param
unsigned long* a
unsigned long* b
unsigned long* c
@return
void
@note logical shift does not sign extend negatives
@mayalias

psrlw

Divides unsigned shorts by two power.

@param
unsigned short* a
unsigned short* b
unsigned char c
@return
void
@note c needs to be a literal, asmconstexpr, or linkconstsym
@note logical shift does not sign extend negatives
@mayalias

psrlwv

Divides unsigned shorts by two power.

@param
unsigned short* a
unsigned short* b
unsigned long* c
@return
void
@note logical shift does not sign extend negatives
@mayalias

psubb

Subtracts 8-bit integers.

@param
unsigned char* a
unsigned char* b
unsigned char* c
@return
void
@mayalias

psubd

Subtracts 32-bit integers.

@param
int* a
int* b
int* c
@return
void
@mayalias

psubq

Subtracts 64-bit integers.

@param
long* a
long* b
long* c
@return
void
@mayalias

psubsb

Subtracts signed 8-bit integers w/ saturation.

@param
char* a
char* b
char* c
@return
void
@mayalias

psubsw

Subtracts signed 16-bit integers w/ saturation.

@param
short* a
short* b
short* c
@return
void
@mayalias

psubusb

Subtracts unsigned 8-bit integers w/ saturation.

@param
unsigned char* a
unsigned char* b
unsigned char* c
@return
void
@mayalias

psubusw

Subtracts unsigned 16-bit integers w/ saturation.

@param
unsigned short* a
unsigned short* b
unsigned short* c
@return
void
@mayalias

psubw

Subtracts 16-bit integers.

@param
short* a
short* b
short* c
@return
void
@mayalias

pthread_cancel

@param
void* thread
@return
int

pthread_mutex_lock

@param
int* mutex
@return
int

pthread_mutex_trylock

@param
int* mutex
@return
int

pthread_mutex_unlock

@param
int* mutex
@return
int

pthread_once

@param
_Bool* once
void(*)() init
@return
int

ptrace

Traces process.

@param
int request
can be PTRACE_xxx
int pid
void* addr
void* data
@return
long
@note de facto linux only atm

ptsname

@param
int fd
@return
char*

ptsname_r

@param
int fd
char* buf
unsigned long size
@return
int

punpckhbw

Interleaves high bytes.

@param
unsigned char* a
unsigned char* b
unsigned char* c
@return
void
@mayalias

punpckhdq

Interleaves high doublewords.

     0    1    2    3
  B  aaaa bbbb CCCC DDDD
  C  eeee ffff GGGG HHHH
               └┬─┘ └─┬┘
           ┌────┘     │
     ┌─────┴─┐ ┌──────┴┐
→ A  CCCC GGGG DDDD HHHH
@param
unsigned int* a
unsigned int* b
unsigned int* c
@return
void
@mayalias

punpckhqdq

Interleaves high quadwords.

@param
unsigned long* a
unsigned long* b
unsigned long* c
@return
void
@mayalias

punpckhwd

Interleaves 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
unsigned short* a
unsigned short* b
unsigned short* c
@return
void
@mayalias

punpcklbw

Interleaves 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
unsigned char* a
unsigned char* b
unsigned char* c
@return
void
@mayalias

punpckldq

Interleaves low doublewords.

     0    1    2    3
  B  AAAA BBBB cccc dddd
  C  EEEE FFFF gggg hhhh
     └┬─┘ └─┬┘
      │     └───┐
     ┌┴──────┐ ┌┴──────┐
→ A  AAAA EEEE BBBB FFFF
@param
unsigned int* a
unsigned int* b
unsigned int* c
@return
void
@mayalias

punpcklqdq

Interleaves low quadwords.

@param
unsigned long* a
unsigned long* b
unsigned long* c
@return
void
@mayalias

punpcklwd

Interleaves 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
unsigned short* a
unsigned short* b
unsigned short* c
@return
void
@mayalias

putchar

Writes byte to stdout.

@param
int c
@return
int
c (as unsigned char) if written or -1 w/ errno

putenv

Emplaces environment key=value.

@param
char* string
@return
int
@see setenv(), getenv()

PutEnvImpl

@param
char* s
_Bool overwrite
@return
int

puts

Writes string w/ trailing newline to stdout.

@param
char* s
@return
int

pututf16

Encodes 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
unsigned short* s
is what ch gets encoded to
unsigned long size
is the number of shorts available in s
unsigned int wc
_Bool awesome
enables numbers the IETF unilaterally banned
@return
int
number of shorts written or -1 w/ errno
@todo delete

putwc

Writes wide character to stream.

@param
%edi
is the wide character
%rsi
is the FILE stream pointer
@return
%eax is set to %edi param or -1 on error

putwchar

Writes wide character to stdout.

@param
int wc
@return
unsigned int
wc if written or -1 w/ errno

pvalloc

Equivalent to valloc(minimum-page-that-holds(n)), that is, round up n to nearest pagesize.

@param
rdi
is number of bytes needed
@return
rax is memory address, or NULL w/ errno
@see dlpvalloc()

pwrite

Writes to file at offset, thus avoiding superfluous lseek().

@param
int fd
is something open()'d earlier, noting pipes might not work
void* buf
is copied from, cf. copy_file_range(), sendfile(), etc.
unsigned long size
in range [1..0x7ffff000] is reasonable
long offset
is bytes from start of file at which write begins
@return
long
[1..size] bytes on success, or -1 w/ errno; noting zero is impossible unless size was passed as zero to do an error check
@see pread(), write()
@asyncsignalsafe
@vforksafe

pwritev

Writes 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
int fd
struct iovec* iovec
int count
is recommended to be 16 or fewer; if it exceeds IOV_MAX then the extra buffers are simply ignored
long off
@return
long
number of bytes actually sent, or -1 w/ errno
@asyncsignalsafe
@vforksafe

pxor

Xors 128-bit integers.

@param
unsigned long* a
unsigned long* b
unsigned long* c
@return
void
@mayalias

qsort

Sorts array.

@param
void* base
points to an array to sort in-place
unsigned long count
is the item count
unsigned long width
is the size of each item
int(*)() cmp
is a callback returning <0, 0, or >0
@return
void
@see qsort_r()

qsort_r

Sorts array.

@param
void* base
points to an array to sort in-place
unsigned long count
is the item count
unsigned long width
is the size of each item
int(*)() cmp
is a callback returning <0, 0, or >0
void* arg
will optionally be passed as the third argument to cmp
@return
void
@see qsort()

raise

Sends signal to this process.

@param
int sig
can be SIGALRM, SIGINT, SIGTERM, SIGKILL, etc.
@return
int
0 on success or -1 w/ errno
@asyncsignalsafe

rand

Returns 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
int

rand32

This function is an independent 32-bit clone of rand64().

@return
unsigned int

rand64

Returns 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
unsigned long
@see rngset()

randf

@return
float

rawmemchr

Returns pointer to first instance of character.

@param
void* m
is memory to search
int c
is search byte which is masked with 255
@return
void*
is pointer to first instance of c

rawmemchr16

Returns pointer to first instance of character in range.

@param
rdi
is a non-null pointer to memory
esi
is the search word
@return
rax points to word if found, or else undefined behavior

rawwmemchr

Returns pointer to first instance of character in range.

@param
rdi
is a non-null pointer to memory
esi
is the search word
@return
rax points to word if found, or else undefined behavior

rdrand

Intel Secure Key Digital Random Number Generator Introduced w/ Ivy Bridge c. 2013 and Excavator c. 2015

@return
unsigned long
@see rdseed(), rand32(), rand64(), and randcpy()

rdseed

Intel Securer Key Digital Random Number Generator Introduced w/ Ivy Bridge c. 2013 and Excavator c. 2015

@return
unsigned long
@see rdrand(), rand32(), rand64(), and randcpy()

read

Reads data from file descriptor.

@param
int fd
is something open()'d earlier
void* buf
is copied into, cf. copy_file_range(), sendfile(), etc.
unsigned long size
in range [1..0x7ffff000] is reasonable
@return
long
[1..size] bytes on success, 0 on EOF, or -1 w/ errno; with exception of size==0, in which case return zero means no error
@see write(), pread(), readv()
@asyncsignalsafe

readansi

Reads 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"            PF1
This 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
int fd
char* buf
is guaranteed to receive a NUL terminator if size>0
unsigned long size
@return
long
number of bytes read (helps differentiate "\0" vs. "")
@see examples/ttyinfo.c
@see ANSI X3.64-1979
@see ISO/IEC 6429
@see FIPS-86
@see ECMA-48

readdir

Reads next entry from directory stream.

This API doesn't define any particular ordering.

@param
struct dirstream* dir
is the object opendir() or fdopendir() returned
@return
struct ent*
next entry or NULL on end or error, which can be differentiated by setting errno to 0 beforehand

realloc

Allocates / 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
rdi
(p) is address of current allocation or NULL
rsi
(n) is number of bytes needed
@return
rax is result, or NULL w/ errno w/o free(p)
@note realloc(p=0, n=0) → malloc(32)
@note realloc(p≠0, n=0) → free(p)
@see dlrealloc()

realloc_in_place

Resizes 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
rdi
(p) is address of current allocation
rsi
(newsize) is number of bytes needed
@return
rax is result, or NULL w/ errno
@see dlrealloc_in_place()

reallocarray

Manages array memory, the BSD way.

@param
void* ptr
may be NULL for malloc() behavior
unsigned long nmemb
may be 0 for free() behavior; shrinking is promised too
unsigned long itemsize
@return
void*
new address or NULL w/ errno and ptr is NOT free()'d

realpath

@param
char* path
char* resolved_path
@return
char*

recv

Receives data from network socket.

@param
int fd
is the file descriptor returned by socket()
void* buf
is where received network data gets copied
unsigned long size
is the byte capacity of buf
int flags
can have MSG_{WAITALL,PEEK,OOB}, etc.
@return
long
number of bytes received, 0 on remote close, or -1 w/ errno
@error EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable), EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
@asyncsignalsafe

regcomp

Compiles 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
struct regex_t* preg
points to state, and needs regfree() afterwards
char* regex
is utf-8 regular expression string
int cflags
can have REG_EXTENDED, REG_ICASE, REG_NEWLINE, REG_NOSUB
@return
int
REG_OK, REG_NOMATCH, REG_BADPAT, etc.
@see regexec(), regfree(), regerror()

regerror

Converts regular expression error code to string.

@param
int e
is error code
struct regex_t* preg
char* buf
unsigned long size
@return
unsigned long
number of bytes needed to hold entire string

regexec

Executes regular expression.

@param
struct regex_t* preg
is state object previously made by regcomp()
char* string
unsigned long nmatch
struct regmatch_t* pmatch
int eflags
can have REG_NOTBOL, REG_NOTEOL
@return
int
0 or REG_NOMATCH

regfree

Frees any memory allocated by regcomp().

@param
struct regex_t* preg
@return
void

ReleaseMemoryIntervals

@param
struct _mmi* mm
int x
int y
void(*)() wf
@return
int

ReleaseMemoryNt

@param
struct _mmi* mm
int l
int r
@return
void

rem1000000000int64

Returns 𝑥 % 1,000,000,000.

@param
rdi
int64 𝑥
@return
rax has remainder

rem1000000int64

Returns 𝑥 % 1,000,000.

@param
rdi
int64 𝑥
@return
rax has remainder

rem10000int64

Returns 𝑥 % 10,000.

@param
rdi
int64 𝑥
@return
rax has remainder

rem1000int64

Returns 𝑥 % 1,000.

@param
rdi
int64 𝑥
@return
rax has remainder

rem100int64

Returns 𝑥 % 100.

@param
rdi
int64 𝑥
@return
rax has remainder

rem10int64

Returns 𝑥 % 10.

@param
rdi
int64 𝑥
@return
rax has remainder

remainder

remainder(𝑥,𝑦) means (𝑥 rem 𝑦) w/ rint()-style rounding.

@param
𝑥
is double passed in lower half of %xmm0
𝑦
is double passed in lower half of %xmm1
@return
remainder ∈ (-|𝑦|,|𝑦|) in %xmm0
@define 𝑥-rint(𝑥/𝑦)*𝑦
@see fmod(), emod(), operator%

remove

Deletes "file" or empty directory associtaed with name.

@param
char* name
@return
int
0 on success or -1 w/ errno
@see unlink() and rmdir() which this abstracts

rename

Moves file the Unix way.

@param
char* oldpathname
char* newpathname
@return
int
0 on success or -1 w/ errno
@asyncsignalsafe

renameat

Renames files relative to directories.

@param
int olddirfd
is normally AT_FDCWD but if it's an open directory and oldpath is relative, then oldpath become relative to dirfd
char* oldpath
int newdirfd
is normally AT_FDCWD but if it's an open directory and newpath is relative, then newpath become relative to dirfd
char* newpath
@return
int
0 on success, or -1 w/ errno

replacestr

Replaces all instances of NEEDLE in S with REPLACEMENT.

@param
char* s
char* needle
can't be empty
char* replacement
@return
char*
newly allocated memory that must be free()'d or NULL w/ errno
@error ENOMEM, EINVAL

replaceuser

Replaces tilde in path w/ user home folder.

@param
char* path
is NULL propagating
@return
char*
must be free()'d

__reservefd

Finds open file descriptor slot.

@return
int

resolvedns

Queries Domain Name System for address associated with name.

@param
struct ResolvConf* resolvconf
can be getresolvconf()
int af
can be AF_INET, AF_UNSPEC
char* name
can be a local or fully-qualified hostname
struct sockaddr* addr
should point to a struct sockaddr_in; if this function succeeds, its sin_family and sin_addr fields will be modified
unsigned int addrsize
is the byte size of addr
@return
int
number of matches found, or -1 w/ errno
@error EAFNOSUPPORT. ENETDOWN, ENAMETOOLONG, EBADMSG

resolvehoststxt

Finds address associated with name in HOSTS.TXT table.

This function performs binary search, so sorthoststxt() must be called on the table beforehand.

@param
struct HostsTxt* ht
can be gethoststxt()
int af
can be AF_INET, AF_UNSPEC
char* name
can be a local or fully-qualified hostname
struct sockaddr* addr
should point to a struct sockaddr_in; if this function succeeds, its sin_family and sin_addr fields will be modified
unsigned int addrsize
is the byte size of addr
char** canon
be used to return a pointer to the canonical name
@return
int
number of matches found, or -1 w/ errno
@error EAFNOSUPPORT

rewind

Moves 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
struct FILE* stream
@return
void

rijndaelinit

Computes key schedule for rijndael().

@param
struct Rijndael* ctx
receives round keys
unsigned int n
is 14 for AES-256, 12 for AES-192, and 10 for AES-128
unsigned int k1
unsigned int k2
@return
void

rindex

Returns pointer to last instance of character the BSD way.

@param
rdi
is a non-null NUL-terminated string pointer
esi
is the search byte
@return
rax points to result, or NULL if not found

rint

Rounds to nearest integer.

@param
is
double passed in %xmm0
@return
double in %xmm0
@note rounding behavior can be changed in mxcsr

rintl

Rounds to nearest integer.

@param
is
long double passed on stack
@return
long double in %st
@note rounding behavior can be changed in control word

rldecode

Seventeen byte decompressor.

@param
di
points to output buffer
si
points to uint8_t {len₁,byte₁}, ..., {0,0}
@return
@mode long,legacy,real

rmdir

Deletes empty directory.

@param
char* path
@return
int
0 on success or -1 w/ errno on error

rmrf

Recursively removes file or directory.

@param
char* path
@return
int

rngset

Fills memory with random bytes, e.g.

char buf[1024]; rngset(buf, sizeof(buf), rand64, -1);

@param
void* buf
unsigned long size
unsigned long(*)() seed
can be rand64() and is always called at least once
unsigned long reseed
is bytes between seed() calls and -1 disables it
@return
void*
original buf

round

Rounds to nearest integer, away from zero.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0
@define round(𝑥) = copysign(trunc(fabs(𝑥)+.5),𝑥) round(𝑥) = trunc(𝑥+copysign(.5,𝑥))

RoundDecimalPlaces

@param
double f
double digs
double(*)() rounder
@return
double

rounddown2pow

Returns 𝑥 rounded down to previous two power.

@param
unsigned long x
@return
unsigned long
@define (𝑥>0→2^⌊log₂𝑥⌋, x=0→0, 𝑇→⊥)
@see roundup2pow()

roundf

Rounds to nearest integer, away from zero.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0

roundl

Rounds to nearest integer, away from zero.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result of exponentiation on FPU stack in %st

roundup2log

Returns 𝑥 rounded up to next two power and log'd.

@param
unsigned long x
@return
unsigned long
@see roundup2pow()

roundup2pow

Returns 𝑥 rounded up to next two power.

@param
unsigned long x
@return
unsigned long
@define (𝑥>0→2^⌈log₂x⌉, x=0→0, 𝑇→⊥)
@see rounddown2pow()

rt_add

@param
void* buf
int bufl
@return
void

rt_end

@param
double* r_ent
double* r_chisq
double* r_mean
double* r_montepicalc
double* r_scc
@return
void

rt_init

@param
int binmode
@return
void

savexmm

Stores XMM registers to buffer.

@param
%rdi
points to &(forcealign(16) uint8_t[256])[128]
@return
@note modern cpus have out-of-order execution engines

sbrk

Adjusts 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
long delta
@return
void*
old break on success or -1 w/ errno
@see mmap(), brk(), _end

scalb

Returns 𝑥 × 2ʸ.

@param
𝑥
is double passed in %xmm0
𝑦
is double passed in %xmm1, which is truncated
@return
result in %xmm0
@see ldexp()

scalbf

Returns 𝑥 × 2ʸ.

@param
𝑥
is float passed in %xmm0
𝑦
is float passed in %xmm1, which is truncated
@return
result in %xmm0
@see ldexpf()

scalbl

Returns 𝑥 × 2ʸ.

@param
𝑥
is long double passed on stack
𝑦
is long double passed on stack
@return
result in %st0
@see ldexpl()

scalbln

Returns 𝑥 × 2ʸ.

@param
𝑥
is double passed in %xmm0
𝑦
is exponent via %edi
@return
double in %xmm0

scalblnf

Returns 𝑥 × 2ʸ.

@param
𝑥
is float passed in %xmm0
𝑦
is exponent via %edi
@return
float in %xmm0

scalblnl

Returns 𝑥 × 2ʸ.

@param
𝑥
is long double passed on stack
𝑦
is exponent via %edi
@return
result in %st0

scalbn

Returns 𝑥 × 2ʸ.

@param
𝑥
is double passed in %xmm0
𝑦
is exponent via %edi
@return
double in %xmm0

scalbnf

Returns 𝑥 × 2ʸ.

@param
𝑥
is float passed in %xmm0
𝑦
is exponent via %edi
@return
float in %xmm0

scalbnl

Returns 𝑥 × 2ʸ.

@param
𝑥
is long double passed on stack
𝑦
is exponent via %edi
@return
result in %st0

scanf

Standard input decoder.

@param
char* fmt
...
@return
int
@see libc/fmt/vcscanf.h

sched_setaffinity

Asks kernel to only schedule process on particular CPUs.

@param
int pid
is the process or thread id (or 0 for caller)
unsigned long bitsetsize
is byte length of bitset
void* bitset
@return
int
0 on success, or -1 w/ errno

sched_yield

Asks kernel to deschedule thread momentarily.

@return
int

send

Sends data to network socket.

@param
int fd
is the file descriptor returned by socket()
void* buf
is the data to send, which we'll copy if necessary
unsigned long size
is the byte-length of buf
int flags
MSG_OOB, MSG_DONTROUTE, MSG_PARTIAL, MSG_NOSIGNAL, etc.
@return
long
number of bytes transmitted, or -1 w/ errno
@error EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable), EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
@asyncsignalsafe

serializednsheader

Serializes DNS message header to wire.

@param
unsigned char* buf
unsigned long size
struct header header
@return
int
number of bytes written (always 12) or -1 w/ errno
@see pascalifydnsname()

serializednsquestion

Serializes DNS question record to wire.

@param
unsigned char* buf
unsigned long size
struct dq dq
@return
int
number of bytes written
@see pascalifydnsname()

setbuf

Sets buffer on stdio stream.

@param
struct FILE* f
char* buf
@return
void

setbuffer

Sets buffer on stdio stream.

@param
struct FILE* f
char* buf
unsigned long size
@return
void

setegid

Sets effective group ID.

@param
%edi
is group id
@return
@see setgid(), getauxval(AT_SECURE)

setenv

Copies variable to environment.

@param
char* name
char* value
int overwrite
@return
int
0 on success, or -1 w/ errno
@see putenv(), getenv()

seteuid

Sets effective user ID.

@param
%edi
is user id
@return
@see setuid(), getauxval(AT_SECURE)

setgrent

@return
void

setitimer

Schedules 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
int which
can be ITIMER_REAL, ITIMER_VIRTUAL, etc.
struct itimerval* newvalue
specifies the interval ({0,0} means one-shot) and duration ({0,0} means disarm) in microseconds ∈ [0,999999] and if this parameter is NULL, we'll polyfill getitimer() behavior
struct itimerval* out_opt_oldvalue
@return
int
0 on success or -1 w/ errno

_setjmp

Saves caller CPU state to cacheline.

@param
rdi
points to jmp_buf
@return
rax 0 when set and !0 when longjmp'd
@returnstwice
@assume system five nexgen32e abi conformant
@note code built w/ microsoft abi compiler can't call this
@see longjmp(), gclongjmp()

setjmp

Saves caller CPU state to cacheline.

@param
rdi
points to jmp_buf
@return
rax 0 when set and !0 when longjmp'd
@returnstwice
@assume system five nexgen32e abi conformant
@note code built w/ microsoft abi compiler can't call this
@see longjmp(), gclongjmp()

setlocale

Sets program locale.

Cosmopolitan only supports the C or POSIX locale.

@param
int category
char* locale
@return
char*

setpriority

Sets nice value of thing.

@param
int which
can be PRIO_PROCESS, PRIO_PGRP, PRIO_USER
unsigned int who
is the pid, pgid, or uid, 0 meaning current
int value
∈ [-NZERO,NZERO) which is clamped automatically
@return
int
nonzero on success or -1 w/ errno
@see getpriority(), nice()

setpwent

@return
void

setresgid

Sets real, effective, and "saved" group ids.

@param
unsigned int real
sets real group id or -1 to do nothing
unsigned int effective
sets effective group id or -1 to do nothing
unsigned int saved
sets saved group id or -1 to do nothing
@return
int
@see setregid(), getauxval(AT_SECURE)

setresuid

Sets real, effective, and "saved" user ids.

@param
unsigned int real
sets real user id or -1 to do nothing
unsigned int effective
sets effective user id or -1 to do nothing
unsigned int saved
sets saved user id or -1 to do nothing
@return
int
@see setreuid(), getauxval(AT_SECURE)

setrlimit

Sets resource limit for current process.

@param
int resource
can be RLIMIT_{CPU,FSIZE,DATA,STACK,CORE,RSS,etc.}
struct rlimit* rlim
specifies new resource limit
@return
int
0 on success or -1 w/ errno
@see libc/sysv/consts.sh

setsid

Creates session and sets the process group id.

@return
int

_setstack

Switches stack.

@param
rdi
is new rsp, passed as malloc(size) + size
rsi
is function to call in new stack space
rdx,rcx,r8,r9
get passed as args to rsi
@return
rax and happens on original stack

setvbuf

Tunes buffering settings for an stdio stream.

@param
struct FILE* f
char* buf
may optionally be non-NULL to set the stream's underlying buffer, which the stream will own, but won't free
int mode
may be _IOFBF, _IOLBF, or _IONBF
unsigned long size
must be a two power if buf is provided
@return
int
0 on success or -1 on error

ShowBacktrace

@param
int fd
struct StackFrame* bp
@return
void

showcrashreports

Installs 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.

  • Backtraces
  • CPU state printout
  • Automatic debugger attachment
Another trick this function enables, is you can press CTRL+\ to open the debugger GUI at any point while the program is running. It can be useful, for example, if a program is caught in an infinite loop.
@return
void
@see callexitontermination()

shufpd

Shuffles double vector.

@param
double* c
double* b
double* a
unsigned char m
@return
void
@mayalias

shufps

Shuffles float vector.

@param
float* c
float* b
float* a
unsigned char m
@return
void
@mayalias

sigaction

Installs 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
int sig
struct copy* act
struct copy* oldact
@return
int
@see xsigaction() for a much better api
@asyncsignalsafe
@vforksafe

sigaddset

Adds signal to set.

@param
struct sigset_t* set
int sig
@return
int
true, false, or -1 w/ errno
@asyncsignalsafe

sigdelset

Removes signal from set.

@param
struct sigset_t* set
int sig
@return
int
0 on success, or -1 w/ errno
@asyncsignalsafe

sigemptyset

Removes all signals from set.

@param
struct sigset_t* set
@return
int
0 on success, or -1 w/ errno
@asyncsignalsafe

sigfillset

Adds all signals to set.

@param
struct sigset_t* set
@return
int
0 on success, or -1 w/ errno
@asyncsignalsafe

sigignore

Configures process to ignore signal.

@param
int sig
@return
int

sigismember

Returns true if signal is member of set.

@param
struct sigset_t* set
int sig
@return
int
true, false, or -1 w/ errno
@asyncsignalsafe

signal

Installs kernel interrupt handler.

@param
int sig
void(*)() func
@return
void(*)()
@see sigaction() which has more features

sigprocmask

Changes program signal blocking state, e.g.:

sigset_t oldmask;
sigprocmask(SIG_BLOCK, &kSigsetFull, &oldmask);
sigprocmask(SIG_SETMASK, &oldmask, NULL);
@param
int how
can be SIG_BLOCK (U), SIG_UNBLOCK (/), SIG_SETMASK (=)
struct kSigsetEmpty* opt_set
struct kSigsetEmpty* opt_out_oldset
@return
int
0 on success, or -1 w/ errno
@asyncsignalsafe
@vforksafe

sigsuspend

Blocks until SIG ∉ MASK is delivered to process.

@param
struct kSigsetEmpty* ignore
is a bitset of signals to block temporarily
@return
int
-1 w/ EINTR
@asyncsignalsafe

sin

Returns sine of 𝑥.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0
@domain -(3π/8) < 𝑥 < 3π/8 for best accuracy

sincos

Returns sine and cosine of 𝑥.

@param
𝑥
is double scalar in low half of %xmm0
%rdi
is double *out_sin
%rsi
is double *out_cos
@return
@domain -(3π/8) < 𝑥 < 3π/8 for best accuracy

sincosf

Returns sine and cosine of 𝑥.

@param
𝑥
is float scalar in low quarter of %xmm0
%rdi
is float *out_sin
%rsi
is float *out_cos
@return
@domain -(3π/8) < 𝑥 < 3π/8 for best accuracy

sincosl

Returns sine and cosine of 𝑥.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
%rdi
is long double *out_sin
%rsi
is long double *out_cos
@return
@domain -(3π/8) < 𝑥 < 3π/8 for best accuracy

sinf

Returns sine of 𝑥.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0
@domain -(3π/8) < 𝑥 < 3π/8 for best accuracy

sinh

Returns hyperbolic sine of 𝑥.

@param
double x
@return
double

sinhf

Returns hyperbolic sine of 𝑥.

@param
float x
@return
float

sinhl

Returns hyperbolic sine of 𝑥.

@param
long double x
@return
long double

sinl

Returns sine of 𝑥.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
%st stores result
@domain -(3π/8) < 𝑥 < 3π/8 for best accuracy

sleb128

Encodes sleb-128 signed integer.

@param
void* buf
unsigned long size
__int128 x
@return
int

sleep

Sleeps for a particular amount of time.

@param
unsigned int seconds
@return
int
@asyncsignalsafe

slowcall

Applies no-clobber guarantee to System Five function call.

  • Reentrant
  • Realigns stack
  • Doesn't assume red zone
  • Clobbers nothing (except %rax and flags)
This function may be called using an stdcall convention. It's useful for files named FOO.hookabi.c and BAR.ncabi.c to make calls into other parts of the system, that don't conform to the same restricted ABI.
@param
six
args and fn addr pushed on stack in reverse order
@return
%rax has function return value, and stack is cleaned up
@see libc/shadowargs.hook.c for intended use case

snprintf

Formats string to buffer.

@param
char* buf
unsigned long count
char* fmt
...
@return
int
number of bytes written, excluding the NUL terminator; or, if the output buffer wasn't passed, or was too short, then the number of characters that *would* have been written is returned
@see palandprintf() and printf() for detailed documentation
@asyncsignalsafe
@vforksafe

socketconnect

Opens socket client connection.

@param
struct addrinfo* ai
can be obtained via getaddrinfo()
int flags
@return
int
socket file descriptor, or -1 w/ errno

sorthoststxt

Sorts 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
struct HostsTxt* ht
@return
void

spacepad

@param
int(*)() out
void* arg
unsigned long n
@return
int

splice

Transfers data to/from pipe.

@param
int infd
long* inopt_out_inoffset
int outfd
long* inopt_out_outoffset
unsigned long uptobytes
unsigned int flags
can have SPLICE_F_{MOVE,NONBLOCK,MORE,GIFT}
@return
long
number of bytes transferred, 0 on input end, or -1 w/ errno
@see copy_file_range() for file ↔ file
@see sendfile() for seekable → socket

sprintf

Formats string to buffer that's hopefully large enough.

@param
char* buf
char* fmt
...
@return
int
@see palandprintf() and printf() for detailed documentation
@see snprintf() for same w/ buf size param
@asyncsignalsafe
@vforksafe

sqrt

Returns square root of 𝑥.

@param
𝑥
is an double passed in %xmm0
@return
result in %xmm0

sqrtf

Returns square root of 𝑥.

@param
𝑥
is an float passed in %xmm0
@return
result in %xmm0

sqrtl

Returns square root of 𝑥.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
result on FPU stack in %st

srand

Seeds random number generator that's used by rand().

@param
unsigned long seed
@return
void

sscanf

String decoder.

@param
char* str
char* fmt
...
@return
int
@see libc/fmt/vcscanf.h (for docs and implementation)

__stack_chk_fail

Aborts program under enemy fire to avoid being taken alive.

@return
void

__start_fatal

Prints initial part of fatal message.

@param
char* file
int line
@return
void
@note this is support code for __check_fail(), __assert_fail(), etc.
@see __start_fatal_ndebug()

__start_fatal_ndebug

Prints initial part of fatal message.

@return
void
@note this is support code for __check_fail(), __assert_fail(), etc.
@see __start_fatal()

startswith

Returns true if s has prefix.

@param
char* s
is a NUL-terminated string
char* prefix
is also NUL-terminated
@return
_Bool

startswith16

Returns true if s has prefix.

@param
unsigned short* s
is a NUL-terminated string
unsigned short* prefix
is also NUL-terminated
@return
_Bool

stat

Returns information about thing.

@param
char* path
struct stat* st
is where result is stored
@return
int
@see S_ISDIR(st.st_mode), S_ISREG(), etc.
@asyncsignalsafe

__stat2linux

Transcodes “The Dismal Data Structure” from BSD→Linux ABI.

@param
void* ms
@return
void
@asyncsignalsafe

stderr

Pointer to standard error stream.

@type
struct __stderr*

stdin

Pointer to standard input stream.

@type
struct __stdin*

stdout

Pointer to standard output stream.

@type
struct __stdout*

stpcpy

Copies bytes from 𝑠 to 𝑑 until a NUL is encountered.

@param
char* d
char* s
@return
char*
pointer to nul byte
@note 𝑑 and 𝑠 can't overlap
@asyncsignalsafe

stpncpy

Prepares static search buffer.

  1. If SRC is too long, it's truncated and *not* NUL-terminated.
  2. If SRC is too short, the remainder is zero-filled.
Please note this function isn't designed to prevent untrustworthy data from modifying memory without authorization. Consider trying memccpy() for that purpose.
@param
char* dest
char* src
unsigned long stride
@return
char*
dest + stride
@see stncpy(), memccpy()
@asyncsignalsafe

strcasecmp

Compares NUL-terminated strings case-insensitively.

@param
char* a
is first non-null NUL-terminated string pointer
char* b
is second non-null NUL-terminated string pointer
@return
int
is <0, 0, or >0 based on uint8_t comparison
@asyncsignalsafe

strcasecmp16

Compares NUL-terminated UCS-2 strings case-insensitively.

@param
unsigned short* l
unsigned short* r
@return
int
is <0, 0, or >0 based on uint16_t comparison
@asyncsignalsafe

strcasecmp16to8

@param
unsigned short* s1
char* s2
@return
int

strcasecmp8to16

Compares UTF-8 and UTF-16 strings, ignoring case.

@param
char* s1
unsigned short* s2
@return
int

strcat

Appends 𝑠 to 𝑑.

@param
char* d
char* s
@return
char*
𝑑
@asyncsignalsafe

strcat16

Appends 𝑠 to 𝑑.

@param
unsigned short* d
unsigned short* s
@return
unsigned short*
𝑑
@asyncsignalsafe

strchr

Returns pointer to first instance of character.

@param
char* s
is a NUL-terminated string
int c
is masked with 255 as byte to search for
@return
char*
pointer to first instance of c or NULL if not found noting that if c is NUL we return pointer to terminator
@asyncsignalsafe

strchr16

Returns pointer to first instance of character.

@param
rdi
is a non-null NUL-terminated char16_t string pointer
esi
is the search word
@return
rax points to first result, or NULL if not found
@note this won't return NULL if search character is NUL
@asyncsignalsafe

strchrnul

Returns pointer to first instance of character.

@param
char* s
is a NUL-terminated string
int c
is masked with 255 as byte to search for
@return
char*
pointer to first instance of c, or pointer to NUL terminator if c is not found

strchrnul16

Returns pointer to first instance of character.

@param
rdi
is a non-null NUL-terminated char16_t string pointer
esi
is the search word
@return
rax points to character, or to NUL word if not found
@note this won't return NULL if search character is NUL

strclen

Returns number of characters in UTF-8 string.

@param
char* s
@return
unsigned long

strclen16

Returns number of characters in UTF-16 or UCS-2 string.

@param
unsigned short* s
@return
unsigned long

strcmp

Compares NUL-terminated strings.

@param
char* a
is first non-null NUL-terminated string pointer
char* b
is second non-null NUL-terminated string pointer
@return
int
is <0, 0, or >0 based on uint8_t comparison
@asyncsignalsafe

strcmp16

Compares NUL-terminated UCS-2 strings.

@param
unsigned short* l
unsigned short* r
@return
int
is <0, 0, or >0 based on uint16_t comparison
@asyncsignalsafe

strcmp16to8

@param
unsigned short* s1
char* s2
@return
int

strcmp8to16

Compares UTF-8 and UTF-16 strings.

@param
char* s1
unsigned short* s2
@return
int

strcoll

Compares strings in the C locale.

@param
char* p
char* q
@return
int

strcpy

Copies bytes from 𝑠 to 𝑑 until a NUL is encountered.

@param
char* d
char* s
@return
char*
original dest
@note 𝑑 and 𝑠 can't overlap
@asyncsignalsafe

strcpy16

Copies NUL-terminated UCS-2 or UTF-16 string.

DEST and SRC must not overlap unless DEST ≤ SRC.

@param
unsigned short* dest
is destination memory
unsigned short* src
is a NUL-terminated 16-bit string
@return
unsigned short*
original dest

strcspn

Returns prefix length, consisting of chars not in reject.

@param
rdi
is string
rsi
is reject nul-terminated character set
@return
rax is index of first byte in charset
@see strspn(), strtok_r()
@asyncsignalsafe

strcspn16

Returns prefix length, consisting of chars not in reject. a.k.a. Return index of first byte that's in charset.

@param
unsigned short* s
unsigned short* reject
is nul-terminated character set
@return
unsigned long
@see strspn(), strtok_r()
@asyncsignalsafe

strcspn_pure

Returns prefix length, consisting of chars not in reject. a.k.a. Return index of first byte that's in charset.

@param
char* s
char* reject
is nul-terminated character set
@return
unsigned long
@see strspn(), strtok_r()
@asyncsignalsafe

strdup

Allocates new copy of string.

@param
char* s
is a NUL-terminated byte string
@return
char*
new string or NULL w/ errno
@error ENOMEM

strerror

Converts errno value to string non-reentrantly.

@param
int err
@return
char*
@see strerror_r()

strerror_r

Converts errno value to string.

@param
int err
char* buf
unsigned long size
@return
int
0 on success, or error code

strfry

Jumbles up string.

@param
char* s
@return
char*

strftime

Converts 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
char* s
unsigned long size
char* f
struct tmp* t
@return
unsigned long
bytes copied excluding nul, or 0 on error

strlcat

Appends string SRC to DEST, the BSD way.

@param
char* dest
is a buffer holding a NUL-terminated string
char* src
is a NUL-terminated string
unsigned long size
is byte capacity of dest
@return
unsigned long
strlen(dest) + strlen(src)
@note dest and src can't overlap
@see strncat()

strlcpy

Copies string, the BSD way.

@param
char* d
is buffer which needn't be initialized
char* s
is a NUL-terminated string
unsigned long n
is byte capacity of d
@return
unsigned long
strlen(s)
@note d and s can't overlap
@note we prefer memccpy()

strlen

Returns length of NUL-terminated string.

@param
rdi
is non-null NUL-terminated string pointer
@return
rax is number of bytes (excluding NUL)
@clob ax,dx,cx,xmm3,xmm4
@note h/t agner fog
@asyncsignalsafe

strlen16

Returns length of NUL-terminated char16_t string.

@param
rdi
is non-null NUL-terminated char16_t string pointer
@return
rax is the number of shorts, excluding the NUL
@asyncsignalsafe

strlen_pure

Returns length of NUL-terminated string.

@param
char* s
@return
unsigned long

strncasecmp

Compares NUL-terminated strings case-insensitively w/ limit.

@param
char* a
is first non-null NUL-terminated string pointer
char* b
is second non-null NUL-terminated string pointer
unsigned long n
@return
int
is <0, 0, or >0 based on uint8_t comparison
@asyncsignalsafe

strncasecmp16

Compares NUL-terminated UCS-2 strings case-insensitively w/ limit.

@param
unsigned short* a
is first non-null NUL-terminated char16 string pointer
unsigned short* b
is second non-null NUL-terminated char16 string pointer
unsigned long n
@return
int
is <0, 0, or >0 based on uint8_t comparison
@asyncsignalsafe

strncasecmp16to8

@param
unsigned short* s1
char* s2
unsigned long n
@return
int

strncasecmp8to16

Compares UTF-8 and UTF-16 strings, ignoring case, with limit.

@param
char* s1
unsigned short* s2
unsigned long n
@return
int

strncat

Appends at most 𝑛 bytes from 𝑠 to 𝑑.

@param
char* d
char* s
unsigned long n
@return
char*
𝑑
@note 𝑑 and 𝑠 can't overlap
@asyncsignaslenafe

strnclen

@param
char* s
unsigned long n
@return
unsigned long

strnclen16

@param
unsigned short* p
unsigned long n
@return
unsigned long

strncmp

Compares NUL-terminated strings w/ limit.

@param
char* a
is first non-null NUL-terminated string pointer
char* b
is second non-null NUL-terminated string pointer
unsigned long n
@return
int
is <0, 0, or >0 based on uint8_t comparison
@asyncsignalsafe

strncmp16

Compares NUL-terminated UCS-2 strings w/ limit.

@param
unsigned short* a
is first non-null NUL-terminated char16 string pointer
unsigned short* b
is second non-null NUL-terminated char16 string pointer
unsigned long n
@return
int
is <0, 0, or >0 based on uint8_t comparison
@asyncsignalsafe

strncmp16to8

@param
unsigned short* s1
char* s2
unsigned long n
@return
int

strncmp8to16

Compares UTF-8 and UTF-16 strings, with limit.

@param
char* s1
unsigned short* s2
unsigned long n
@return
int

strncpy

Prepares static search buffer.

  1. If SRC is too long, it's truncated and *not* NUL-terminated.
  2. If SRC is too short, the remainder is zero-filled.
Please note this function isn't designed to prevent untrustworthy data from modifying memory without authorization; the memccpy() function can be used for that purpose.
@param
char* dest
char* src
unsigned long stride
@return
char*
dest
@see stpncpy(), memccpy()
@asyncsignalsafe

strndup

Allocates new copy of string, with byte limit.

@param
char* s
is a NUL-terminated byte string
unsigned long n
if less than strlen(s) will truncate the string
@return
char*
new string or NULL w/ errno
@error ENOMEM

strnlen

Returns length of NUL-terminated string w/ limit.

@param
char* s
is string
unsigned long n
is max length
@return
unsigned long
byte length
@asyncsignalsafe

strnlen16

Returns length of NUL-terminated memory, with limit.

@param
rdi
is non-null memory
rsi
is the maximum number of shorts to consider
@return
rax is the number of shorts, excluding the NUL
@asyncsignalsafe

strnlen16_s

Returns 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
rdi
is a nullable NUL-terminated char16_t string pointer
rsi
is the maximum number of shorts to consider
@return
rax is the number of shorts, excluding the NUL

strnlen_s

Returns 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
rdi
is a nullable NUL-terminated string pointer
rsi
is the maximum number of bytes to consider
@return
rax is the number of bytes, excluding the NUL

strntolower

@param
char* s
unsigned long n
@return
char*

strntoupper

Mutates string to ASCII uppercase w/ limit.

@param
char* s
unsigned long n
@return
char*
string
@praam s is string
@praam n is max bytes to consider

strnwidth

Returns monospace display width of UTF-8 string.

  • Control codes are discounted
  • ANSI escape sequences are discounted
  • East asian glyphs, emoji, etc. count as two
@param
char* s
is NUL-terminated string
unsigned long n
is max bytes to consider
unsigned long o
is offset for doing tabs
@return
int
monospace display width

strnwidth16

Returns monospace display width of UTF-16 or UCS-2 string.

@param
unsigned short* p
unsigned long n
unsigned long o
@return
int

strpbrk

Returns pointer to first byte matching any in accept, or NULL.

@param
char* s
char* accept
@return
char*
@asyncsignalsafe

strpbrk16

Returns pointer to first byte matching any in accept, or NULL.

@param
unsigned short* s
unsigned short* accept
@return
unsigned short*
@asyncsignalsafe

strptime

@param
char* s
char* f
struct tm* tm
@return
char*

strrchr

Searches for last instance of character in string.

@param
char* s
is NUL-terminated string to search
int c
is treated as unsigned char
@return
char*
address of last c in s, or NULL if not found
@asyncsignalsafe

strrchr16

Searches for last instance of char16_t in string.

@param
unsigned short* s
is NUL-terminated char16_t string to search
int c
is treated as char16_t
@return
unsigned short*
address of last c in s, or NULL if not found
@asyncsignalsafe

strsak

Swiss army knife of string character scanning. Used to be fourteen fast functions in one.

@param
rdi
is non-null string memory
rsi
is max number of bytes to consider
dl
is search character #1
dh
is search character #2
r8
is subtracted from result (for length vs. pointer)
r9
masks result if DH is found (for NUL vs. NULL)
r10
masks result on bytes exhausted (for length v. NULL)
@return
rax end pointer after r8/r9/r10 modifications

strsak16

Swiss Army Knife of string char16_t scanning. Sixteen fast functions in one.

@param
rdi
is non-null string memory
rsi
is max number of shorts to consider
dx
is search character #1
r11w
is search character #2
r8
is subtracted from result (for length vs. pointer)
r9
masks result if DH is found (for NUL vs. NULL)
r10
masks result on shorts exhausted (for length v. NULL)
@return
rax end pointer after r8/r9/r10 modifications

strsep

Tokenizes 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
char** str
on first call points to var holding string to be tokenized and is used by this function to track state on subsequent calls
char* delim
is a set of characters that constitute separators
@return
char*
next token or NULL when we've reached the end or *str==NULL
@note unlike strtok() this does empty tokens and is re-entrant

strsignal

Returns name associated with signal code.

@param
int sig
@return
char*
@see sigaction()

strspn

Returns prefix length, consisting of chars in accept.

@param
char* s
char* accept
is nul-terminated character set
@return
unsigned long
@see strcspn(), strtok_r()
@asyncsignalsafe

strspn16

Returns prefix length, consisting of chars in accept.

@param
unsigned short* s
unsigned short* accept
is nul-terminated character set
@return
unsigned long
@see strcspn(), strtok_r()
@asyncsignalsafe

strstr

Searches for substring.

@param
char* haystack
is the search area, as a NUL-terminated string
char* needle
is the desired substring, also NUL-terminated
@return
char*
pointer to first substring within haystack, or NULL
@asyncsignalsafe
@see memmem()

strstr16

Searches for substring.

@param
unsigned short* haystack
is the search area, as a NUL-terminated string
unsigned short* needle
is the desired substring, also NUL-terminated
@return
unsigned short*
pointer to first substring within haystack, or NULL
@asyncsignalsafe
@see memmem()

strtod

@param
char* s00
char** se
@return
double

strtodg

@param
char* s00
char** se
struct FPI* fpi
int* exp
unsigned int* bits
@return
int

strtodI

@param
char* s
char** sp
double* dd
@return
int

strtof

@param
char* s
char** sp
@return
float

strtoId

@param
char* s
char** sp
double* f0
double* f1
@return
int

strtoIdd

@param
char* s
char** sp
double* f0
double* f1
@return
int

strtoIf

@param
char* s
char** sp
float* f0
float* f1
@return
int

strtoimax

Decodes 128-bit signed integer from ASCII string.

@param
char* s
is a non-NULL NUL-terminated string
char** endptr
if non-NULL will always receive a pointer to the char following the last one this function processed, which is usually the NUL byte, or in the case of invalid strings, would point to the first invalid character
int base
can be anywhere between [2,36] or 0 to auto-detect based on the the prefixes 0 (octal), 0x (hexadecimal), 0b (binary), or decimal (base 10) by default.
@return
__int128
the decoded saturated number
@see strtoumax

strtoIx

@param
char* s
char** sp
void* a
void* b
@return
int

strtok

Extracts non-empty tokens from string.

@param
char* s
is mutated and should be NULL on subsequent calls
char* sep
is a NUL-terminated set of bytes to consider separators
@return
char*
pointer to next token or NULL for end
@see strtok_r() and strsep() for superior functions
@notasyncsignalsafe

strtok_r

Extracts non-empty tokens from string.

@param
char* s
is mutated and should be NULL on subsequent calls
char* sep
is a NUL-terminated set of bytes to consider separators
char** state
tracks progress between calls
@return
char*
pointer to next token or NULL for end
@see strsep() which is similar
@asyncsignalsafe

strtol

Converts string to number.

@param
char* s
char** opt_out_end
int optional_base
is recommended as 0 for flexidecimal
@return
long

strtold

Converts string to long double.

@param
char* s
char** endptr
@return
long double

strtoll

@param
char* s
char** endptr
int optional_base
@return
long

strtolower

Mutates string to ASCII lowercase.

@param
char* s
@return
char*
string
@praam s is string

strtonum

Converts string to integer, the BSD way.

@param
char* nptr
long minval
long maxval
char** errstr
@return
long

strtopd

@param
char* s
char** sp
double* d
@return
int

strtopdd

@param
char* s
char** sp
double* dd
@return
int

strtopf

@param
char* s
char** sp
float* f
@return
int

strtopx

@param
char* s
char** sp
void* V
@return
int

strtord

@param
char* s
char** sp
int rounding
double* d
@return
int

strtordd

@param
char* s
char** sp
int rounding
double* dd
@return
int

strtorf

@param
char* s
char** sp
int rounding
float* f
@return
int

strtorx

@param
char* s
char** sp
int rounding
void* L
@return
int

strtoul

@param
char* s
char** endptr
int optional_base
@return
unsigned long

strtoull

@param
char* s
char** endptr
int optional_base
@return
unsigned long

strtoumax

Decodes 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
char* s
char** endptr
int base
@return
unsigned __int128

strtoupper

Mutates string to ASCII uppercase.

@param
char* s
@return
char*
string
@praam s is string

strverscmp

Compares two version strings.

@param
char* l0
char* r0
@return
int

strwidth

Returns monospace display width of UTF-8 string.

  • Control codes are discounted
  • ANSI escape sequences are discounted
  • East asian glyphs, emoji, etc. count as two
@param
char* s
is NUL-terminated string
unsigned long o
is string offset for computing tab widths
@return
int
monospace display width

strwidth16

Returns monospace display width of UTF-16 or UCS-2 string.

@param
unsigned short* s
unsigned long o
@return
int

__subvdi3

Returns 𝑥-𝑦, aborting on overflow.

@param
rdi
is int64 𝑥
rsi
is int64 𝑦
@return
rax is 𝑥-𝑦
@see -ftrapv

__subvsi3

Returns 𝑥-𝑦, aborting on overflow.

@param
edi
is int32 𝑥
esi
is int32 𝑦
@return
@see -ftrapv

__subvti3

Returns 𝑥-𝑦, aborting on overflow.

@param
rdi:rsi
is int128 𝑥
rdx:rcx
is int128 𝑦
@return
rdx:rax is 𝑥-𝑦
@see -ftrapv


symlinkat

Creates 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
char* target
can be relative and needn't exist
int newdirfd
char* linkpath
is what gets created
@return
int
0 on success, or -1 w/ errno
@note Windows NT only lets admins do this
@asyncsignalsafe

sync

Flushes file system changes to disk by any means necessary.

@return
void

sync_file_range

Flushes subset of file to disk.

@param
int fd
long offset
is page rounded
long bytes
is page rounded; 0 means until EOF
unsigned int flags
can have SYNC_FILE_RANGE_{WAIT_BEFORE,WRITE,WAIT_AFTER}
@return
int
@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_chdir_nt

@param
char* path
@return
int

sys_close_nt

@param
struct kEmptyFd* fd
@return
int

sys_dup3

@param
int oldfd
int newfd
int flags
@return
int

sys_dup_nt

Implements dup(), dup2(), and dup3() for Windows NT.

@param
int oldfd
int newfd
int flags
@return
int

sys_execve

@param
char* prog
char** argv
char** envp
@return
int

sys_execve_nt

@param
char* program
char** argv
char** envp
@return
int

sys_faccessat_nt

@param
int dirfd
char* path
int mode
unsigned int flags
@return
int

sys_fadvise_nt

@param
int fd
unsigned long offset
unsigned long len
int advice
@return
int

sys_fchdir_nt

@param
int dirfd
@return
int

sys_fcntl_nt

@param
int fd
int cmd
unsigned int arg
@return
int

sys_fdatasync_nt

@param
int fd
@return
int

sys_flock_nt

@param
int fd
int op
@return
int


sys_fstat

Supports fstat(), etc. implementations.

@param
int fd
struct stat* st
@return
int
@asyncsignalsafe

sys_fstat_metal

@param
int fd
struct stat* st
@return
int

sys_fstat_nt

@param
long handle
struct stat* st
@return
int

sys_fstatat

Supports stat(), lstat(), fstatat(), etc. implementations.

@param
int dirfd
char* pathname
struct stat* st
int flags
@return
int
@asyncsignalsafe

sys_fstatat_nt

@param
int dirfd
char* path
struct stat* st
unsigned int flags
@return
int

sys_ftruncate_nt

@param
int fd
unsigned long length
@return
int

sys_getcwd_nt

@param
char* buf
unsigned long size
@return
char*

sys_getcwd_xnu

@param
char* res
unsigned long size
@return
char*


sys_getpriority_nt

@param
int ignored
@return
int

sys_getrusage_nt

@param
int who
struct rusage* usage
@return
int

sys_getsetpriority_nt

@param
int which
unsigned int who
int value
int(*)() impl
@return
int

sys_gettimeofday_nt

@param
struct it_value* tv
struct timezone* tz
@return
int

sys_isatty_nt

@param
int fd
@return
int

sys_kill_nt

@param
int pid
int sig
@return
int


sys_lseek_nt

@param
int fd
long offset
int whence
@return
long

sys_madvise_nt

@param
void* addr
unsigned long length
int advice
@return
int

sys_mkdirat_nt

@param
int dirfd
char* path
unsigned int mode
@return
int

sys_mmap

Obtains 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
void* addr
unsigned long size
int prot
int flags
int fd
long off
@return
struct DirectMap

sys_mmap_metal

@param
void* paddr
unsigned long size
int prot
int flags
int fd
long off
@return
struct res

sys_mmap_nt

@param
void* addr
unsigned long size
int prot
int flags
long handle
long off
@return
struct dm

sys_msync_nt

@param
void* addr
unsigned long size
int flags
@return
int

sys_munmap_metal

@param
void* addr
unsigned long size
@return
int

sys_nanosleep_nt

@param
struct st_ctim* req
struct st_ctim* rem
@return
int

sys_open_nt

@param
int dirfd
char* file
unsigned int flags
int mode
@return
long

sys_openat_metal

@param
int dirfd
char* file
int flags
unsigned int mode
@return
int

sys_pipe

@param
int* fds
@return
int

sys_pipe2

@param
int* pipefd
unsigned int flags
@return
int

sys_pipe_nt

@param
int* pipefd
unsigned int flags
@return
int

sys_read_nt

@param
struct kEmptyFd* fd
struct iovec* iov
unsigned long iovlen
long opt_offset
@return
long

sys_readv_metal

@param
struct kEmptyFd* fd
struct iovec* iov
int iovlen
@return
long

sys_readv_serial

@param
struct kEmptyFd* fd
struct iovec* iov
int iovlen
@return
long

sys_renameat_nt

@param
int olddirfd
char* oldpath
int newdirfd
char* newpath
@return
int


sys_setitimer_nt

@param
int which
struct itv* newvalue
struct itv* out_opt_oldvalue
@return
int

sys_setpriority_nt

@param
int nice
@return
int

sys_symlinkat_nt

@param
char* target
int newdirfd
char* linkpath
@return
int

sys_sync_nt

Flushes all open file handles and, if possible, all disk drives.

@return
int

sys_sysinfo_nt

@param
struct sysinfo* info
@return
int

sys_truncate_nt

@param
char* path
unsigned long length
@return
int

sys_unlinkat_nt

@param
int dirfd
char* path
int flags
@return
int

sys_utimensat

@param
int dirfd
char* path
struct st_ctim* ts
int flags
@return
int

sys_utimensat_nt

@param
int dirfd
char* path
ANONYMOUS-STRUCT* ts
int flags
@return
int

sys_utimensat_xnu

@param
int dirfd
char* path
struct st_ctim* ts
int flags
@return
int

sys_utimes_nt

@param
char* path
struct it_value* tv
@return
int

sys_wait4_nt

@param
int pid
int* opt_out_wstatus
int options
struct rusage* opt_out_rusage
@return
int

sys_write_nt

@param
struct kEmptyFd* fd
struct iovec* iov
unsigned long iovlen
long opt_offset
@return
long

sys_writev_metal

@param
struct kEmptyFd* fd
struct iovec* iov
int iovlen
@return
long

sys_writev_serial

@param
struct kEmptyFd* fd
struct iovec* iov
int iovlen
@return
long

sys_xinet_ntop

Formats internet address to string, or dies.

@param
int af
can be AF_INET, e.g. addr->sin_family
void* src
is the binary-encoded address, e.g. &addr->sin_addr
@return
char*
allocated IP address string, which must be free()'d

syscall

Performs 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
%rdi
is system call ordinal, which isn't translated, and must be correct for the underlying host system
%rsi,%rdx,%rcx,%r8,%r9
may supply parameters 1 through 5
sixth
is optionally pushed on the stack before call
@return
%rax has result, or -1 w/ errno on failure

syscon_start

Sections 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

sysconf

Returns configuration value about system.

@param
int thing
can be _SC_XXX
@return
long

sysinfo

Returns amount of system ram, cores, etc.

@param
struct sysinfo* info
@return
int
0 on success or -1 w/ errno
@error ENOSYS, EFAULT

system

Launches program with system command interpreter.

@param
char* cmdline
is an interpreted Turing-complete command
@return
int
-1 if child process couldn't be created, otherwise a wait status that can be accessed using macros like WEXITSTATUS(s)

systemexec

Executes system command replacing current process.

@param
char* cmdline
@return
int
@vforksafe

__systemfive

Performs 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
%rax
function ordinal supplied by jump slot
%rdi,%rsi,%rdx,%rcx,%r8,%r9
and rest on stack
@return
%rax:%rdx is result, or -1 w/ errno on error
@clob %rcx,%r10,%r11
@see syscalls.sh

tan

Returns tangent of 𝑥.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0
@domain -(3π/8) < 𝑥 < 3π/8 for best accuracy

tanf

Returns tangent of 𝑥.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0
@domain -(3π/8) < 𝑥 < 3π/8 for best accuracy

tanh

Returns hyperbolic tangent of 𝑥.

@param
double x
@return
double

tanhf

Returns hyperbolic tangent of 𝑥.

@param
float x
@return
float

tanhl

Returns hyperbolic tangent of 𝑥.

@param
long double x
@return
long double

tanl

Returns tangent of 𝑥.

@param
𝑥
is an 80-bit long double passed on stack in 16-bytes
@return
%st stores result

tarjan

Determines order of things in network and finds tangled clusters too.

@param
int vertex_count
is the number of items in the vertices array
int[2]* edges
are grouped directed links between indices of vertices, which can be thought of as "edge[i][0] depends on edge[i][1]" or "edge[i][1] must come before edge[i][0]" in topological order
int edge_count
is the number of items in edges, which may be 0 if there aren't any connections between vertices in the graph
int* out_sorted
receives indices into the vertices array in topologically sorted order, and must be able to store vertex_count items, and that's always how many are stored
int* out_opt_components
receives indices into the out_sorted array, indicating where each strongly-connected component ends; must be able to store vertex_count items; and it may be NULL
int* out_opt_componentcount
receives the number of cycle indices written to out_opt_components, which will be vertex_count if there aren't any cycles in the graph; and may be NULL if out_opt_components is NULL
@return
int
0 on success or -1 w/ errno
@error ENOMEM
@note Tarjan's Algorithm is O(|V|+|E|)

tcgetattr

Obtains the termios struct.

@param
int fd
open file descriptor that isatty()
struct termios* tio
is where result is stored
@return
int
-1 w/ errno on error
@asyncsignalsafe

tcgetpgrp

Returns which process group controls terminal.

@param
int fd
@return
int
@asyncsignalsafe

tcsetattr

Sets struct on teletypewriter w/ drains and flushes.

@param
int fd
open file descriptor that isatty()
int opt
can be:
  • TCSANOW: sets console settings
  • TCSADRAIN: drains output, and sets console settings
  • TCSAFLUSH: drops input, drains output, and sets console settings
struct termios* tio
@return
int
0 on success, -1 w/ errno
@asyncsignalsafe

tcsetpgrp

Puts process group in control of terminal.

@param
int fd
int pgrp
@return
int
@asyncsignalsafe

telldir

Returns offset into directory data.

@param
struct dirstream* dir
@return
long

tempnam

Creates name for temporary file.

@param
char* dir
char* pfx
@return
char*

__text_windows_start

Special 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

time

Returns time as seconds from UNIX epoch.

@param
long* opt_out_ret
can receive return value on success
@return
long
seconds since epoch, or -1 w/ errno
@asyncsignalsafe

time2posix

@param
long t
@return
long

timegm

@param
struct mytm* tmp
@return
long

timelocal

@param
struct mytm* tmp
@return
long

timeoff

@param
struct mytm* tmp
long offset
@return
long

times

Returns accounting data for process on time-sharing system.

@param
struct tms* out_times
@return
long

TimeSpecToFileTime

Converts UNIX nanosecond timestamp to Windows COBOL timestamp.

@param
struct ts ts
@return
ANONYMOUS-STRUCT

TimeToFileTime

@param
long t
@return
ANONYMOUS-STRUCT

TimeValToFileTime

@param
struct it_value* tv
@return
ANONYMOUS-STRUCT

timingsafe_memcmp

Lexicographically 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
void* b1
void* b2
unsigned long len
@return
int
@note each byte is interpreted as unsigned char

tinydivsi

Support 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
rdi
is number to divide
cl
is magnum #1
rdx
is magnum #2
@return
quotient

tinystrlen

8-bit strlen that's tiny and near optimal if data's tiny.

@param
RDI
is char *s
EAX
is unsigned length
@return
@see libc/nexgen32e/strsak.S

tinystrlen16

16-bit strlen that's tiny and near optimal if data's tiny.

@param
RDI
is char16_t *s
EAX
is unsigned length
@return
@see libc/nexgen32e/strsak16.S

tinystrncmp

Compares strings w/ limit & no-clobber greg abi.

@param
%rdi
is first string
%rsi
is second string
%rdx
is max length
@return
<0, 0, or >0 depending on comparison
@clob flags only
@asyncsignalsafe

tinystrnlen

8-bit strnlen that's tiny and near optimal if data's tiny.

@param
RDI
is char *s
RSI
is size_t n
EAX
is unsigned length
@return
@see libc/nexgen32e/strsak.S

tinystrnlen16

16-bit strnlen that's tiny and near optimal if data's tiny.

@param
RDI
is char16_t *s
RSI
is size_t n
EAX
is unsigned length
@return
@see libc/nexgen32e/strsak16.S

tinywcslen

32-bit strlen that's tiny and near optimal if data's tiny.

@param
RDI
is wchar_t *s
EAX
is unsigned length
@return
@see libc/nexgen32e/strsak32.S

tinywcsnlen

32-bit strnlen that's tiny and near optimal if data's tiny.

@param
RDI
is wchar_t *s
RSI
is size_t n
EAX
is unsigned length
@return
@see libc/nexgen32e/strsak32.S

tmpfile

Creates a temporary file.

@return
struct FILE*
@see mkostempsm(), kTmpPath

tolower

Converts character to lower case.

@param
int c
@return
int

touch

Creates new file or changes modified time on existing one.

@param
char* file
is a UTF-8 string, which may or may not exist
unsigned int mode
is an octal user/group/other permission, e.g. 0755
@return
int
0 on success, or -1 w/ errno
@see creat()

toupper

Converts character to upper case.

@param
int c
@return
int

towlower

Converts wide character to lower case.

@param
unsigned int wc
@return
unsigned int

towupper

Converts wide character to upper case.

@param
unsigned int wc
@return
unsigned int

tpdecode

Thompson-Pike Varint Decoder.

@param
char* s
is a NUL-terminated string
unsigned int* out
@return
int
number of bytes successfully consumed or -1 w/ errno
@note synchronization is performed
@see libc/str/tpdecodecb.internal.h (for implementation)
@deprecated

tpenc

Encodes Thompson-Pike varint.

@param
edi
is int to encode
@return
rax is word-encoded byte buffer
@note invented on a napkin in a new jersey diner

tpencode

Thompson-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
char* p
is what ch gets encoded to
unsigned long size
is the number of bytes available in buf
unsigned int wc
int awesome
mode enables numbers the IETF unilaterally banned
@return
unsigned int
number of bytes written
@note this encoding was designed on a napkin in a new jersey diner
@deprecated

tprecode16to8

Transcodes UTF-16 to UTF-8.

@param
char* dst
is output buffer
unsigned long dstsize
is bytes in dst
unsigned short* src
is NUL-terminated UTF-16 input string
@return
struct r
ax bytes written excluding nul
dx index of character after nul word in src

tprecode8to16

Transcodes UTF-8 to UTF-16.

@param
unsigned short* dst
is output buffer
unsigned long dstsize
is shorts in dst
char* src
is NUL-terminated UTF-8 input string
@return
struct r
ax shorts written excluding nul
dx index of character after nul word in src

TrackMemoryInterval

@param
struct _mmi* mm
int x
int y
long h
int prot
int flags
@return
int

triplf

Hoses interrupt descriptor table and triple-faults the system.

@return
@see youtu.be/GIKfEAF2Yhw?t=67
@mode long,legacy,real

trunc

Rounds to integer, toward zero.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half of %xmm0
@define trunc(𝑥+copysign(.5,𝑥))
@see round(),rint(),nearbyint()
@see roundsd $_MM_FROUND_TO_ZERO|_MM_FROUND_NO_EXC,%xmm0,%xmm0

truncate

Reduces or extends underlying physical medium of file.

If file was originally larger, content >length is lost.

@param
char* path
must exist
unsigned long length
@return
int
0 on success or -1 w/ errno
@see ftruncate()
@error ENOENT

truncf

Rounds to integer, toward zero.

@param
𝑥
is float scalar in low quarter of %xmm0
@return
float scalar in low quarter of %xmm0
@define trunc(𝑥+copysign(.5,𝑥))
@see round(),rint(),nearbyint()
@see roundss $_MM_FROUND_TO_ZERO|_MM_FROUND_NO_EXC,%xmm0,%xmm0

truncl

Rounds to integer, toward zero.

@param
𝑥
is long double passed on stack
@return
long double in %st

ttyname

@param
int fd
@return
char*

ttyname_r

@param
int fd
char* buf
unsigned long size
@return
int

tzcnt

Finds 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
edi
is 32-bit unsigned 𝑥 value
@return
eax number in range [0,32) or 32 if 𝑥 is 0
@see also treasure trove of nearly identical functions

tzcntl

Finds 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
rdi
is 64-bit unsigned 𝑥 value
@return
rax number in range [0,64) or 64 if 𝑥 is 0
@see also treasure trove of nearly identical functions

tzcntll

Finds 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
rdi
is 64-bit unsigned 𝑥 value
@return
rax number in range [0,64) or 64 if 𝑥 is 0
@see also treasure trove of nearly identical functions

tzname

@type
char*[2]

tzset

@return
void

__udivmodti4

Performs 128-bit unsigned division and remainder.

@param
unsigned __int128 a
is dividend
unsigned __int128 b
is divisor
unsigned __int128* rem
receives remainder if not NULL
@return
unsigned __int128

uint128toarray_radix10

Converts unsigned 128-bit integer to string.

@param
unsigned __int128 i
char* a
needs at least 40 bytes
@return
unsigned long
bytes written w/o nul

uint64toarray

@param
unsigned long i
char* a
int r
@return
unsigned long

uint64toarray_fixed16

@param
unsigned long x
char* b
unsigned char k
@return
unsigned long

uint64toarray_radix10

Converts unsigned 64-bit integer to string.

@param
unsigned long i
char* a
needs at least 21 bytes
@return
unsigned long
bytes written w/o nul

uint64toarray_radix16

@param
unsigned long x
char* b
@return
unsigned long

uint64toarray_radix8

Converts unsigned 64-bit integer to octal string.

@param
unsigned long i
char* a
needs at least 24 bytes
@return
unsigned long
bytes written w/o nul

uname

Asks kernel to give us the uname -a data.

@param
struct utsname* lool
@return
int
0 on success, or -1 w/ errno

unbing

Turns CP437 unicode glyph into its binary representation.

@param
int c
is a unicode character
@return
int
byte representation, or -1 if ch wasn't ibm cp437
@see bing()

unbingbuf

Decodes 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
void* buf
is caller owned
unsigned long size
is byte length of buf
unsigned short* glyphs
is UCS-2 encoded CP437 representation of binary data
int fill
if -1 will memset any remaining buffer space
@return
void*
@note no NUL terminator is added to end of buf
@see tunbing(), unbingstr(), unbing()

unbingstr

Decodes human-readable CP437 glyphs into binary, e.g.

CHECK_EQ(0, memcmp(gc(unbingstr(u" ☺☻♥♦")), "\0\1\2\3\4", 5));
@param
unsigned short* s
@return
void*
@note no NUL terminator is added to end of buf
@see tunbing(), unbingbuf(), unbing()

uncompress

Decompresses 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
int
Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In the case where there is not enough room, uncompress() will fill the output buffer with the uncompressed data up to that point.

uncompress2

Same 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
int

undeflate

Decompresses raw DEFLATE data.

This is 10x smaller and 10x slower than chromium zlib.

@param
void* output
should be followed by a single guard page, and have 36kb of guard pages preceding it too because buffer overflows are part of the design of this algorithm
unsigned long outputsize
void* input
unsigned long inputsize
struct DeflateState* ds
@return
long
@note h/t Phil Katz, David Huffman, Claude Shannon

ungetc

@param
int c
struct FILE* f
@return
int

ungray

Decodes gray code.

@param
unsigned int x
@return
unsigned int
@see https://en.wikipedia.org/wiki/Gray_code
@see gray()

unhexbuf

@param
void* buf
unsigned long size
char* hexdigs
@return
void*

unhexstr

@param
char* hexdigs
@return
void*

unhilbert

Decodes Hilbert space-filling curve.

@param
long n
long i
@return
struct m
@see https://en.wikipedia.org/wiki/Hilbert_curve
@see hilbert()



unlinkat

Deletes inode and maybe the file too.

@param
int dirfd
is normally AT_FDCWD but if it's an open directory and path is relative, then path becomes relative to dirfd
char* path
is the thing to delete
int flags
can have AT_REMOVEDIR
@return
int
0 on success, or -1 w/ errno

unlockpt

@param
int fd
@return
int

unmorton

Deinterleaves bits.

@param
unsigned long i
@return
struct axdx_t
deinterleaved coordinate {ax := 𝑦, dx := 𝑥}
@see en.wikipedia.org/wiki/Z-order_curve
@see morton()

unrijndaelinit

Computes key schedule for unrijndael().

@param
struct Rijndael* ctx
unsigned int n
is 14 for AES-256, 12 for AES-192, and 10 for AES-128
unsigned int k1
unsigned int k2
@return
void

unsetenv

Removes environment variable.

@param
char* s
@return
int

unsleb128

Decodes 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
void* buf
unsigned long size
__int128* out
@return
int

UntrackMemoryIntervals

@param
void* addr
unsigned long size
@return
int

usleep

Sleeps for particular amount of microseconds.

@param
unsigned int microseconds
@return
int

utime

Changes last accessed/modified times on file.

@param
char* path
struct utimbuf* times
if NULL means now
@return
int
0 on success or -1 w/ errno
@asyncsignalsafe

utimensat

Sets atime/mtime on file, the modern way.

@param
int dirfd
char* path
struct st_ctim* ts
is atime/mtime, or null for current time
int flags
can have AT_SYMLINK_NOFOLLOW
@return
int
@note no xnu/rhel5 support if dirfd≠AT_FDCWD∨flags≠0
@asyncsignalsafe

utimes

Changes last accessed/modified times on file.

@param
char* path
struct it_value* tv
@return
int
0 on success or -1 w/ errno
@asyncsignalsafe
@see stat()

valloc

Equivalent to memalign(4096, n).

@param
rdi
is number of bytes needed
@return
rax is memory address, or NULL w/ errno
@see dlvalloc()

vasprintf

Formats string w/ dynamic memory allocation.

@param
char** strp
char* fmt
struct __va_list* va
@return
int
complete bytes written (excluding NUL) or -1 w/ errno
@see xasprintf() for a better API

vcls

Clears display page.

@param
es:di
arbitrary address within video page
@return
es:ax starting address
@mode long,legacy,real

vcscanf

String / 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.

  • %d parses integer
  • %ms parses string allocating buffer assigning pointer
@param
int(*)() callback
supplies UTF-8 characters using -1 sentinel
int(*)() unget
void* arg
char* fmt
is a computer program embedded inside a c string, written in a domain-specific programming language that, by design, lacks Turing-completeness
struct __va_list* va
points to the variadic argument state
@return
int
@see libc/fmt/pflink.h (dynamic memory is not a requirement)

vdprintf

Formats string directly to system i/o device.

@param
int fd
char* fmt
struct __va_list* va
@return
int
@asyncsignalsafe
@vforksafe

verr

@param
int eval
char* fmt
struct __va_list* va
@noreturn

verrx

@param
int eval
char* fmt
struct __va_list* va
@noreturn

vflogf

Writes 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
unsigned int level
char* file
int line
struct FILE* f
char* fmt
struct __va_list* va
@return
void

vflogf_onfail

Takes corrective action if logging is on the fritz.

@param
struct FILE* f
@return
void

vfork

Forks 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
pid of child process or 0 if forked process
@returnstwice
@vforksafe

vfprintf

@param
struct FILE* f
char* fmt
struct __va_list* va
@return
int

vfscanf

Stream decoder.

@param
struct FILE* stream
char* fmt
struct __va_list* ap
@return
int
@see libc/fmt/vcscanf.h

vmsplice

Transfers memory to pipe.

@param
int fd
struct iovec* chunks
long count
unsigned int flags
can have SPLICE_F_{MOVE,NONBLOCK,MORE,GIFT}
@return
long
number of bytes actually transferred, or -1 w/ errno

vprintf

@param
char* fmt
struct __va_list* va
@return
int

vscanf

String decoder.

@param
char* fmt
struct __va_list* ap
@return
int
@see libc/fmt/vcscanf.h

vsnprintf

Formats string to buffer w/ preexisting vararg state.

@param
char* buf
stores output and a NUL-terminator is always written, provided buf!=NULL && size!=0
unsigned long size
is byte capacity buf
char* fmt
struct __va_list* va
@return
int
number of bytes written, excluding the NUL terminator; or, if the output buffer wasn't passed, or was too short, then the number of characters that *would* have been written is returned
@see palandprintf() and printf() for detailed documentation
@asyncsignalsafe
@vforksafe

vsprintf

Formats string to buffer hopefully large enough w/ vararg state.

@param
char* buf
char* fmt
struct __va_list* va
@return
int
@see palandprintf() and printf() for detailed documentation
@see vsnprintf() for modern alternative w/ buf size param

vsscanf

Decodes string.

@param
char* str
char* fmt
struct __va_list* va
@return
int
@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

vwarn

@param
char* fmt
struct __va_list* va
@return
void

vwarnx

@param
char* fmt
struct __va_list* va
@return
void

wait

Waits for status to change on any child process.

@param
int* opt_out_wstatus
optionally returns status code, and *wstatus may be inspected using WEEXITSTATUS(), etc.
@return
int
process id of terminated child or -1 w/ errno
@asyncsignalsafe
@vforksafe

wait3

Waits for status to change on any child process.

@param
int* opt_out_wstatus
optionally returns status code, and *wstatus may be inspected using WEEXITSTATUS(), etc.
int options
can have WNOHANG, WUNTRACED, WCONTINUED, etc.
struct rusage* opt_out_rusage
optionally returns accounting data
@return
int
process id of terminated child or -1 w/ errno
@asyncsignalsafe

wait4

Waits for status to change on process.

@param
int pid
>0 targets specific process, =0 means any proc in a group, -1 means any child process, <-1 means any proc in specific group
int* opt_out_wstatus
optionally returns status code, and *wstatus may be inspected using WEEXITSTATUS(), etc.
int options
can have WNOHANG, WUNTRACED, WCONTINUED, etc.
struct rusage* opt_out_rusage
optionally returns accounting data
@return
int
process id of terminated child or -1 w/ errno
@asyncsignalsafe

waitpid

Waits for status to change on process.

@param
int pid
>0 targets specific process, =0 means any proc in a group, -1 means any child process, <-1 means any proc in specific group
int* opt_out_wstatus
optionally returns status code, and *wstatus may be inspected using WEXITSTATUS(), etc.
int options
can have WNOHANG, WUNTRACED, WCONTINUED, etc.
@return
int
process id of terminated child or -1 w/ errno
@asyncsignalsafe

warn

@param
char* fmt
...
@return
void

warnx

@param
char* fmt
...
@return
void

wchomp

Mutates line to remove line-ending characters.

@param
int* line
is NULL-propagating
@return
int*
@see getline

wcscasecmp

Compares NUL-terminated wide strings case-insensitively.

@param
int* a
is first non-null NUL-terminated string pointer
int* b
is second non-null NUL-terminated string pointer
@return
int
is <0, 0, or >0 based on uint8_t comparison
@asyncsignalsafe

wcscat

Appends 𝑠 to 𝑑.

@param
int* d
int* s
@return
int*
𝑑
@asyncsignalsafe

wcschr

Returns pointer to first instance of character.

@param
rdi
is a non-null NUL-terminated wchar_t string pointer
esi
is the search word
@return
rax points to first result, or NULL if not found
@note this won't return NULL if search character is NUL
@asyncsignalsafe

wcschrnul

Returns pointer to first instance of character.

@param
rdi
is a non-null NUL-terminated wchar_t string pointer
esi
is the search word
@return
rax points to character, or to NUL word if not found
@note this won't return NULL if search character is NUL

wcscmp

Compares NUL-terminated wide strings.

@param
int* a
is first non-null NUL-terminated string pointer
int* b
is second non-null NUL-terminated string pointer
@return
int
is <0, 0, or >0 based on uint8_t comparison
@asyncsignalsafe

wcscpy

Copies NUL-terminated wide character string.

𝑑 and 𝑠 must not overlap unless 𝑑 ≤ 𝑠.

@param
int* d
int* s
@return
int*
original dest
@asyncsignalsafe

wcscspn

Returns prefix length, consisting of chars not in reject. a.k.a. Return index of first byte that's in charset.

@param
int* s
int* reject
is nul-terminated character set
@return
unsigned long
@see strspn(), strtok_r()
@asyncsignalsafe

wcsdup

Allocates copy of wide string.

@param
int* s
@return
int*

wcsendswith

Returns true if s has suffix.

@param
int* s
is a NUL-terminated string
int* suffix
is also NUL-terminated
@return
_Bool

wcslen

Returns length of NUL-terminated wchar_t string.

@param
rdi
is non-null NUL-terminated wchar_t string pointer
@return
rax is the number of chars, excluding the NUL
@asyncsignalsafe

wcsncasecmp

Compares NUL-terminated wide strings case-insensitively w/ limit.

@param
int* a
is first non-null NUL-terminated string pointer
int* b
is second non-null NUL-terminated string pointer
unsigned long n
@return
int
is <0, 0, or >0 based on uint8_t comparison
@asyncsignalsafe

wcsncmp

Compares NUL-terminated wide strings w/ limit.

@param
int* a
is first non-null NUL-terminated string pointer
int* b
is second non-null NUL-terminated string pointer
unsigned long n
@return
int
is <0, 0, or >0 based on uint8_t comparison
@asyncsignalsafe

wcsncpy

@param
int* d
int* s
unsigned long n
@return
int*

wcsnlen

Returns length of NUL-terminated memory, with limit.

@param
rdi
is non-null memory
rsi
is the maximum number of chars to consider
@return
rax is the number of chars, excluding the NUL
@asyncsignalsafe

wcsnlen_s

Returns 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
rdi
is a nullable NUL-terminated wchar_t string pointer
rsi
is the maximum number of chars to consider
@return
rax is the number of chars, excluding the NUL

wcsnwidth

Returns monospace display width of wide character string.

@param
int* pwcs
unsigned long n
unsigned long o
@return
int

wcspbrk

Returns pointer to first byte matching any in accept, or NULL.

@param
int* s
int* accept
@return
int*
@asyncsignalsafe

wcsrchr

Searches for last instance of wchar_t in string.

@param
int* s
is NUL-terminated wchar_t string to search
int c
is the needle
@return
int*
address of last c in s, or NULL if not found
@asyncsignalsafe

wcssak

Swiss army knife of wchar_t string scanning. Seven fast functions in one.

@param
rdi
is non-null wchar_t string memory
rsi
is max number of chars to consider
edx
is search character #1
r11d
is search character #2
r8
is subtracted from result (for length vs. pointer)
r9
masks result if r11w is found (for NUL vs. NULL)
r10
masks result on chars exhausted (for length v. NULL)
@return
rax end pointer after r8/r9/r10 modifications

wcsspn

Returns prefix length, consisting of chars in accept.

@param
int* s
int* accept
is nul-terminated character set
@return
unsigned long
@see strcspn(), strtok_r()
@asyncsignalsafe

wcsstartswith

Returns true if s has prefix.

@param
int* s
is a NUL-terminated string
int* prefix
is also NUL-terminated
@return
_Bool

wcsstr

Searches for substring.

@param
int* haystack
is the search area, as a NUL-terminated string
int* needle
is the desired substring, also NUL-terminated
@return
int*
pointer to first substring within haystack, or NULL
@asyncsignalsafe
@see memmem()

wcstoimax

@param
int* s
int** endptr
int base
@return
__int128

wcstol

@param
int* s
int** end
int opt_base
@return
long

wcswidth

Returns monospace display width of wide character string.

@param
int* pwcs
unsigned long o
@return
int

wctob

@param
unsigned int c
@return
int

wctomb

@param
char* s
int wc
@return
int

wctype

@param
char* name
@return
unsigned int

wcwidth

Returns cell width of monospace character.

@param
int c
@return
int

weakfree

Thunks free() if it's linked, otherwise do nothing.

@return
@see free_s() which can ignore static/stack and clear refs

__winerr

Return path for failed Win32 API calls.

@return
long
-1 w/ few exceptions
@note this is a code-size saving device


winrandish

Returns somewhat randomish number on Windows.

@return
long

wmemchr

Returns pointer to first instance of character in range.

@param
rdi
is a non-null pointer to memory
esi
is the int32_t search word (officially wchar_t)
rdx
is length of memory in chars
@return
rax points to word if found or NULL
@asyncsignalsafe

wmemcpy

@param
int* dest
int* src
unsigned long count
@return
int*

wmemmove

@param
int* dest
int* src
unsigned long count
@return
int*

wmempcpy

@param
int* dest
int* src
unsigned long count
@return
int*

wmemrchr

Searches for last instance of wchar_t in memory region.

@param
rdi
points to data to search
esi
is treated as int32_t (officially wchar_t)
rdx
is short count in rdi
@return
rax is address of last %esi in %rdi, or NULL
@note AVX2 requires Haswell (2014+) or Excavator (2015+)

wmemset

Sets wide memory.

@param
int* dest
int c
unsigned long count
@return
int*
@asyncsignalsafe

write

Writes data to file descriptor.

@param
int fd
is something open()'d earlier
void* buf
is copied from, cf. copy_file_range(), sendfile(), etc.
unsigned long size
in range [1..0x7ffff000] is reasonable
@return
long
[1..size] bytes on success, or -1 w/ errno; noting zero is impossible unless size was passed as zero to do an error check
@see read(), pwrite(), writev(), SIGPIPE
@asyncsignalsafe

xasprintf

Returns dynamically formatted string.

@param
char* fmt
...
@return
char*
must be free()'d or gc()'d
@note greatest of all C functions

xbarf

Writes data to file.

@param
char* path
void* data
unsigned long size
can be -1 to strlen(data)
@return
int
if failed, -1 w/ errno
@note this is uninterruptible

xcalloc

Allocates initialized memory, or dies.

@param
unsigned long count
unsigned long size
@return
void*

xdie

@return
void

xdirname

Returns directory portion of path.

@param
char* path
@return
char*

xdtoa

Converts double to string the easy way.

@param
double d
@return
char*
string that needs to be free'd

xdtoaf

Converts double to string w/ high-accuracy the easy way.

@param
float d
@return
char*
string that needs to be free'd

xdtoal

Converts double to string the easy way.

@param
long double d
@return
char*
string that needs to be free'd

xgetline

Reads line from stream.

@param
struct FILE* f
@return
char*
allocated line that needs free() and usually chomp() too, or NULL on ferror() or feof()
@see getline() for a more difficult api

xiso8601ts

Returns allocated string representation of nanosecond timestamp.

@param
struct ts* opt_ts
@return
char*

xiso8601tv

Returns allocated string representation of microsecond timestamp.

@param
struct it_value* opt_tv
@return
char*

xjoinpaths

Joins paths, e.g.

"a"  + "b"  → "a/b"
"a/" + "b"  → "a/b"
"a"  + "b/" → "a/b/"
"a"  + "/b" → "/b"
"."  + "b"  → "b"
""   + "b"  → "b"
@param
char* path
char* other
@return
char*
newly allocated string of resulting path

xmalloc

Allocates uninitialized memory, or dies.

@param
unsigned long bytes
@return
void*

xmemalign

Allocates aligned memory, or dies.

@param
unsigned long alignment
unsigned long bytes
@return
void*

xmemalignzero

Allocates aligned cleared memory, or dies.

@param
unsigned long alignment
unsigned long bytes
@return
void*

xrealloc

Relocates, 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
void* p1
unsigned long newsize
@return
void*

xsigaction

Installs handler for kernel interrupt, e.g.:

onctrlc(sig) { exit(128+sig); }
CHECK_NE(-1, xsigaction(SIGINT, onctrlc, SA_RESETHAND, 0, 0));
@param
int sig
can be SIGINT, SIGTERM, etc.
void* handler
is SIG_DFL, SIG_IGN, or a pointer to a 0≤arity≤3 callback function passed (sig, siginfo_t *, ucontext_t *).
unsigned long flags
can have SA_RESETHAND, SA_RESTART, SA_SIGINFO, etc.
unsigned long mask
is 1ul«SIG₁[…|1ul«SIGₙ] bitset to block in handler
struct sa* old
optionally receives previous handler
@return
int
0 on success, or -1 w/ errno
@see libc/sysv/consts.sh
@asyncsignalsafe

xslurp

Reads entire file into memory.

@param
char* path
unsigned long* opt_out_size
@return
char*
NUL-terminated malloc'd contents, or NULL w/ errno
@note this is uninterruptible

xstrcat

Concatenates 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
char* s
...
@return
char*
@see gc()

xstrdup

Allocates new copy of string, or dies.

@param
char* s
@return
char*

xstrmul

Multiplies string.

@param
char* s
unsigned long n
@return
char*

xstrndup

Allocates new copy of string, with byte limit.

@param
char* s
is a NUL-terminated byte string
unsigned long n
if less than strlen(s) will truncate the string
@return
char*
new string or NULL w/ errno
@error ENOMEM

xunbing

Decodes 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
unsigned short* binglyphs
@return
void*
@see xunbing(), unbingstr(), unbing()

xunbinga

Same as xunbing() w/ alignment guarantee.

@param
unsigned long a
unsigned short* binglyphs
@return
void*

xvalloc

Allocates page-aligned memory, or dies.

@param
unsigned long size
@return
void*

xvasprintf

Returns dynamically formatted string.

@param
char* fmt
struct __va_list* va
@return
char*
fully formatted string, which must be free()'d
@see xasprintf()

xwrite

Writes data uninterruptibly.

@param
int fd
void* p
unsigned long n
@return
int
0 on success, or -1 w/ errno

z_errmsg

@type
char*[10]

zcalloc

@param
void* opaque
unsigned int items
unsigned int size
@return
void*

zcfree

@param
void* opaque
void* ptr
@return
void

zError

Exported to allow conversion of error code to string for compress() and uncompress()

@param
int err
@return
char*

zipfindcentraldir

Locates 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
unsigned char* p
points to file memory
unsigned long n
is byte size of file
@return
unsigned char*

__zipos_close

Closes compressed object.

@param
int fd
is vetted by close()
@return
int

__zipos_fstat

Reads file metadata from αcτµαlly pδrταblε εxεcµταblε object store.

@param
struct ZiposHandle* h
ANONYMOUS-STRUCT* st
@return
int
@asyncsignalsafe

__zipos_get

Returns pointer to zip central directory of current executable.

@return
struct zipos*

__zipos_open

Loads compressed file from αcτµαlly pδrταblε εxεcµταblε object store.

@param
struct ZiposUri* name
unsigned int flags
int mode
@return
int
@note don't call open() from signal handlers

__zipos_parseuri

Extracts information about ZIP URI if it is one.

@param
char* uri
struct ZiposUri* out
@return
long

__zipos_read

Reads data from zip store object.

@param
struct ZiposHandle* h
struct iovec* iov
unsigned long iovlen
long opt_offset
@return
long
[1..size] bytes on success, 0 on EOF, or -1 w/ errno; with exception of size==0, in which case return zero means no error
@asyncsignalsafe

__zipos_stat

Reads file metadata from αcτµαlly pδrταblε εxεcµταblε object store.

@param
struct ZiposUri* name
ANONYMOUS-STRUCT* st
@return
int
@asyncsignalsafe

zlibCompileFlags

@return
unsigned long

zlibVersion

The 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
char*