honeybadger

cosmopolitan libc

your build-once run-anywhere c library

objects

__assert_disable
daylight
E2BIG
EACCES
EADDRINUSE
EADDRNOTAVAIL
EAFNOSUPPORT
EAGAIN
EALREADY
EBADF
EBADMSG
EBUSY
ECANCELED
ECHILD
ECONNABORTED
ECONNREFUSED
ECONNRESET
EDEADLK
EDESTADDRREQ
EDOM
EDQUOT
EEXIST
EFAULT
EFBIG
EFTYPE
EHOSTDOWN
EHOSTUNREACH
EIDRM
EILSEQ
EINPROGRESS
EINTR
EINVAL
EIO
EISCONN
EISDIR
ELOOP
EMEDIUMTYPE
EMFILE
EMLINK
EMSGSIZE
EMULTIHOP
ENAMETOOLONG
ENETDOWN
ENETRESET
ENETUNREACH
ENFILE
ENOBUFS
ENODATA
ENODEV
ENOENT
ENOEXEC
ENOLCK
ENOLINK
ENOMEDIUM
ENOMEM
ENOMSG
ENONET
ENOPROTOOPT
ENOSPC
ENOSR
ENOSTR
ENOSYS
ENOTBLK
ENOTCONN
ENOTDIR
ENOTEMPTY
ENOTRECOVERABLE
ENOTSOCK
ENOTSUP
ENOTTY
ENXIO
EOPNOTSUPP
EOVERFLOW
EOWNERDEAD
EPERM
EPFNOSUPPORT
EPIPE
EPROTO
EPROTONOSUPPORT
EPROTOTYPE
ERANGE
EREMOTE
ERESTART
EROFS
__errno
ESHUTDOWN
ESOCKTNOSUPPORT
ESPIPE
ESRCH
ESTALE
ETIME
ETIMEDOUT
ETOOMANYREFS
ETXTBSY
EUSERS
EXDEV
__ftrace
g_fds
g_isrunningundermake
h_errno
__hostos
__isworker
kConsoleHandles
kCrashSigs
kHexToInt
kHttpMethod
kHttpRepeatable
kMbBittab
kNtWsaData
kStartTsc
kTmpPath
kX86GradeNames
kX86MarchNames
kXedChipFeatures
kXedEamode
kXedErrorNames
__log_file
__nocolor
__nosync
optarg
opterr
optind
optopt
optreset
program_executable_name
__replmode
stderr
stdin
stdout
__strace
testlib_enable_tmp_setup_teardown
__threaded
timezone
traceme
tzname
z_errmsg

functions

a64l
abort
abs
accept
accept4
access
acos
acosf
acosh
acoshf
acoshl
acosl
_addrusage
__addvdi3
__addvsi3
__addvti3
adler32
adler32_combine
adler32_z
alarm
aligned_alloc
appendd
appendf
appendHostInfo
appendr
AppendResourceReport
appends
appendw
appendz
arch_prctl
AreMemoryIntervalsOk
__arena_pop
__arena_push
__arg_max
__asan_check
asctime
asctime_r
asin
asinf
asinh
asinhf
asinhl
asinl
asprintf
__assert_fail
atan
atan2l
atanf
atanh
atanhf
atanhl
atanl
atexit
atfork
atof
atoi
atol
atoll
AttachDebugger
balloc
basename
bcopy
bextra
bfree
bind
bing
bingblit
bitreverse16
bitreverse32
bitreverse64
bitreverse8
BLAKE2B256
BLAKE2B256_Final
BLAKE2B256_Init
BLAKE2B256_Process
BLAKE2B256_Update
brk
bsdthread_create
bsearch
bsearch_r
bsf
bsfl
bsfll
bsr
bsr128
bsrl
bsrll
bswap_64
btowc
bzero
c16rtomb
c2rangr
c32rtomb
callexitontermination
calloc
CategorizeIp
__cbrt
cbrt
cbrtf
cbrtl
ceil
ceilf
ceill
cescapec
cfgetispeed
cfgetospeed
cfmakeraw
cfsetispeed
cfsetospeed
chdir
__check_fail
__check_fail_ndebug
_check_sigchld
CheckElfAddress
CheckForMemoryLeaks
chmod
_chomp
_chomp16
chown
chroot
_classifypath
clearenv
clearerr
clearerr_unlocked
__clk_tck
clock
clock_getres
clock_gettime
__clock_gettime_get
clone
close
close_range
close_s
closedir
closefrom
CloseHandle
closelog
CloseSymbolTable
cmpsb
cmpsl
cmpsq
cmpsw
cmpub
cmpul
cmpuq
cmpuw
_cmpxchg
commandv
commandvenv
CompareDnsNames
CompareSlices
CompareSlicesCase
compress
compress2
compressBound
connect
_construct
ConvertTicksToNanos
copy_file_range
copy_with_crc
copyfd
_copyfd
copyfile
copysign
copysignf
copysignl
cos
cosh
coshf
coshl
cosl
cosmo
cosmo2flock
_countbits
countbranch_report
countexpr_report
cprojl
crc32
crc32_combine
crc32_pclmul
crc32_z
crc32c
crc32init
crc_finalize
crc_reset
creat
CreateDirectory
CreateFile
CreateFileMapping
CreateFileMappingNuma
CreateMemoryInterval
CreateNamedPipe
CreatePipe
CreatePipeName
CreateProcess
CreateSymbolicLink
CreateThread
critbit0_allprefixed
critbit0_clear
critbit0_contains
critbit0_delete
critbit0_emplace
critbit0_get
critbit0_insert
crypt
crypt_r
ctermid
cthread_attr_destroy
cthread_attr_getdetachstate
cthread_attr_getguardsize
cthread_attr_getstacksize
cthread_attr_init
cthread_attr_setdetachstate
cthread_attr_setguardsize
cthread_attr_setstacksize
cthread_memory_wait32
cthread_memory_wake32
cthread_self
cthread_sem_destroy
cthread_sem_init
cthread_sem_signal
cthread_sem_wait
cthread_sem_wait_futex
cthread_sem_wait_spin
ctime
ctime_r
__cxa_atexit
__cxa_finalize
__cxa_printexits
_d2ld2
DecodeBase64
DecodeDosArgv
DecodeLatin1
DecodeNf32
_defer
__defer
deflate
deflateBound
deflateCopy
deflateEnd
deflateGetDictionary
deflateInit
deflateInit2
deflateParams
deflatePending
deflatePrime
deflateReset
deflateSetDictionary
deflateSetHeader
deflateTune
DeleteFile
DescribeCapability
DescribeClockName
DescribeDirfd
DescribeFlags
DescribeFrame
DescribeFutexResult
DescribeHow
DescribeIov
DescribeIovNt
DescribeMagnum
DescribeMapFlags
DescribeMapping
DescribeNtConsoleInFlags
DescribeNtConsoleOutFlags
DescribeNtCreationDisposition
DescribeNtFileAccessFlags
DescribeNtFileFlagAttr
DescribeNtFileMapFlags
DescribeNtFileShareFlags
DescribeNtFiletypeFlags
DescribeNtFutexOp
DescribeNtMovFileInpFlags
DescribeNtPageFlags
DescribeNtPipeModeFlags
DescribeNtPipeOpenFlags
DescribeNtProcAccessFlags
DescribeNtSecurityAttributes
DescribeNtStartFlags
DescribeNtSymlinkFlags
DescribeOpenFlags
DescribePersonalityFlags
DescribePollFlags
DescribePrctlOperation
DescribeProt
DescribeProtFlags
DescribeRemapFlags
DescribeRlimit
DescribeRlimitName
DescribeSchedParam
DescribeSchedPolicy
DescribeSeccompOperation
DescribeSigaction
DescribeSigaltstk
DescribeSigset
DescribeSockaddr
DescribeSocketFamily
DescribeSocketProtocol
DescribeSocketType
DescribeSockLevel
DescribeSockOptname
DescribeStat
DescribeTimespec
DescribeTimeval
DeserializeDnsHeader
DestroyHttpMessage
DeviceIoControl
__die
difftime
dirfd
dirname
div
__divmodti4
__divti3
djbsort
djbsort_avx2
dl_iterate_phdr
dlbulk_free
dlcalloc
dlclose
dlerror
dlfree
dlindependent_calloc
dlindependent_comalloc
dlmallinfo
dlmalloc
dlmalloc_abort
dlmalloc_footprint
dlmalloc_footprint_limit
dlmalloc_inspect_all
dlmalloc_max_footprint
dlmalloc_requires_more_vespene_gas
dlmalloc_set_footprint_limit
dlmalloc_stats
dlmalloc_trim
dlmalloc_usable_size
dlmallopt
dlmemalign
dlopen
dlposix_memalign
dlpvalloc
dlrealloc
dlrealloc_in_place
dlsym
dlvalloc
__dos2errno
DosDateTimeToUnix
dprintf
drem
dsleep
dtime
dtoa
DumpHexc
dup
dup2
dup3
eaccess
ecvt
EfiMain
ElevateSeDebugPrivilege
EncodeBase64
EncodeHttpHeaderValue
EncodeLatin1
EncodeNf32
EncodeUrl
encrypt
endgrent
endhostent
endnetent
endprotoent
endpwent
endservent
endswith
endswith16
__ensurefds
__ensurefds_unlocked
epoll_create
epoll_create1
epoll_ctl
epoll_wait
erf
erfc
erfcf
erff
err
__errno_location
errx
_escapedos
EscapeFragment
EscapeHost
EscapeHtml
EscapeIp
EscapeJsStringLiteral
EscapeParam
EscapePass
EscapePath
EscapeSegment
EscapeUrl
EscapeUrlView
EscapeUser
euidaccess
execl
execle
execlp
execv
execve
execvp
execvpe
_exit
exit
_Exit
_Exit1
exp
exp10
exp10f
exp10l
exp2
exp2f
exp2l
expf
expl
explicit_bzero
expm1
expm1f
expm1l
_f2ld2
fabs
fabsf
fabsl
faccessat
fadvise
__fbufsize
fchdir
fchmod
fchmodat
fchown
fchownat
fclose
fclose_s
fcntl
fcvt
fdatasync
fdim
fdimf
fdiml
fdopen
fdopendir
feclearexcept
fegetenv
fegetround
__fentry__
feof
feof_unlocked
feraiseexcept
ferror
ferror_unlocked
fesetenv
fesetround
fetestexcept
fflush
fflush_unlocked
ffs
ffsl
ffsll
fgetc
fgetc_unlocked
fgetln
fgetpos
fgets
fgets_unlocked
fgetwc
fgetwc_unlocked
fgetws
fgetws_unlocked
filecmp
fileexists
fileno
fileno_unlocked
FindClose
FindComBinary
FindContentType
FindDebugBinary
FindEmbeddedApe
FindFirstFile
FindNextFile
finite
finitef
finitel
_firewall
FixPath
__fixupnewfd
__fixupnewsockfd
__flbf
flock
flock2cosmo
flockfile
flogf
floor
floorf
floorl
FlushFileBuffers
_flushlbf
FlushViewOfFile
fma
fmax
fmaxf
fmaxl
fmemopen
fmin
fminf
fminl
fmod
fmodl
__fmt
__fmt_stoa
fnmatch
FoldHeader
fopen
fopenflags
fork
FormatBinary64
FormatFlex64
FormatHex64
FormatHttpDateTime
FormatInt32
FormatInt64
FormatInt64Thousands
FormatMemorySize
FormatOctal32
FormatOctal64
FormatUint32
FormatUint64
FormatUint64Thousands
__fpending
fprintf
fprintf_unlocked
__fpurge
fpurge
fputc
fputc_unlocked
fputs
fputs_unlocked
fputwc
fputwc_unlocked
fputws
fputws_unlocked
fread
fread_unlocked
__freadable
__freading
free
free_s
freeaddrinfo
freedtoa
FreeHostsTxt
freelocale
FreeResolvConf
_freestack
freopen
frexp
frexpf
frexpl
fscanf
fseek
fseeko
fseeko_unlocked
__fsetlocking
fsetpos
fstat
fstatat
fsum
fsumf
fsync
ftell
ftello
ftok
ftrace_init
ftrace_install
ftracer
ftruncate
ftrylockfile
ftw
funlockfile
futimens
futimes
futimesat
__fwritable
fwrite
fwrite_unlocked
__fwriting
g_ddfmt
g_ddfmt_p
g_dfmt
g_dfmt_p
g_ffmt
g_ffmt_p
g_isrunningundermake_init
g_xfmt
g_xfmt_p
gai_strerror
__gc
_gc
_gclongjmp
gcvt
gdbexec
gdtoa
GenerateConsoleCtrlEvent
get_current_dir_name
__get_symbol
__get_symbol_by_addr
__get_virtual
GetAddr2linePath
getaddrinfo
getauxval
_getauxval
getc
getc_unlocked
getcachesize
GetCallerName
getchar
getchar_unlocked
getcontext
GetCpuCount
getcwd
getdelim
getdelim_unlocked
getdomainname
GetDosArgv
GetDosEnviron
getegid
GetElfDynStringTable
GetElfDynSymbolTable
GetElfSectionAddress
GetElfSectionHeaderAddress
GetElfSectionName
GetElfSectionNameStringTable
GetElfSegmentHeaderAddress
GetElfString
GetElfStringTable
GetElfStrs
GetElfSymbolTable
GetElfVirtualAddressRange
getentropy
getenv
geteuid
GetExitCodeProcess
GetFileAttributes
getfiledescriptorsize
GetFileSize
GetGdbPath
getgid
getgrent
getgrgid
getgrgid_r
getgrnam
getgrnam_r
getgrouplist
gethostbyaddr
gethostbyname
gethostent
GetHostIps
gethostname
gethostname_bsd
gethostname_linux
gethostname_nt
GetHostsTxt
GetHttpHeader
GetHttpHeaderName
GetHttpMethod
GetHttpReason
GetInstructionLengths
GetInterpreterExecutableName
GetIpCategoryName
getitimer
getline
getloadavg
GetMagnumStr
GetMaxFd
GetMemtrackSize
getnameinfo
getnetbyaddr
getnetbyname
getnetent
GetNtBaseSocket
GetNtNameServers
GetNtOpenFlags
GetNtProtocolsTxtPath
GetNtServicesTxtPath
__getntsyspath
getopt
getpeername
getpgid
getpgrp
getpid
getppid
getpriority
GetProcAddressModule
GetProgramExecutableName
getprotobyname
getprotobynumber
getprotoent
getpwent
getpwnam
getpwnam_r
getpwuid
getpwuid_r
getrandom
getresgid
GetResolvConf
GetResourceLimit
getresuid
getrlimit
getrusage
gets
getservbyname
getservbyport
getservent
GetSiCodeName
getsid
getsockname
getsockopt
GetSymbolTable
GetTempPathA_flunk
gettid
gettimeofday
__gettimeofday_get
getttycols
getttysize
getuid
getutf16
getwc
getwc_unlocked
getwchar
getwchar_unlocked
getx86processormodel
GetZipCdirComment
GetZipCdirCommentSize
GetZipCdirOffset
GetZipCdirRecords
GetZipCdirSize
GetZipCfileCompressedSize
GetZipCfileMode
GetZipCfileOffset
GetZipCfileTimestamps
GetZipCfileUncompressedSize
GetZipLfileCompressedSize
GetZipLfileUncompressedSize
glob
globfree
gmtime
gmtime_r
GoodSocket
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
HasControlCodes
HeaderHas
herror
hextoint
HighwayHash64
hilbert
__hook
hstrerror
hypot
hypotf
hypotl
i128abs
iconv
iconv_close
iconv_open
identity
ilogb
ilogbf
ilogbl
imapxlatab
imaxabs
IndentLines
index
IndexDoubleNulString
inet_addr
inet_aton
inet_ntoa
inet_ntop
inet_pton
inflate
__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
InitHttpMessage
InitializeFileDescriptors
initstate
insertionsort
int128toarray_radix10
int64toarray
interruptiblecall
ioctl
ioctl_default
ioctl_fioclex
ioctl_siocgifaddr
ioctl_siocgifaddr_nt
ioctl_siocgifbrdaddr
ioctl_siocgifbrdaddr_nt
ioctl_siocgifconf
ioctl_siocgifconf_nt
ioctl_siocgifdstaddr
ioctl_siocgifflags
ioctl_siocgifflags_nt
ioctl_siocgifnetmask
ioctl_siocgifnetmask_nt
ioctl_tcgets
ioctl_tcgets_nt
ioctl_tcsets
ioctl_tcsets_nt
ioctl_tiocgwinsz
ioctl_tiocgwinsz_nt
ioctl_tiocswinsz
ioctl_tiocswinsz_nt
__iovec2nt
_isabspath
IsAcceptableHost
IsAcceptablePath
IsAcceptablePort
IsAfrinicIp
isalnum
isalpha
IsAnonymousIp
IsApnicIp
IsArinIp
isascii
IsAtLeastWindows10
isatty
isblank
ischardev
iscntrl
IsDebuggerPresent
isdigit
isdigit_l
isdirectory
isdirectory_nt
_isdirsep
IsDodIp
IsElf64Binary
IsElfSymbolContent
isexecutable
isgraph
_isheap
IsLacnicIp
IsLoopbackIp
islower
islower_l
IsMemtracked
IsMimeType
IsMulticastIp
iso8601
isprint
IsPrivateIp
IsPublicIp
ispunct
IsReasonablePath
isregularfile
isregularfile_nt
IsRipeIp
IsRunningUnderMake
issetugid
isspace
issymlink
issymlink_nt
IsTestnetIp
_istext
isupper
isupper_l
IsValidCookieValue
IsValidHttpToken
iswalnum
iswalpha
iswalpha_l
iswblank
iswblank_l
iswcntrl
iswcntrl_l
iswctype
iswdigit
iswdigit_l
iswgraph
iswlower
iswlower_l
iswprint
iswprint_l
iswpunct
iswpunct_l
iswseparator
iswspace
iswspace_l
iswupper
iswupper_l
iswxdigit
iswxdigit_l
isxdigit
isxdigit_l
IsZipCdir32
IsZipCdir64
itoa
_jmpstack
_join
_joinpaths
kappendf
kCp437
kCpuids
kDos2Errno
kHttpToken
kill
killpg
kisdangerous
kNtSystemDirectory
kNtWindowsDirectory
kprintf
ksnprintf
kToLower
kToUpper
kvappendf
kvprintf
kvsnprintf
l64a
labs
landlock_add_rule
landlock_create_ruleset
landlock_restrict_self
lchown
ldexp
ldexpf
ldexpl
ldiv
LengthInt64
LengthInt64Thousands
LengthUint64
LengthUint64Thousands
lgamma
lgamma_r
lgammaf
lgammaf_r
link
linkat
listen
llabs
lldiv
llround
llroundf
_loadxmm
localeconv
localtime
localtime_lock
localtime_r
localtime_unlock
_lockcmpxchg
_lockxadd
lockxchg
log
log10
log10f
log10l
log1p
log1pf
log1pl
log2
log2f
log2l
logb
logbf
logbl
logf
logl
longerjmp
longjmp
_longjmp
longsort
LookupProtoByName
LookupProtoByNumber
LookupServicesByName
LookupServicesByPort
lround
lroundf
lseek
lstat
lutimes
lz4check
lz4cpy
lz4decode
madvise
major
makedev
makedirs
mallinfo
malloc
malloc_inspect_all
malloc_stats
malloc_trim
malloc_usable_size
__map_phdrs
_mapanon
_mapshared
_mapstack
MapViewOfFileEx
MapViewOfFileExNuma
MarsagliaXorshift32
MarsagliaXorshift64
mblen
mbrlen
mbrtoc16
mbrtoc32
mbrtowc
mbsinit
mbsnrtowcs
mbsrtowcs
mbstowcs
mbtowc
MeasureEntropy
memalign
memcasecmp
memccpy
memchr16
memfrob
meminfo
memjmpinit
memmove
mempcpy
memset16
memsummary
MetalPrintf
mincore
minor
mkdir
mkdirat
mkdtemp
mkfifo
mknod
mkntcmdline
mkntenvblock
__mkntpath2
mkostemp
mkostemps
mkostempsm
mkostempsmi
mkstemp
mkstemps
mktemp
mktime
_mktls
mmap
modf
modff
__morph_begin
__morph_end
morton
mount
MoveFileEx
mprotect
mpsadbw
__mpsadbws
mremap
msync
_mt19937
Mul4x4Adx
Mul6x6Adx
Mul8x8Adx
__mulvdi3
__mulvsi3
__mulvti3
munmap
nan
nanf
nanl
_nanos
nanosleep
__negvdi2
__negvsi2
__negvti2
__new_page
newaddrinfo
newlocale
nextafter
nextafterf
nextafterl
nexttoward
nexttowardf
nexttowardl
nftw
nice
nl_langinfo
nl_langinfo_l
nowl_setup
__nt2sysv
ntaccesscheck
NtGetVersion
ntreturn
ntsetprivilege
ntspawn
__on_arithmetic_overflow
__oncrash
__onfork
open
openat
opendir
OpenExecutable
openlog
OpenProcess
openpty
OpenSymbolTable
pabsb
pabsd
pabsw
packssdw
packsswb
packusdw
packuswb
paddb
paddd
paddq
paddsb
paddsw
paddusb
paddusw
paddw
__paginate
palignr
__palignrs
pand
pandn
ParseContentLength
ParseForwarded
ParseHost
ParseHostsTxt
ParseHttpDateTime
ParseHttpMessage
ParseHttpRange
ParseIp
ParseParams
parseport
ParseRequestUri
ParseResolvConf
ParseUrl
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
poll
popcnt
popen
por
posix_fadvise
posix_madvise
posix_memalign
posix_openpt
posix_spawn
posix_spawn_file_actions_addclose
posix_spawn_file_actions_adddup2
posix_spawn_file_actions_addopen
posix_spawn_file_actions_destroy
posix_spawn_file_actions_init
posix_spawnattr_destroy
posix_spawnattr_getflags
posix_spawnattr_getpgroup
posix_spawnattr_getschedparam
posix_spawnattr_getschedpolicy
posix_spawnattr_getsigdefault
posix_spawnattr_getsigmask
posix_spawnattr_init
posix_spawnattr_setflags
posix_spawnattr_setpgroup
posix_spawnattr_setschedparam
posix_spawnattr_setschedpolicy
posix_spawnattr_setsigdefault
posix_spawnattr_setsigmask
posix_spawnp
pow
pow10
pow10f
pow10l
powf
powi
powif
powil
prctl
pread
preadv
__print_maps
__printargs
PrintBacktraceUsingSymbols
printf
PrintGarbage
PrintGarbageNumeric
PrintMemoryIntervals
PrintSystemMappings
program_invocation_name
program_invocation_short_name
psadbw
pselect
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_getspecific
pthread_key_create
pthread_key_delete
pthread_mutex_destroy
pthread_mutex_init
pthread_mutex_lock
pthread_mutex_trylock
pthread_mutex_unlock
pthread_mutexattr_destroy
pthread_mutexattr_gettype
pthread_mutexattr_init
pthread_mutexattr_settype
pthread_once
pthread_setspecific
ptrace
ptsname
ptsname_r
puff
punpckhbw
punpckhdq
punpckhqdq
punpckhwd
punpcklbw
punpckldq
punpcklqdq
punpcklwd
putc
putc_unlocked
putchar
putchar_unlocked
putenv
PutEnvImpl
puts
pututf16
putwc
putwc_unlocked
putwchar
putwchar_unlocked
pvalloc
pwrite
pwritev
pxor
qsort
qsort_r
quick_exit
raise
rand
rand64
random
rawmemchr16
rawwmemchr
rdrand
rdrand_init
rdseed
read
readansi
readdir
readlink
readlinkat
readv
_real1
_real2
_real3
realloc
realloc_in_place
reallocarray
realpath
reboot
recv
recvfrom
recvmsg
RefreshTime
regcomp
regerror
regexec
regfree
ReleaseMemoryIntervals
ReleaseMemoryNt
remainder
remove
RemoveDirectory
remquo
remquof
remquol
rename
renameat
ReOpenFile
replacestr
replaceuser
__reservefd
__reservefd_unlocked
ResolveDns
ResolveDnsReverse
ResolveHostsReverse
ResolveHostsTxt
RestoreDefaultCrashSignalHandlers
__restorewintty
rewind
rewinddir
rindex
rint
rintl
rldecode
rldecode2
rmdir
rmrf
rngset
round
rounddown2pow
roundf
roundl
roundup2log
roundup2pow
rt_add
rt_end
rt_init
__sample_pids
_savexmm
sbrk
scalb
scalbf
scalbl
scalbln
scalblnf
scalblnl
scalbn
scalbnf
scalbnl
scanf
sched_get_priority_max
sched_get_priority_min
sched_getaffinity
sched_getparam
sched_getscheduler
sched_rr_get_interval
sched_setaffinity
sched_setparam
sched_setscheduler
sched_yield
seccomp
seekdir
select
send
sendfile
sendmsg
sendto
SerializeDnsHeader
SerializeDnsQuestion
setbuf
setbuffer
setcontext
SetCurrentDirectory
setegid
setenv
seteuid
setfsgid
setfsuid
setgid
setgrent
sethostent
setitimer
setjmp
_setjmp
setkey
setlinebuf
setlocale
setlogmask
setlongerjmp
setnetent
setpgid
setpgrp
setpriority
setprotoent
setpwent
setregid
setresgid
setresuid
setreuid
setrlimit
setservent
setsid
setsockopt
_setstack
setstate
setuid
SetUp
setvbuf
sha1_transform_avx2
sha1_transform_ni
sha256_transform_ni
ShowBacktrace
ShowCrashReport
ShowCrashReports
shufpd
shufps
shutdown
__sig_add
__sig_check
__sig_handle
__sig_mask
__sig_raise
sigaction
sigaddset
sigaltstack
sigdelset
sigemptyset
sigfillset
sigignore
siginterrupt
sigismember
signal
sigprocmask
sigqueue
sigsuspend
sin
sincos
sincosf
sincosl
sinh
sinhf
sinhl
sinl
sizetol
sleb128
sleb64
sleep
_smt19937
_Smt19937
snprintf
sockaddr2bsd
sockaddr2linux
socket
socketpair
_spawn
splice
sprintf
sqrt
sqrtf
sqrtl
srand
srandom
sscanf
__start_fatal
startswith
startswith16
startswithi
stat
stpcpy
stpncpy
__strace_init
strcasecmp
strcasecmp16
strcasecmp16to8
strcasecmp8to16
strcat
strcat16
strchr16
strchrnul16
strclen
strclen16
strcmp
strcmp16
strcmp16to8
strcmp8to16
strcoll
strcoll_l
strcpy
strcpy16
strcspn
strcspn16
strdup
strerdoc
strerrno
strerror
strerror_r
strerror_wr
strfry
strftime
strftime_l
stripext
stripexts
strlcat
strlcpy
strlen
strlen16
strncasecmp
strncasecmp16
strncasecmp16to8
strncasecmp8to16
strncat
strncat16
strnclen
strnclen16
strncmp
strncmp16
strncmp16to8
strncmp8to16
strncpy
strndup
strnlen
strnlen16
strnlen16_s
strnlen_s
strntolower
strntoupper
strnwidth
strnwidth16
strpbrk
strpbrk16
strptime
strrchr
strrchr16
strsak16
strsep
strsignal
strspn
strspn16
strstr16
strtod
strtod_l
strtodg
strtodI
strtof
strtof_l
strtoi128
strtoId
strtoIdd
strtoIf
strtoimax
strtoIx
strtok
strtok_r
strtol
strtold
strtold_l
strtoll
strtoll_l
strtolower
strtonum
strtopd
strtopdd
strtopf
strtopx
strtord
strtordd
strtorf
strtorx
strtou128
strtoul
strtoull
strtoull_l
strtoumax
strtoupper
strverscmp
strwidth
strwidth16
strxfrm
strxfrm_l
__subvdi3
__subvsi3
__subvti3
svigna
swprintf
symlink
symlinkat
sync
sync_file_range
sys_accept
sys_accept4
sys_accept_nt
sys_bind
sys_bind_nt
sys_chdir_nt
sys_clock_gettime_mono
sys_clock_gettime_nt
sys_clock_gettime_xnu
sys_clone_linux
sys_close_epoll_nt
sys_close_nt
sys_closesocket_nt
sys_connect
sys_connect_nt
sys_dup3
sys_dup_nt
sys_execve
sys_execve_nt
sys_faccessat_nt
sys_fadvise_nt
sys_fchdir_nt
sys_fchmodat_nt
sys_fcntl
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_getloadavg_nt
sys_getpeername
sys_getpeername_nt
sys_getppid_nt
sys_getpriority_nt
sys_getrusage
sys_getrusage_nt
sys_getsetpriority_nt
sys_getsockname
sys_getsockname_nt
sys_getsockopt_nt
sys_gettid
sys_gettimeofday_metal
sys_gettimeofday_nt
sys_gettimeofday_xnu
sys_isatty_metal
sys_isatty_nt
sys_kill_nt
sys_linkat_nt
sys_listen_nt
sys_lseek_nt
sys_madvise_nt
sys_mkdirat_nt
sys_mmap
sys_mmap_metal
sys_mmap_nt
sys_mprotect_nt
sys_msync_nt
sys_munmap
sys_munmap_metal
sys_nanosleep_nt
sys_nanosleep_xnu
sys_open_nt
sys_openat
sys_openat_metal
sys_pause_nt
sys_pipe
sys_pipe2
sys_pipe_nt
sys_poll_metal
sys_poll_nt
sys_read_nt
sys_readlinkat_nt
sys_readv_metal
sys_readv_nt
sys_readv_serial
sys_recv_nt
sys_recvfrom_nt
sys_renameat_nt
sys_sched_getscheduler_netbsd
sys_send_nt
sys_sendto_nt
sys_setitimer_nt
sys_setpriority_nt
sys_setsockopt_nt
sys_shutdown_nt
sys_sigprocmask
sys_socket
sys_socket_nt
sys_socketpair
sys_socketpair_nt
sys_symlinkat_nt
sys_sync_nt
sys_sysinfo_nt
sys_truncate_nt
sys_unlinkat_nt
sys_unveil_linux
sys_utimensat
sys_utimensat_nt
sys_utimensat_xnu
sys_utimes_nt
sys_wait4
sys_wait4_nt
sys_write_nt
sys_writev_metal
sys_writev_nt
sys_writev_serial
sys_xinet_ntop
syscall
__syscall__
syscon_start
sysconf
sysinfo
syslog
system
systemexec
__systemfive
tan
tanf
tanh
tanhf
tanhl
tanl
tarjan
tcdrain
tcflow
tcflush
tcgetattr
tcgetpgrp
tcgetsid
tcsendbreak
tcsetattr
tcsetpgrp
TearDown
telldir
tempnam
TerminateProcess
__text_windows_start
__tfork_thread
tgamma
tgammaf
tgkill
time
times
_timespec2timeval
_timespec_add
_timespec_eq
_timespec_frommicros
_timespec_frommillis
_timespec_gt
_timespec_gte
_timespec_sub
_timespec_tomicros
_timespec_tomillis
TimeSpecToWindowsTime
_timeval_add
TimeValToWindowsTime
timingsafe_memcmp
tinydivsi
tinywcslen
tinywcsnlen
tkill
tmpfile
tolower
tolower_l
touch
toupper
toupper_l
towctrans
towlower
towlower_l
towupper
towupper_l
tpdecode
tpenc
tpencode
tprecode16to8
tprecode8to16
TrackMemoryInterval
trunc
truncate
truncf
truncl
ttyname
ttyname_r
tzset
__udivmodti4
uint128toarray_radix10
uint64toarray
uint64toarray_fixed16
uint64toarray_radix16
uint64toarray_radix8
uleb128
uleb64
umask
uname
unbing
unbingbuf
unbingstr
Unchunk
uncompress
uncompress2
undeflate
Underlong
ungetc
ungetc_unlocked
ungetwc
ungetwc_unlocked
ungray
unhexbuf
unhexstr
unhilbert
unlink
unlink_s
unlinkat
unlockpt
UnmapViewOfFile
unmorton
unmount
unsetenv
unsleb128
UntrackMemoryIntervals
unuleb64
unveil
unzleb64
uselocale
usleep
utf16to32
utf16toutf8
utf8toutf32
utime
utimensat
utimes
valloc
vappendf
vasprintf
vcscanf
vdprintf
__vdsosym
verr
verrx
vflogf
vfork
vfprintf
vfprintf_unlocked
vfscanf
vigna
vigna_r
VirtualProtect
VisualizeControlCodes
vmsplice
vprintf
vscanf
vsnprintf
vsprintf
vsscanf
vsyslog
vwarn
vwarnx
wait
_wait0
wait3
wait4
WaitForMultipleObjects
WaitForSingleObject
waitpid
warn
warnx
_wchomp
wcrtomb
wcscasecmp
wcscat
wcschr
wcschrnul
wcscmp
wcscoll_l
wcscpy
wcscspn
wcsdup
wcsendswith
wcslen
wcsncasecmp
wcsncat
wcsncmp
wcsncpy
wcsnlen
wcsnlen_s
wcsnrtombs
wcsnwidth
wcspbrk
wcsrchr
wcsrtombs
wcssak
wcsspn
wcsstartswith
wcsstr
wcstod
wcstof
wcstoi128
wcstoimax
wcstok
wcstol
wcstold
wcstold_l
wcstoll
wcstoll_l
wcstombs
wcstou128
wcstoul
wcstoull
wcstoull_l
wcstoumax
wcswidth
wcsxfrm
wcsxfrm_l
wctob
wctomb
wctrans
wctype
wcwidth
_weakfree
WindowsDurationToTimeSpec
WindowsDurationToTimeVal
WindowsTimeToTimeSpec
WindowsTimeToTimeVal
__winerr
WinMain
WinMainForked
__winsockerr
WinSockInit
WinThreadLaunch
wmemchr
wmemcmp
wmemcpy
wmemmove
wmempcpy
write
writev
WritevUninterruptible
WSARecv
WSARecvFrom
WSAStartup
WSAWaitForMultipleEvents
xasprintf
xbarf
xcalloc
xdie
xdirname
xdtoa
xdtoaf
xdtoal
xed_decoded_inst_zero_set_mode
xed_get_chip_features
xed_instruction_length_decode
xed_isa_set_is_valid_for_chip
xed_prefix_table_bit
xed_test_chip_features
xfixpath
xgetline
xhomedir
xiso8601ts
xiso8601tv
xjoinpaths
xload
xloadzd
xmalloc
xmemalign
xmemalignzero
xreadlink
xreadlinkat
xrealloc
xsigaction
xslurp
xspawn
xstrcat
xstrdup
xstripext
xstripexts
xstrmul
xstrndup
xunbing
xunbinga
xvalloc
xvasprintf
xvspawn
xwrite
zcalloc
zcfree
zError
__zipos_close
__zipos_free
__zipos_fstat
__zipos_get
__zipos_lseek
__zipos_open
__zipos_parseuri
__zipos_read
__zipos_stat
zleb128
zleb64
zlibCompileFlags
zlibVersion

a64l

Converts base64 to 32-bit integer, the posix way.

@param
const char* s
@return
long
@see l64a() for inverse
@see DecodeBase64()

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
@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
@restartable (unless SO_RCVTIMEO)

accept4

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 out_addr's byte length
int flags
can have SOCK_{CLOEXEC,NONBLOCK}, which may apply to both the newly created socket and the server one
@return
int
client fd which needs close(), or -1 w/ errno
@asyncsignalsafe
@restartable (unless SO_RCVTIMEO)

access

Checks if effective user can access path in particular ways.

@param
const 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
double x
@return
double
value in range [0,M_PI]
NAN if 𝑥 ∈ {NAN,+INFINITY,-INFINITY}
NAN if 𝑥 ∉ [-1,1]

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
@define acosh(x) = log(x + sqrt(x*x-1))

acoshf

Returns inverse hyperbolic cosine of 𝑥.

@param
float x
@return
float
@define acosh(x) = log(x + sqrt(x*x-1))

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(fabs(sqrt((1-𝑥)*(1+𝑥))),𝑥)
@domain -1 ≤ 𝑥 ≤ 1

_addrusage

Accumulates resource statistics in y to x.

@param
struct rusage* x
struct rusage* y
@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

aligned_alloc

Same as memalign(a, n) but requires IS2POW(a).

@param
unsigned long a
unsigned long n
number of bytes needed
@return
void*
memory address, or NULL w/ errno
@throw EINVAL if !IS2POW(a)
@see pvalloc()
@threadsafe

appendd

Appends data to buffer, e.g.

char *b = 0;
appendd(&b, "hello", 5);
free(b);
The resulting buffer is guaranteed to be NUL-terminated, i.e. !b[appendz(b).i] will be the case.
@param
char** b
void* s
may contain nul characters and may be null if l is zero
unsigned long l
is byte length of s
@return
long
bytes appended (always l) or -1 if ENOMEM
@see appendz(b).i to get buffer length
@note 20% faster than appends()

appendf

Appends formatted string to buffer, e.g.

char *b = 0;
appendf(&b, "hello %d\n", 123);
free(b);
@param
char** b
const char* fmt
...
@return
long
bytes appended or -1 if ENOMEM
@see appendz(b).i to get buffer length
@note O(1) amortized buffer growth

appendHostInfo

@param
struct HostAdapterInfoNode* parentInfoNode
const char* baseName
struct NtIpAdapterAddresses* aa
struct NtIpAdapterUnicastAddress** ptrUA
struct NtIpAdapterPrefix** ptrAP
int count
@return
struct HostAdapterInfoNode*

appendr

Resets length of append buffer, e.g.

char *b = 0;
appends(&b, "hello");
appendr(&b, 1);
assert(!strcmp(b, "h"));
appendr(&b, 0);
assert(!strcmp(b, ""));
free(b);
If i is greater than the current length then the extra bytes are filled with NUL characters. If i is less than the current length then memory is released to the system.

The resulting buffer is guaranteed to be NUL-terminated, i.e. !b[appendz(b).i] will be the case even if both params are 0.

@param
char** b
unsigned long i
@return
long
i or -1 if ENOMEM
@see appendz(b).i to get buffer length

AppendResourceReport

Generates process resource usage report.

@param
char** b
struct rusage* ru
const char* nl
@return
void

appends

Appends string to buffer, e.g.

char *b = 0;
appends(&b, "hello");
free(b);
The resulting buffer is guaranteed to be NUL-terminated, i.e. !b[appendz(b).i] will be the case.
@param
char** b
const char* s
@return
long
bytes appended (always strlen(s)) or -1 if ENOMEM
@see appendz(b).i to get buffer length
@note 2x faster than appendf()

appendw

Appends character or word-encoded string to buffer.

Up to eight characters can be appended. For example:

appendw(&s, 'h'|'i'<<8);
appendw(&s, READ64LE("hi\0\0\0\0\0"));
Are equivalent to:

appends(&s, "hi");
The special case:

appendw(&s, 0);
Will append a single NUL character.

This function is slightly faster than appendd() and appends(). Its main advantage is it improves code size in functions that call it.

The resulting buffer is guaranteed to be NUL-terminated, i.e. !b[appendz(b).i] will be the case.

@param
char** b
unsigned long w
@return
long
bytes appended or -1 if ENOMEM
@see appendz(b).i to get buffer length

appendz

Returns size of append buffer.

@param
char* p
must be 0 or have been allocated by an append*() function
@return
struct z
i is number of bytes stored in buffer
n is number of bytes in allocation

arch_prctl

Don't bother.

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

AreMemoryIntervalsOk

@param
struct _mmi* mm
@return
_Bool

__arena_pop

Pops memory arena.

This pops the most recently created arena, freeing all the memory that was allocated between the push and pop arena calls. If this is the last arena on the stack, then the old malloc hooks are restored.

@return
void
@see __arena_push()

__arena_push

Pushes memory arena.

This allocator gives a ~3x performance boost over dlmalloc, mostly because it isn't thread safe and it doesn't do defragmentation.

Calling this function will push a new arena. It may be called multiple times from the main thread recursively. The first time it's called, it hooks all the regular memory allocation functions. Any allocations that were made previously outside the arena, will be passed on to the previous hooks. Then, the basic idea, is rather than bothering with free() you can just call __arena_pop() to bulk free.

Arena allocations also have a slight size advantage, since 32-bit pointers are always used. The maximum amount of arena memory is 805,175,296 bytes.

@return
void
@see __arena_pop()

__arg_max

Returns ARG_MAX for host platform.

@return
int

__asan_check

Checks validity of memory range.

Normally this is abstracted by the compiler.

@param
void* p
is starting virtual address
long n
is number of bytes to check
@return
struct f
kind is 0 on success or <0 on invalid
shadow points to first poisoned shadow byte
@note this takes 6 picoseconds per byte

asctime

@param
struct tm* timeptr
@return
char*

asctime_r

@param
struct tm* timeptr
char* buf
@return
char*

asin

Returns arc sine of 𝑥.

@param
double x
@return
double
value in range [-M_PI/2,M_PI/2]
NAN if 𝑥 ∈ {NAN,+INFINITY,-INFINITY}
NAN if 𝑥 ∉ [-1,1]

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
@define asinh(x) = sign(x)*log(|x|+sqrt(x*x+1)) ~= x - x^3/6 + o(x^5)

asinhf

Returns inverse hyperbolic sine of 𝑥.

@param
float x
@return
float
@define asinh(x) = sign(x)*log(|x|+sqrt(x*x+1)) ~= x - x^3/6 + o(x^5)

asinhl

Returns inverse hyperbolic sine of 𝑥.

@param
long double x
@return
long double
@define asinh(x) = sign(x)*log(|x|+sqrt(x*x+1)) ~= x - x^3/6 + o(x^5)

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

asprintf

Formats string, allocating needed memory.

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

__assert_disable

Disables assert() failures at runtime.

@type
_Bool

__assert_fail

Handles failure of assert() macro.

@param
const char* expr
const char* file
int line
@return
void

atan

Returns arc tangent of 𝑥.

@param
𝑥
is double scalar in low half of %xmm0
@return
double scalar in low half 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
@define x ? log1p(2 * x / (1 - x)) / 2 : x

atanhf

Returns inverse hyperbolic tangent of 𝑥.

@param
float x
@return
float
@define x ? log1p(2 * x / (1 - x)) / 2 : x

atanhl

Returns inverse hyperbolic tangent of 𝑥.

@param
long double x
@return
long double
@define x ? log1p(2 * x / (1 - x)) / 2 : x

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
const char* s
@return
double

atoi

Decodes decimal integer from ASCII string.

atoi 10⁸              22𝑐         7𝑛𝑠
strtol 10⁸            37𝑐        12𝑛𝑠
strtoul 10⁸           35𝑐        11𝑛𝑠
wcstol 10⁸            30𝑐        10𝑛𝑠
wcstoul 10⁸           30𝑐        10𝑛𝑠
strtoimax 10⁸         80𝑐        26𝑛𝑠
strtoumax 10⁸         78𝑐        25𝑛𝑠
wcstoimax 10⁸         77𝑐        25𝑛𝑠
wcstoumax 10⁸         76𝑐        25𝑛𝑠
@param
const char* s
is a non-null nul-terminated string
@return
int
the decoded signed saturated integer

atol

Decodes decimal integer from ASCII string.

@param
const char* s
is a non-null nul-terminated string
@return
long
the decoded signed saturated integer

atoll

Decodes decimal number from ASCII string.

@param
const char* s
is a non-null nul-terminated string
@return
long
the decoded signed saturated integer

AttachDebugger

Launches GDB debugger GUI for current process.

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

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

@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, e.g.

path     │ dirname() │ basename()
─────────────────────────────────
0        │ .         │ .
.        │ .         │ .
..       │ .         │ ..
/        │ /         │ /
usr      │ .         │ usr
/usr/    │ /         │ usr
/usr/lib │ /usr      │ lib
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 and may be mutated, but not expanded in length
@return
char*
pointer to path, or inside path, or to a special r/o string
@see dirname()
@see SUSv2

bcopy

Moves memory the BSD way.

Please use memmove() instead. Note the order of arguments.

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

bextra

Extracts bit field from array.

@param
const unsigned int* p
unsigned long i
char b
@return
unsigned int

bfree

Frees memory return by balloc().

@param
struct GuardedBuffer* b
@return
void
@deprecated

bind

Assigns local address and port number to socket, e.g.

struct sockaddr_in in = {AF_INET, htons(12345), {htonl(0x7f000001)}};
int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bind(fd, &in, sizeof(in));
@param
int fd
is the file descriptor returned by socket()
void* addr
is usually the binary-encoded ip:port on which to listen
unsigned int addrsize
is the byte-length of addr's true polymorphic form
@return
int
0 on success or -1 w/ errno
@error ENETDOWN, EPFNOSUPPORT, etc.
@asyncsignalsafe

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
int x
@return
int

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
int x
@return
int

BLAKE2B256

Computes blake2b 256bit message digest.

blake2b256 n=0                     191 nanoseconds
blake2b256 n=8                      23 ns/byte         40,719 kb/s
blake2b256 n=31                      6 ns/byte            153 mb/s
blake2b256 n=32                      6 ns/byte            158 mb/s
blake2b256 n=63                      3 ns/byte            312 mb/s
blake2b256 n=64                      3 ns/byte            317 mb/s
blake2b256 n=128                     1 ns/byte            640 mb/s
blake2b256 n=256                     1 ns/byte            662 mb/s
blake2b256 n=22851                   1 ns/byte            683 mb/s
@param
void* data
unsigned long len
unsigned char* out
@return
int

BLAKE2B256_Final

@param
struct ctx* b2b
unsigned char* out
@return
int

BLAKE2B256_Init

@param
struct ctx* b2b
@return
int

BLAKE2B256_Process

@param
struct ctx* b2b
const unsigned long* data
@return
int

BLAKE2B256_Update

@param
struct ctx* b2b
void* in_data
unsigned long len
@return
int

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

bsdthread_create

XNU thread system calls.

@return
int
@see darwin-libpthread/kern/kern_support.c

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

bsr128

Returns binary logarithm of integer 𝑥.

  uint32 𝑥   bsf(𝑥) tzcnt(𝑥)   ffs(𝑥)   bsr(𝑥) lzcnt(𝑥)
0x00000000      wut       32        0      wut       32
0x00000001        0        0        1        0       31
0x80000001        0        0        1       31        0
0x80000000       31       31       32       31        0
0x00000010        4        4        5        4       27
0x08000010        4        4        5       27        4
0x08000000       27       27       28       27        4
0xffffffff        0        0        1       31        0
@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

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

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

btowc

@param
int c
@return
unsigned int

bzero

Sets memory to zero.

bzero n=0                          661 picoseconds
bzero n=1                          661 ps/byte          1,476 mb/s
bzero n=2                          330 ps/byte          2,952 mb/s
bzero n=3                          220 ps/byte          4,428 mb/s
bzero n=4                          165 ps/byte          5,904 mb/s
bzero n=7                           94 ps/byte         10,333 mb/s
bzero n=8                           41 ps/byte         23,618 mb/s
bzero n=15                          44 ps/byte         22,142 mb/s
bzero n=16                          20 ps/byte         47,236 mb/s
bzero n=31                          21 ps/byte         45,760 mb/s
bzero n=32                          20 ps/byte         47,236 mb/s
bzero n=63                          10 ps/byte         92,997 mb/s
bzero n=64                          15 ps/byte         62,982 mb/s
bzero n=127                         15 ps/byte         62,490 mb/s
bzero n=128                         10 ps/byte         94,473 mb/s
bzero n=255                         14 ps/byte         68,439 mb/s
bzero n=256                          9 ps/byte            105 gb/s
bzero n=511                         15 ps/byte         62,859 mb/s
bzero n=512                         11 ps/byte         83,976 mb/s
bzero n=1023                        15 ps/byte         61,636 mb/s
bzero n=1024                        10 ps/byte         88,916 mb/s
bzero n=2047                         9 ps/byte            105 gb/s
bzero n=2048                         8 ps/byte            109 gb/s
bzero n=4095                         8 ps/byte            115 gb/s
bzero n=4096                         8 ps/byte            118 gb/s
bzero n=8191                         7 ps/byte            129 gb/s
bzero n=8192                         7 ps/byte            130 gb/s
bzero n=16383                        6 ps/byte            136 gb/s
bzero n=16384                        6 ps/byte            137 gb/s
bzero n=32767                        6 ps/byte            140 gb/s
bzero n=32768                        6 ps/byte            141 gb/s
bzero n=65535                       15 ps/byte         64,257 mb/s
bzero n=65536                       15 ps/byte         64,279 mb/s
bzero n=131071                      15 ps/byte         63,166 mb/s
bzero n=131072                      15 ps/byte         63,115 mb/s
bzero n=262143                      15 ps/byte         62,052 mb/s
bzero n=262144                      15 ps/byte         62,097 mb/s
bzero n=524287                      15 ps/byte         61,699 mb/s
bzero n=524288                      15 ps/byte         61,674 mb/s
bzero n=1048575                     16 ps/byte         60,179 mb/s
bzero n=1048576                     15 ps/byte         61,330 mb/s
bzero n=2097151                     15 ps/byte         61,071 mb/s
bzero n=2097152                     15 ps/byte         61,065 mb/s
bzero n=4194303                     16 ps/byte         60,942 mb/s
bzero n=4194304                     16 ps/byte         60,947 mb/s
bzero n=8388607                     16 ps/byte         60,872 mb/s
bzero n=8388608                     16 ps/byte         60,879 mb/s
@param
void* p
is memory address
unsigned long n
is byte length
@return
void
p
@asyncsignalsafe

c16rtomb

@param
char* s
unsigned short c16
unsigned int* ps
@return
unsigned long

c2rangr

Computes transcedental trigonometry op w/ reactive scaling.

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

c32rtomb

@param
char* s
unsigned int c
unsigned int* t
@return
unsigned long

callexitontermination

Installs default handlers for friendly kill signals.

@param
struct sa_mask* 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()
@threadsafe

CategorizeIp

Classifies IP address.

@param
unsigned int x
@return
int
integer e.g. kIpLoopback, kIpPrivate, etc.
@see GetIpCategoryName()

__cbrt

Returns cube root of 𝑥.

@param
double x
@return
double

cbrt

Returns cube root of 𝑥.

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

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

cfgetispeed

@param
struct termios* t
@return
unsigned int

cfgetospeed

@param
struct termios* t
@return
unsigned int

cfmakeraw

@param
struct termios* t
@return
void

cfsetispeed

@param
struct termios* t
int speed
@return
int

cfsetospeed

@param
struct termios* t
int speed
@return
int

chdir

Sets current directory.

This does *not* update the PWD environment variable.

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

__check_fail

Handles failure of CHECK_xx() macros.

@param
const char* suffix
const char* opstr
unsigned long want
const char* wantstr
unsigned long got
const char* gotstr
const char* file
int line
const char* fmt
...
@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
const char* file
int line
const char* opchar
const char* fmt
...
@noreturn
@see libc/log/thunks/__check_fail_ndebug.S

_check_sigchld

Checks to see if SIGCHLD should be raised on Windows.

@return
void
true if a signal was raised
@note yoinked by fork-nt.c

CheckElfAddress

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

CheckForMemoryLeaks

Tests for memory leaks.

This function needs to call __cxa_finalize(). Therefore any runtime services that depend on malloc() cannot be used, after calling this function.

@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
@param
const 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
const char* pathname
unsigned int uid
is user id, or -1u to not change
unsigned int gid
is group id, or -1u to not change
@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

chroot

Changes root directory.

@param
const char* path
@return
int
@raise ENOSYS on Windows

_classifypath

Classifies file path name.

For the purposes of this function, we always consider backslash interchangeable with forward slash, even though the underlying operating system might not. Therefore, for the sake of clarity, remaining documentation will only use the forward slash.

This function behaves the same on all platforms. For instance, this function will categorize C:/FOO.BAR as a DOS path, even if you're running on UNIX rather than DOS.

If you wish to check if a pathname is absolute, in a manner that's inclusive of DOS drive paths, DOS rooted paths, in addition to the New Technology UNC paths, then you may do the following:

if (_classifypath(str) & _kPathAbs) { ... }
To check if path is a relative path:

if (~_classifypath(str) & _kPathAbs) { ... }
Please note the above check includes rooted paths such as \foo which is considered absolute by MSDN and we consider it absolute although, it's technically relative to the current drive letter.

Please note that /foo/bar is an absolute path on Windows, even though it's actually a rooted path that's considered relative to current drive by WIN32.

@param
const char* s
@return
int
integer value that's one of following:
  • 0 if non-weird relative path e.g. c
  • _kPathAbs if absolute (or rooted dos) path e.g. /⋯
  • _kPathDos if c:, d:foo i.e. drive-relative path
  • _kPathAbs|_kPathDos if proper dos path e.g. c:/foo
  • _kPathDos|_kPathDev if dos device path e.g. nul, conin$
  • _kPathAbs|_kPathWin if //c, //?c, etc.
  • _kPathAbs|_kPathWin|_kPathDev if //./⋯, //?/⋯
  • _kPathAbs|_kPathWin|_kPathDev|_kPathRoot if //. or //?
  • _kPathAbs|_kPathNt e.g. \??\\⋯ (undoc. strict backslash)
@see "The Definitive Guide on Win32 to NT Path Conversion", James Forshaw, Google Project Zero Blog, 2016-02-29
@see "Naming Files, Paths, and Namespaces", MSDN 01/04/2021

clearenv

Removes all environment variables.

@return
int

clearerr

Clears error state on stream.

@param
struct FILE* f
is file object stream pointer
@return
void
@see clearerr_unlocked()
@threadsafe

clearerr_unlocked

@param
struct FILE* f
@return
void

__clk_tck

Returns system clock ticks per second.

The returned value is memoized. This function is intended to be used via the CLK_TCK macro wrapper.

The returned value is always greater than zero. It's usually 100 hertz which means each clock tick is 10 milliseconds long.

@return
int

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_getres

Returns granularity of clock.

@param
int clock
struct st_birthtim* ts
@return
int

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.

nowl                l:        45𝑐        15𝑛𝑠
rdtsc               l:        13𝑐         4𝑛𝑠
gettimeofday        l:        44𝑐        14𝑛𝑠
clock_gettime       l:        40𝑐        13𝑛𝑠
__clock_gettime     l:        35𝑐        11𝑛𝑠
sys_clock_gettime   l:       220𝑐        71𝑛𝑠
@param
int clock
can be CLOCK_REALTIME, CLOCK_MONOTONIC, etc.
ANONYMOUS-STRUCT* ts
is where the result is stored
@return
int
0 on success, or -1 w/ errno
@error EINVAL if clock isn't supported on this system
@see strftime(), gettimeofday()
@asyncsignalsafe

__clock_gettime_get

Returns pointer to fastest clock_gettime().

@param
_Bool* opt_out_isfast
@return
int(*)()

clone

Creates thread.

Threads are created in a detached manner. They currently can't be synchronized using wait() or posix signals. Threads created by this function should be synchronized using shared memory operations.

Any memory that's required by this system call wrapper is allocated to the top of your stack. This shouldn't be more than 128 bytes.

Your function is called from within the stack you specify. A return address is pushed onto your stack, that causes returning to jump to _Exit1() which terminates the thread. Even though the callback says it supports a return code, that'll only work on Linux and Windows.

The tls parameter is for thread-local storage. If you specify this then clone() will implicitly rewire libc (e.g. errno) to use TLS:

static char tib[64];
__initialize_tls(tib);
__install_tls(tib);
If you want a main process TLS size that's larger call it manually. Once you've done the above and/or started creating your own threads you'll be able to access your tls thread information block, using

char *p = __get_tls();
printf("errno is %d\n", *(int *)(p + 0x3c));
This function follows the same ABI convention as the Linux userspace libraries, with a few small changes. The varargs has been removed to help prevent broken code, and the stack size and tls size parameters are introduced for compatibility with FreeBSD.

To keep this system call lightweight, only the thread creation use case is polyfilled across platforms. For example, if you want fork that works on OpenBSD for example, don't do it with clone(SIGCHLD) and please just call fork(). Even if you do that on Linux, it will effectively work around libc features like atfork(), so that means other calls like getpid() may return incorrect values.

@param
void* func
is your callback function, which this wrapper requires not be null, otherwise EINVAL is raised. It is passed two args within the child thread: (1) the caller-supplied arg and (2) the new tid is always passed in the second arg for convenience
void* stk
points to the bottom of a caller allocated stack, which must be allocated via mmap() using the MAP_STACK flag, or else you won't get optimal performance and it won't work on OpenBSD
unsigned long stksz
is the size of that stack in bytes, we recommend that that this be set to GetStackSize() or else memory safety tools like kprintf() can't do as good and quick of a job; this value must be 16-aligned plus it must be at least 4192 bytes in size and it's advised to have the bottom-most page, be a guard page
int flags
which SHOULD always have all of these flags:

  • CLONE_THREAD
  • CLONE_VM
  • CLONE_FS
  • CLONE_FILES
  • CLONE_SIGHAND
This system call wrapper is intended for threads, and as such, we won't polyfill Linux's ability to simulate unrelated calls (e.g. fork, vfork) via clone() on other platforms. Please just call fork() and vfork() when that's what you want.

Your flags may also optionally also additionally bitwise-OR any combination of the following additional flags:

  • CLONE_PARENT_SETTID must be specified if you intend to set the ptid argument, which is guaranteed to be updated with the child tid BEFORE BOTH clone() returns and func is invoked
  • CLONE_CHILD_SETTID must be specified if you intend to set the ctid argument, which is guaranteed to be updated with the child tid before func is called, however we CAN NOT guarantee this will happen BEFORE clone() returns
  • CLONE_CHILD_CLEARTID causes *ctid = 0 upon child thread termination. This is used to implement join so that the parent may know when it's safe to free the child's stack memory, and as such, is guaranteed to happen AFTER the child thread has either terminated or has finished using its stack memory
  • CLONE_SETTLS is needed if you intend to specify the tls argument, which after thread creation may be accessed using __get_tls(). Doing this means that errno, gettid(), etc. correctly work. Caveat emptor if you choose not to do this.
void* arg
is passed as an argument to func in the child thread
int* ptid
void* tls
may be used to set the thread local storage segment; this parameter is ignored if CLONE_SETTLS is not set
int* ctid
lets the child receive its thread id without having to call gettid() and is ignored if CLONE_CHILD_SETTID isn't set
@return
int
tid of child on success, or -1 w/ errno
@threadsafe

close

Closes file descriptor.

This function may be used for file descriptors returned by functions like open, socket, accept, epoll_create, and landlock_create_ruleset.

This function should never be called twice for the same file descriptor, regardless of whether or not an error happened. However that doesn't mean the error should be ignored.

@param
int fd
@return
int
0 on success, or -1 w/ errno
@error EINTR means a signal was received while closing in which case close() does not need to be called again, since the fd will close in the background
@asyncsignalsafe
@vforksafe

close_range

Closes inclusive range of file descriptors, e.g.

// close all non-stdio file descriptors
if (close_range(3, -1, 0) == -1) {
  for (int i = 3; i < 256; ++i) {
    close(i);
  }
}
This is supported on Linux 5.9+, FreeBSD, and OpenBSD. On FreeBSD, flags must be zero. On OpenBSD, we call closefrom(int) so last should be -1 in order to get OpenBSD support, otherwise ENOSYS will be returned. We also polyfill closefrom on FreeBSD since it's available on older kernels.

On Linux, the following flags are supported:

  • CLOSE_RANGE_UNSHARE
  • CLOSE_RANGE_CLOEXEC
@param
unsigned int first
unsigned int last
unsigned int flags
@return
int
0 on success, or -1 w/ errno
@error ENOSYS if not Linux 5.9+ / FreeBSD / OpenBSD
@error EBADF on OpenBSD if first is greater than highest fd
@error EINVAL if flags are bad or first is greater than last
@error EMFILE if a weird race condition happens on Linux
@error EINTR possibly on OpenBSD
@error ENOMEM on Linux maybe

close_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

closefrom

Closes extra file descriptors, e.g.

// close all non-stdio file descriptors
if (closefrom(3) == -1) {
  for (int i = 3; i < 256; ++i) {
    close(i);
  }
}
@param
int first
@return
int
0 on success, or -1 w/ errno
@error ENOSYS if not Linux 5.9+ / FreeBSD / OpenBSD
@error EBADF on OpenBSD if first is greater than highest fd
@error EINVAL if flags are bad or first is greater than last
@error EMFILE if a weird race condition happens on Linux
@error EINTR possibly on OpenBSD
@error ENOMEM on Linux maybe
@note supported on Linux 5.9+, FreeBSD 8+, and OpenBSD

CloseHandle

Closes an open object handle.

@param
long hObject
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

closelog

Closes the file descriptor being used to write to the system logger

Use of closelog is optional

@return
void
@asyncsignalsafe

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
const char* name
char* pathbuf
unsigned long pathbufsz
@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
const char* var
is environment variable which may be used to override PATH search, and it can force a NULL result if it's empty
const char* cmd
is name of program, which is returned asap if it's an absolute path
@return
const char*
pointer to exe path string, or NULL if it couldn't be found or the environment variable was empty; noting that the caller should copy this string before saving it

CompareDnsNames

Compares DNS hostnames in reverse lexicographical asciibetical order.

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

CompareSlices

@param
const char* a
unsigned long n
const char* b
unsigned long m
@return
int

CompareSlicesCase

@param
const char* a
unsigned long n
const char* b
unsigned long m
@return
int

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

connect

Connects socket to remote end.

ProTip: Connectionless sockets, e.g. UDP, can be connected too. The benefit is not needing to specify the remote address on each send. It also means getsockname() can be called to retrieve routing details.

@param
int fd
void* addr
unsigned int addrsize
@return
int
0 on success or -1 w/ errno
@asyncsignalsafe
@restartable (unless SO_RCVTIMEO)

_construct

Calls global initialization functions.

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

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

_copyfd

Copies data between fds the old fashioned way.

Even though Cosmopolitan polyfills copy_file_range() to fallback to doing this, it's useful to call this function in cases where you know it'd be more helpful to get the larger buffer size with read/write.

Reads are allowed to be interrupted. Writes are uninterruptible. If we get an interrupt when partial data was written, we return the partial amount. Therefore the file descriptors are guaranteed to remain in a consistent state, provided EINTR is the only error.

If n is 0 then 0 is returned and no i/o operations are performed.

@param
int infd
int outfd
unsigned long n
@return
long
bytes successfully exchanged

copyfile

Copies file.

This implementation goes 2x faster than the cp command that comes included with most systems since we use the newer copy_file_range() system call rather than sendfile().

@param
const char* src
const char* dst
int flags
may have COPYFILE_PRESERVE_TIMESTAMPS, COPYFILE_NOCLOBBER
@return
int
0 on success, or -1 w/ errno

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
double x
@return
double
@note should take ~5ns

cosh

Returns hyperbolic cosine of 𝑥.

cosh(x) = (exp(x) + 1/exp(x))/2
        = 1 + 0.5*(exp(x)-1)*(exp(x)-1)/exp(x)
        = 1 + x*x/2 + o(x^4)
@param
double x
@return
double

coshf

Returns hyperbolic cosine of 𝑥.

cosh(x) = (exp(x) + 1/exp(x))/2
        = 1 + 0.5*(exp(x)-1)*(exp(x)-1)/exp(x)
        = 1 + x*x/2 + o(x^4)
@param
float x
@return
float

coshl

Returns hyperbolic cosine of 𝑥.

cosh(x) = (exp(x) + 1/exp(x))/2
        = 1 + 0.5*(exp(x)-1)*(exp(x)-1)/exp(x)
        = 1 + x*x/2 + o(x^4)
@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

cosmo2flock

@param
unsigned long memory
@return
void

_countbits

Returns population count of array.

@param
void* a
is byte sequence
unsigned long n
@return
unsigned long
number of bits set to one
@note 30gbps on Nehalem (Intel 2008+) otherwise 3gbps



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)
This implementation takes 32 picoseconds per byte or 30 gibibyte/s.
@param
unsigned int h
is initial value
void* data
unsigned long size
@return
unsigned int

crc32c

Computes 32-bit Castagnoli Cyclic Redundancy Check.

@param
unsigned int init
is the initial hash value
void* data
points to the data
unsigned long size
is the byte size of data
@return
unsigned int
eax is the new hash value
@note Used by ISCSI, TensorFlow, etc.

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
const 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

CreateDirectory

Creates directory on the New Technology.

@param
const unsigned short* lpPathName
struct NtSecurityAttributes* lpSecurityAttributes
@return
int
handle, or -1 on failure
@note this wrapper takes care of ABI, STRACE(), and __winerr()

CreateFile

Opens file on the New Technology.

@param
const unsigned short* lpFileName
unsigned int dwDesiredAccess
unsigned int dwShareMode
struct NtSecurityAttributes* opt_lpSecurityAttributes
int dwCreationDisposition
unsigned int dwFlagsAndAttributes
long opt_hTemplateFile
@return
long
handle, or -1 on failure
@note this wrapper takes care of ABI, STRACE(), and __winerr()

CreateFileMapping

Creates file mapping object on the New Technology.

@param
long opt_hFile
may be -1 for MAP_ANONYMOUS behavior
struct NtSecurityAttributes* opt_lpFileMappingAttributes
unsigned int flProtect
unsigned int dwMaximumSizeHigh
unsigned int dwMaximumSizeLow
const unsigned short* opt_lpName
@return
long
handle, or 0 on failure
@note this wrapper takes care of ABI, STRACE(), and __winerr()
@see MapViewOfFileEx()

CreateFileMappingNuma

Creates file mapping object on the New Technology.

@param
long opt_hFile
may be -1 for MAP_ANONYMOUS behavior
struct NtSecurityAttributes* opt_lpFileMappingAttributes
unsigned int flProtect
unsigned int dwMaximumSizeHigh
unsigned int dwMaximumSizeLow
const unsigned short* opt_lpName
unsigned int nndDesiredNumaNode
@return
long
handle, or 0 on failure
@note this wrapper takes care of ABI, STRACE(), and __winerr()
@see MapViewOfFileExNuma()

CreateMemoryInterval

@param
struct _mmi* mm
int i
@return
int

CreateNamedPipe

Creates pipe.

@param
const unsigned short* lpName
unsigned int dwOpenMode
unsigned int dwPipeMode
unsigned int nMaxInstances
unsigned int nOutBufferSize
unsigned int nInBufferSize
unsigned int nDefaultTimeOutMs
struct NtSecurityAttributes* opt_lpSecurityAttributes
@return
long
handle to server end
@note this wrapper takes care of ABI, STRACE(), and __winerr()

CreatePipe

Creates anonymous pipe.

@param
long* out_hReadPipe
long* out_hWritePipe
struct NtSecurityAttributes* opt_lpPipeAttributes
unsigned int nSize
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

CreatePipeName

@param
unsigned short* a
@return
unsigned short*

CreateProcess

Creates process on the New Technology.

@param
const unsigned short* opt_lpApplicationName
unsigned short* lpCommandLine
struct NtSecurityAttributes* opt_lpProcessAttributes
struct NtSecurityAttributes* opt_lpThreadAttributes
int bInheritHandles
unsigned int dwCreationFlags
void* opt_lpEnvironment
const unsigned short* opt_lpCurrentDirectory
struct NtStartupInfo* lpStartupInfo
struct NtProcessInformation* opt_out_lpProcessInformation
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()


CreateThread

Opens file on the New Technology.

@param
struct NtSecurityAttributes* lpThreadAttributes
unsigned long dwStackSize
may be 0 for default per executable
unsigned int(*)() lpStartAddress
void* lpParameter
unsigned int dwCreationFlags
unsigned int* opt_lpThreadId
@return
long
thread handle, or 0 on failure
@note this wrapper takes care of ABI, STRACE(), and __winerr()

critbit0_allprefixed

Invokes callback for all items with prefix.

@param
struct critbit0* t
const 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
const char* u
NUL-terminated string
@return
_Bool
@note h/t djb and agl

critbit0_delete

Removes 𝑢 from 𝑡.

@param
struct critbit0* t
tree
const 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
is critical bit tree
char* u
is nul-terminated string which must be 8+ byte aligned and becomes owned by the tree afterwards
unsigned long ulen
@return
int
true if 𝑡 was mutated, or -1 w/ errno
@note h/t djb and agl

critbit0_get

Returns first item in 𝑡 with prefix 𝑢.

@param
struct critbit0* t
tree
const 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
const char* u
NUL-terminated string
@return
int
true if 𝑡 was mutated, or -1 w/ errno
@note h/t djb and agl

crypt

Encrypts password the old fashioned way.

The method of encryption depends on the first three chars of salt:

  • $1$ is MD5
  • $2$ is Blowfish
  • $5$ is SHA-256
  • $6$ is SHA-512
  • Otherwise DES
@param
const char* key
const char* salt
@return
char*
static memory with encrypted password
@see third_party/argon2/

crypt_r

Encrypts password the old fashioned way.

The method of encryption depends on the first three chars of salt:

  • $1$ is MD5
  • $2$ is Blowfish
  • $5$ is SHA-256
  • $6$ is SHA-512
  • Otherwise DES
@param
const char* key
const char* salt
struct crypt_data* data
@return
char*
static memory with encrypted password
@see third_party/argon2/

ctermid

Generates path of controlling terminal.

This function always returns /dev/tty since that's supported by all supported platforms, and polyfilled on Windows.

@param
char* s
may optionally specify an outut buffer L_ctermid in size
@return
char*
pointer to s (or image memory if s was null) which contains path of controlling terminal, or empty string if if this program is a win32 app running in gui mode

cthread_attr_destroy

@param
struct cthread_attr_t* attr
@return
int

cthread_attr_getdetachstate

@param
struct cthread_attr_t* attr
@return
int

cthread_attr_getguardsize

@param
struct cthread_attr_t* attr
@return
unsigned long

cthread_attr_getstacksize

@param
struct cthread_attr_t* attr
@return
unsigned long

cthread_attr_init

@param
struct cthread_attr_t* attr
@return
int

cthread_attr_setdetachstate

@param
struct cthread_attr_t* attr
int mode
@return
int

cthread_attr_setguardsize

@param
struct cthread_attr_t* attr
unsigned long size
@return
int

cthread_attr_setstacksize

@param
struct cthread_attr_t* attr
unsigned long size
@return
int

cthread_memory_wait32

@param
int* addr
int val
ANONYMOUS-STRUCT* timeout
@return
int

cthread_memory_wake32

@param
int* addr
int n
@return
int

cthread_self

Returns thread descriptor of the current thread.

@return
struct cthread_descriptor_t*

cthread_sem_destroy

Destroys semaphore.

@param
union cthread_sem_t* sem
@return
int

cthread_sem_init

Initializes semaphore.

@param
union cthread_sem_t* sem
int count
@return
int

cthread_sem_signal

Notifies a thread waiting on semaphore.

@param
union cthread_sem_t* sem
@return
int

cthread_sem_wait

Waits on semaphore.

@param
union cthread_sem_t* sem
int spin
ANONYMOUS-STRUCT* timeout
@return
int

cthread_sem_wait_futex

Waits on semaphore with kernel assistance.

@param
union cthread_sem_t* sem
ANONYMOUS-STRUCT* timeout
@return
int

cthread_sem_wait_spin

Waits on semaphore without kernel assistance.

@param
union cthread_sem_t* sem
unsigned long count
int spin
ANONYMOUS-STRUCT* timeout
@return
int

ctime

@param
const long* timep
@return
char*

ctime_r

@param
const 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

__cxa_printexits

Prints global destructors.

@param
struct FILE* f
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


DecodeBase64

Decodes base64 ascii representation to binary.

This supports the following alphabets:

  • ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
  • ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_
@param
const char* data
is input value
unsigned long size
if -1 implies strlen
unsigned long* out_size
if non-NULL receives output length
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

DecodeDosArgv

@param
int ignore
struct st_* st
@return
void

DecodeLatin1

Decodes ISO-8859-1 to UTF-8.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

DecodeNf32

Decodes u32 from ANSI Nf sequence.

@param
const char* s
char** e
@return
unsigned int

_defer

Calls fn(arg) when function returns.

This garbage collector overwrites the return address on the stack so that the RET instruction calls a trampoline which calls free(). It's loosely analogous to Go's defer keyword rather than a true cycle gc.

@param
void* fn
void* arg
@return
void*
@warning do not return a gc()'d pointer
@warning do not realloc() with gc()'d pointer
@warning be careful about static keyword due to impact of inlining
@note you should use -fno-omit-frame-pointer

__defer

Adds destructor to garbage shadow stack.

@param
struct StackFrame* frame
is passed automatically by wrapper macro
void* fn
takes one argument
void* arg
is passed to fn(arg)
@return
void
arg

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

DeleteFile

Deletes existing file.

@param
const unsigned short* lpPathName
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

DescribeCapability

@param
char* buf
int x
@return
const char*

DescribeClockName

Describes clock_gettime() clock argument.

@param
char* buf
int x
@return
const char*

DescribeDirfd

@param
char* buf
int dirfd
@return
const char*

DescribeFlags

@param
char* p
unsigned long n
struct DescribeFlags* d
unsigned long m
const char* prefix
unsigned int x
@return
const char*

DescribeFrame

@param
char* buf
int x
@return
const char*

DescribeFutexResult

@param
char* buf
int ax
@return
const char*

DescribeHow

@param
char* buf
int how
@return
const char*

DescribeIov

@param
struct iovec* iov
int iovlen
long rem
@return
void

DescribeIovNt

@param
struct ProviderSpecific* iov
unsigned int iovlen
long rem
@return
void

DescribeMagnum

@param
char* b
struct MagnumStr* m
const char* p
int x
@return
char*

DescribeMapFlags

@param
char* buf
int x
@return
const char*

DescribeMapping

@param
char* p
int prot
int flags
@return
const char*

DescribeNtConsoleInFlags

@param
char* buf
unsigned int x
@return
const char*

DescribeNtConsoleOutFlags

@param
char* buf
unsigned int x
@return
const char*

DescribeNtCreationDisposition

@param
unsigned int x
@return
const char*

DescribeNtFileAccessFlags

@param
char* buf
unsigned int x
@return
const char*

DescribeNtFileFlagAttr

@param
char* buf
unsigned int x
@return
const char*

DescribeNtFileMapFlags

@param
char* buf
unsigned int x
@return
const char*

DescribeNtFileShareFlags

@param
char* buf
unsigned int x
@return
const char*

DescribeNtFiletypeFlags

@param
char* buf
unsigned int x
@return
const char*

DescribeNtFutexOp

@param
int x
@return
const char*

DescribeNtMovFileInpFlags

@param
char* buf
unsigned int x
@return
const char*

DescribeNtPageFlags

@param
char* buf
unsigned int x
@return
const char*

DescribeNtPipeModeFlags

@param
char* buf
unsigned int x
@return
const char*

DescribeNtPipeOpenFlags

@param
char* buf
unsigned int x
@return
const char*

DescribeNtProcAccessFlags

@param
char* buf
unsigned int x
@return
const char*

DescribeNtSecurityAttributes

@param
struct NtSecurityAttributes* p
@return
const char*

DescribeNtStartFlags

@param
char* buf
unsigned int x
@return
const char*

DescribeNtSymlinkFlags

@param
char* buf
unsigned int x
@return
const char*

DescribeOpenFlags

Describes clock_gettime() clock argument.

@param
char* buf
int x
@return
const char*

DescribePersonalityFlags

@param
char* buf
int x
@return
const char*

DescribePollFlags

@param
char* buf
int x
@return
const char*

DescribePrctlOperation

@param
int x
@return
const char*

DescribeProt

@param
char* p
int prot
@return
char*

DescribeProtFlags

@param
char* buf
int x
@return
const char*

DescribeRemapFlags

@param
char* buf
int x
@return
const char*

DescribeRlimit

@param
char* buf
int rc
struct rlimit* rlim
@return
const char*

DescribeRlimitName

Describes setrlimit() / getrlimit() argument.

@param
char* buf
int x
@return
const char*

DescribeSchedParam

Describes clock_gettime() clock argument.

@param
char* buf
struct sched_param* x
@return
const char*

DescribeSchedPolicy

Describes clock_gettime() clock argument.

@param
char* buf
int x
@return
const char*


DescribeSigaction

@param
char* buf
int rc
struct sigaction* sa
@return
const char*

DescribeSigaltstk

@param
char* buf
int rc
struct uc_stack* ss
@return
const char*

DescribeSigset

@param
char* buf
int rc
struct sa_mask* ss
@return
const char*

DescribeSockaddr

@param
char* buf
struct sockaddr* sa
unsigned long sasize
@return
const char*

DescribeSocketFamily

@param
char* buf
int family
@return
const char*

DescribeSocketProtocol

@param
char* buf
int family
@return
const char*

DescribeSocketType

@param
char* buf
int type
@return
const char*

DescribeSockLevel

Describes setsockopt() level arguments.

@param
char* buf
int x
@return
const char*

DescribeSockOptname

Describes setsockopt() optname arguments.

@param
char* buf
int l
int x
@return
const char*

DescribeStat

@param
char* buf
int rc
struct stat* st
@return
const char*

DescribeTimespec

@param
char* buf
int rc
struct st_birthtim* ts
@return
const char*

DescribeTimeval

@param
char* buf
int rc
ANONYMOUS-STRUCT* tv
@return
const char*

DeserializeDnsHeader

Serializes DNS message h to wire.

@param
struct DnsHeader* h
const unsigned char* p
@return
void
number of bytes read (always 12) or -1 w/ errno

DestroyHttpMessage

Destroys HTTP message parser.

@param
struct HttpMessage* r
@return
void

DeviceIoControl

Does device file stuff on the New Technology.

@param
long hDevice
unsigned int dwIoControlCode
void* lpInBuffer
unsigned int nInBufferSize
void* lpOutBuffer
unsigned int nOutBufferSize
unsigned int* lpBytesReturned
struct inout_lpOverlapped* lpOverlapped
@return
int
handle, or -1 on failure
@note this wrapper takes care of ABI, STRACE(), and __winerr()

__die

Aborts process after printing a backtrace.

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

@noreturn

difftime

@param
long time1
long time0
@return
double

dirfd

Returns file descriptor associated with DIR object.

@param
struct dirstream* dir
@return
int

dirname

Returns directory portion of path, e.g.

path     │ dirname() │ basename()
─────────────────────────────────
.        │ .         │ .
..       │ .         │ ..
/        │ /         │ /
usr      │ .         │ usr
/usr/    │ /         │ usr
/usr/lib │ /usr      │ lib
@param
char* path
is UTF-8 and may be mutated, but not expanded in length
@return
char*
pointer to path, or inside path, or to a special r/o string
@see basename()
@see SUSv2

div

@param
int num
int den
@return
struct div_t

__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

dlbulk_free

@param
void** array
unsigned long nelem
@return
unsigned long

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

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

dlindependent_comalloc

@param
unsigned long n_elements
unsigned long* sizes
void** chunks
@return
void**

dlmallinfo

@param
struct nm*
@return
struct nm

dlmalloc

@param
unsigned long bytes
@return
void*




dlmalloc_inspect_all

@param
void(*)() handler
void* arg
@return
void


dlmalloc_requires_more_vespene_gas

Acquires more system memory for dlmalloc.

@param
unsigned long size
@return
void*
memory map address on success, or null w/ errno

dlmalloc_set_footprint_limit

@param
unsigned long bytes
@return
unsigned long


dlmalloc_trim

@param
unsigned long pad
@return
int

dlmalloc_usable_size

@param
void* mem
@return
unsigned long

dlmallopt

@param
int param_number
int value
@return
int

dlmemalign

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

dlopen

@param
const 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
const char* name
@return
void*

dlvalloc

@param
unsigned long bytes
@return
void*

__dos2errno

Translates Windows error using superset of consts.sh.

This function is called by __winerr(). It can only be used on Windows, because it returns an errno. Normally, errnos will be programmed to be the same as DOS errnos, per consts.sh. But since there's so many more errors in DOS, this function provides an added optional benefit mapping additional constants onto the errnos in consts.sh.

@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
const 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*

DumpHexc

Turns data into "\x00..." string literal.

@param
const char* p
unsigned long n
unsigned long* z
@return
char*

dup

Duplicates file descriptor.

The O_CLOEXEC flag shall be cleared from the resulting file descriptor; see dup3() to preserve it.

@param
int fd
remains open afterwards
@return
int
some arbitrary new number for fd
@raise EOPNOTSUPP if zipos file
@raise EBADF if fd isn't open
@asyncsignalsafe
@vforksafe

dup2

Duplicates file descriptor, granting it specific number.

The O_CLOEXEC flag shall be cleared from the resulting file descriptor; see dup3() to preserve it.

Unlike dup3(), the dup2() function permits oldfd and newfd to be the same, in which case the only thing this function does is test if oldfd is open.

@param
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
@raise EBADF is oldfd isn't open
@raise EBADF is newfd negative or too big
@raise EINTR if a signal handler was called
@asyncsignalsafe
@vforksafe

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
may have O_CLOEXEC which is needed to preserve the close-on-execve() state after file descriptor duplication
@return
int
newfd on success, or -1 w/ errno
@raise EINVAL if flags has unsupported bits
@raise EINVAL if newfd equals oldfd
@raise EBADF is oldfd isn't open
@raise EBADF is newfd negative or too big
@raise EINTR if a signal handler was called
@see dup(), dup2()

E2BIG

Argument list too errno_t.

@type
const int

EACCES

Permission denied.

@type
const int

eaccess

Performs access() check using effective user/group id.

@param
const char* filename
int amode
@return
int

EADDRINUSE

Address already in use.

@type
const int

EADDRNOTAVAIL

Address not available.

@type
const int

EAFNOSUPPORT

Address family not supported.

@type
const int

EAGAIN

Resource temporarily unavailable (e.g. SO_RCVTIMEO expired, too many processes, too much memory locked, read or write with O_NONBLOCK needs polling, etc.).

@type
const int

EALREADY

Connection already in progress.

@type
const int

EBADF

Bad file descriptor.

@type
const int

EBADMSG

Bad message.

@type
const int

EBUSY

Device or resource busy.

@type
const int

ECANCELED

Operation canceled.

@type
const int

ECHILD

No child process.

@type
const int

ECONNABORTED

Connection reset before accept.

@type
const int

ECONNREFUSED

Connection refused error.

@type
const int

ECONNRESET

Connection reset by client.

@type
const int

ecvt

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

EDEADLK

Resource deadlock avoided.

@type
const int

EDESTADDRREQ

Destination address required.

@type
const int

EDOM

Mathematics argument out of domain of function.

@type
const int

EDQUOT

Disk quota exceeded.

@type
const int

EEXIST

File exists.

@type
const int

EFAULT

Pointer passed to system call that would otherwise segfault.

@type
const int

EFBIG

File too large.

@type
const int

EfiMain

EFI Application Entrypoint.

This entrypoint is mutually exclusive from WinMain since Windows apps and EFI apps use the same PE binary format. So if you want to trade away Windows so that you can use UEFI instead of the normal BIOS boot process, do this:

STATIC_YOINK("EfiMain");
int main() { ... }
You can use QEMU to test this, but please note that UEFI goes thousands of times slower than the normal BIOS boot

qemu-system-x86_64 \
  -bios OVMF.fd    \
  -nographic       \
  -net none        \
  -drive format=raw,file=fat:rw:o/tool/viz
FS0:
deathstar.com
@param
unsigned long ImageHandle
struct EFI_SYSTEM_TABLE* SystemTable
@return
unsigned long
@see libc/dce.h

EFTYPE

Inappropriate file type or format. (BSD only)

@type
const int

EHOSTDOWN

Host down error.

@type
const int

EHOSTUNREACH

Host unreachable error.

@type
const int

EIDRM

Identifier removed.

@type
const int

EILSEQ

Unicode decoding error.

@type
const int

EINPROGRESS

Operation already in progress.

@type
const int

EINTR

The greatest of all errnos.

@type
const int

EINVAL

Invalid argument.

@type
const int

EIO

Unix consensus.

@type
const int

EISCONN

Socket is connected.

@type
const int

EISDIR

Is a a directory.

@type
const int


ELOOP

Too many levels of symbolic links.

@type
const int

EMEDIUMTYPE

Wrong medium type.

@type
const int

EMFILE

Too many open files.

@type
const int


EMSGSIZE

Message too errno_t.

@type
const int

EMULTIHOP

Multihop attempted.

@type
const int

ENAMETOOLONG

Filename too errno_t.

@type
const int

EncodeBase64

Encodes binary to base64 ascii representation.

@param
const char* data
is input value
unsigned long size
if -1 implies strlen
unsigned long* out_size
if non-NULL receives output length
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

EncodeHttpHeaderValue

Encodes HTTP header value.

This operation involves the following:

  1. Trim whitespace.
  2. Turn UTF-8 into ISO-8859-1.
  3. Make sure no C0 or C1 control codes are present (except tab).
If the input value isn't thompson-pike encoded then this implementation will fall back to latin1 in most cases.
@param
const char* data
is input value
unsigned long size
if -1 implies strlen
unsigned long* out_size
if non-NULL receives output length on success
@return
char*
allocated NUL-terminated string, or NULL w/ errno

EncodeLatin1

Encodes UTF-8 to ISO-8859-1.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
int f
can kControlC0, kControlC1, kControlWs to forbid
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno
@error EILSEQ means UTF-8 found we can't or won't re-encode
@error ENOMEM means malloc() failed

EncodeNf32

Encodes u32 as ANSI Nf sequence content.

@param
char* p
unsigned int x
@return
char*

EncodeUrl

Encodes URL.

@param
struct Url* h
unsigned long* z
if not null receives string length of result
@return
char*
nul-terminated url string needing free
@see ParseUrl()

encrypt

@param
char* block
int edflag
@return
void

endgrent

@return
void

endhostent

@return
void

endnetent

@return
void

endprotoent

@return
void

endpwent

@return
void

endservent

@return
void

endswith

Returns true if s has suffix.

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

endswith16

Returns true if s has suffix.

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

ENETDOWN

Network is down.

@type
const int

ENETRESET

Connection reset by network.

@type
const int

ENETUNREACH

Host is unreachable.

@type
const int

ENFILE

Too many open files in system.

@type
const int

ENOBUFS

No buffer space available.

@type
const int

ENODATA

No data.

@type
const int

ENODEV

No such device.

@type
const int

ENOENT

No such file or directory.

@type
const int

ENOEXEC

Exec format error.

@type
const int

ENOLCK

No locks available.

@type
const int


ENOMEDIUM

No medium found.

@type
const int

ENOMEM

We require more vespene gas.

@type
const int

ENOMSG

No message error.

@type
const int

ENONET

No network.

@type
const int

ENOPROTOOPT

Protocol not available.

@type
const int

ENOSPC

No space left on device.

@type
const int

ENOSR

Out of streams resources.

@type
const int

ENOSTR

No string.

@type
const int

ENOSYS

System call unavailable.

@type
const int
@note kNtErrorInvalidFunction on NT

ENOTBLK

Block device required.

@type
const int

ENOTCONN

Socket is not connected.

@type
const int

ENOTDIR

Not a directory.

@type
const int

ENOTEMPTY

Directory not empty.

@type
const int

ENOTRECOVERABLE

State not recoverable.

@type
const int

ENOTSOCK

Not a socket.

@type
const int

ENOTSUP

Operation not supported.

@type
const int

ENOTTY

Inappropriate i/o control operation.

@type
const int

__ensurefds

Grows file descriptor array memory if needed.

@param
int fd
@return
int
@asyncsignalsafe
@threadsafe

__ensurefds_unlocked

Grows file descriptor array memory if needed.

@param
int fd
@return
int
@see libc/runtime/memtrack64.txt
@see libc/runtime/memtrack32.txt
@asyncsignalsafe

ENXIO

No such device or address.

@type
const int

EOPNOTSUPP

Socket operation not supported.

@type
const int

EOVERFLOW

Overflow error.

@type
const int

EOWNERDEAD

Owner died.

@type
const int

EPERM

Operation not permitted.

@type
const int
@note kNtErrorInvalidAccess on NT

EPFNOSUPPORT

Protocol family not supported.

@type
const int

EPIPE

Broken pipe.

@type
const int

epoll_create

Creates new epoll instance.

@param
int size
is ignored but must be greater than zero
@return
int
epoll file descriptor, or -1 on failure

epoll_create1

Creates new epoll instance.

@param
int flags
must be zero or can have O_CLOEXEC
@return
int
epoll file descriptor, or -1 on failure

epoll_ctl

Controls which socket events are monitored.

It is recommended to always explicitly remove a socket from its epoll set using EPOLL_CTL_DEL before closing it. As on Linux, your closed sockets are automatically removed from the epoll set, but wepoll may not be able to detect that a socket was closed until the next call to epoll_wait().

@param
int epfd
is file descriptor created by epoll_create()
int op
can be EPOLL_CTL_{ADD,MOD,DEL}
int fd
is file descriptor to monitor
struct epoll_event* ev
is ignored if op is EPOLL_CTL_DEL
@return
int
0 on success, or -1 w/ errno
@error ENOTSOCK on Windows if fd isn't a socket :(

epoll_wait

Receives socket events.

@param
int epfd
struct epoll_event* events
will receive information about what happened
int maxevents
is array length of events
int timeoutms
is milliseconds, 0 to not block, or -1 for forever
@return
int
number of events stored, 0 on timeout, or -1 w/ errno
@norestart

EPROTO

Protocol error.

@type
const int

EPROTONOSUPPORT

Protocol not supported.

@type
const int

EPROTOTYPE

Protocol wrong type for socket.

@type
const int

ERANGE

Result too large.

@type
const int

EREMOTE

Remote error.

@type
const int

ERESTART

Please restart syscall.

@type
const int

erf

Returns error function of 𝑥.

@param
double x
@return
double

erfc

Returns complementary error function of 𝑥.

@param
double x
@return
double

erfcf

@param
float x
@return
float

erff

@param
float x
@return
float

EROFS

Read-only filesystem.

@type
const int

err

@param
int eval
const 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.

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

__errno_location

Returns address of errno variable.

@return
int*
@see __initialize_tls()
@see __install_tls()

errx

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

_escapedos

Escapes command so DOS can run it.

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

EscapeFragment

Escapes URL fragment.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

EscapeHost

Escapes URL host or registry name.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

EscapeHtml

Escapes HTML entities.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

EscapeIp

Escapes URL IP-literal.

This is the same as EscapeHost except colon is permitted.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

EscapeJsStringLiteral

Escapes UTF-8 data for JavaScript or JSON string literal.

HTML entities and forward slash are escaped too for added safety.

We assume the UTF-8 is well-formed and can be represented as UTF-16. Things that can't be decoded will fall back to binary. Things that can't be encoded will use invalid codepoint markers. This function is agnostic to numbers that have been used with malicious intent in the past under buggy software. Noncanonical encodings such as overlong NUL are canonicalized as NUL. Therefore it isn't necessary to say EscapeJsStringLiteral(Underlong(𝑥)) since EscapeJsStringLiteral(𝑥) will do the same thing.

@param
char** r
is realloc'able output buffer reused between calls
unsigned long* y
is used to track byte length of *r
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
@return
char*
*r on success, or null w/ errno

EscapeParam

Escapes query/form name/parameter.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

EscapePass

Escapes URL password.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

EscapePath

Escapes URL path.

This is the same as EscapePathSegment() except slash is allowed.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

EscapeSegment

Escapes URL path segment.

Please note this will URI encode the slash character. That's because segments are the labels between the slashes in a path.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

EscapeUrl

Escapes URL component using generic table.

This function is agnostic to the underlying charset. Always using UTF-8 is a good idea.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
const char* T
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno
@see kEscapeAuthority
@see kEscapeIpLiteral
@see kEscapePath
@see kEscapePathSegment
@see kEscapeParam
@see kEscapeFragment

EscapeUrlView

Escapes URL component using generic table w/ stpcpy() api.

@param
char* p
struct fragment* v
const char* T
@return
char*

EscapeUser

Escapes URL user name.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

ESHUTDOWN

Cannot send after transport endpoint shutdown.

@type
const int

ESOCKTNOSUPPORT

Socket type not supported.

@type
const int

ESPIPE

Invalid seek.

@type
const int

ESRCH

No such process.

@type
const int

ESTALE

Stale error.

@type
const int

ETIME

Timer expired.

@type
const int

ETIMEDOUT

Connection timed out.

@type
const int

ETOOMANYREFS

Too many references: cannot splice.

@type
const int

ETXTBSY

Won't open executable that's executing in write mode.

@type
const int

euidaccess

Performs access() check using effective user/group id.

@param
const char* filename
int amode
@return
int

EUSERS

Too many users.

@type
const int

EXDEV

Improper link.

@type
const int

execl

Executes program, with current environment.

The current process is replaced with the executed one.

@param
const char* exe
const 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
const char* exe
const 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
const char* prog
is program to launch (may be PATH searched)
const 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
const char* exe
char** argv
@return
int
@asyncsignalsafe
@vforksafe

execve

Replaces current process with program.

@param
const char* prog
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
const 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
const 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

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

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 on unix (but not windows)
@noreturn
@asyncsignalsafe
@threadsafe
@vforksafe

_Exit1

Terminates thread with raw system call.

@param
int rc
only works on Linux and Windows
@noreturn
@see cthread_exit()
@threadsafe

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.

@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 𝑒^𝑥-𝟷.

@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
const char* path
is a filename or directory
int mode
can be R_OK, W_OK, X_OK, F_OK
unsigned int flags
can have AT_EACCESS, AT_SYMLINK_NOFOLLOW
@return
int
0 if ok, or -1 and sets errno
@note on Linux flags is only supported on Linux 5.8+
@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

__fbufsize

Returns capacity of stdio stream buffer.

@param
struct FILE* f
@return
unsigned long

fchdir

Sets current directory based on file descriptor.

This does *not* update the PWD environment variable.

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

fchmod

Changes file permissions via open()'d file descriptor.

@param
int fd
unsigned int mode
contains octal flags (base 8)
@return
int
@asyncsignalsafe
@see chmod()

fchmodat

Changes permissions on file, e.g.:

CHECK_NE(-1, fchmodat(AT_FDCWD, "foo/bar.txt", 0644));
CHECK_NE(-1, fchmodat(AT_FDCWD, "o/default/program.com", 0755));
CHECK_NE(-1, fchmodat(AT_FDCWD, "privatefolder/", 0700));
@param
int dirfd
const char* path
must exist
unsigned int mode
contains octal flags (base 8)
int flags
can have AT_SYMLINK_NOFOLLOW
@return
int
@errors ENOENT, ENOTDIR, ENOSYS
@asyncsignalsafe
@see fchmod()

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
@raises ENOSYS on Windows

fchownat

Changes owner and/or group of path.

@param
int dirfd
is open()'d relative-to directory, or AT_FDCWD, etc.
const char* path
unsigned int uid
is user id, or -1 to not change
unsigned int gid
is group id, or -1 to not change
int flags
can have AT_SYMLINK_NOFOLLOW, etc.
@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));
This function lets you duplicate file descriptors without running into an edge case where they take over stdio handles:

CHECK_GE((newfd = fcntl(oldfd, F_DUPFD,         3)), 3);
CHECK_GE((newfd = fcntl(oldfd, F_DUPFD_CLOEXEC, 3)), 3);
This function implements POSIX Advisory Locks, e.g.

CHECK_NE(-1, fcntl(zfd, F_SETLKW, &(struct flock){F_WRLCK}));
// ...
CHECK_NE(-1, fcntl(zfd, F_SETLK, &(struct flock){F_UNLCK}));
Please be warned that locks currently do nothing on Windows since figuring out how to polyfill them correctly is a work in progress.
@param
int fd
int cmd
can be F_{GET,SET}{FD,FL}, etc.
...
@return
int
0 on success, or -1 w/ errno
@asyncsignalsafe
@restartable

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 sync(), fsync(), sync_file_range()
@see __nosync to secretly disable
@asyncsignalsafe

fdim

Returns positive difference.

@param
double x
double y
@return
double

fdimf

Returns positive difference.

@param
float x
float y
@return
float

fdiml

Returns positive difference.

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

fdopen

Allocates stream object for already-opened file descriptor.

@param
int fd
existing file descriptor or -1 for plain old buffer
const 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

feclearexcept

@param
int mask
@return
int

fegetenv

@param
void** envp
@return
int

fegetround

Returns rounding mode.

This implementation retrieves it from the x87 FPU control word.

@return
int
@see fesetround() for changing this

__fentry__

Function entry hook stub.

@return
@note cc -pg -mfentry adds this to the start of every function
@see libc/log/shadowargs.ncabi.c
@mode long,legacy,real

feof

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

@param
struct FILE* f
is file object stream pointer
@return
int
@see feof_unlocked()
@threadsafe

feof_unlocked

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

@param
struct FILE* f
is file object stream pointer
@return
int
@see feof()

feraiseexcept

@param
int mask
@return
int

ferror

Returns nonzero if stream is in error state.

@param
struct FILE* f
is file stream pointer
@return
int
non-zero if and only if it's an error state
@see ferror_unlocked(), feof()
@note EOF doesn't count
@threadsafe

ferror_unlocked

Returns nonzero if stream is in error state.

@param
struct FILE* f
is file stream pointer
@return
int
non-zero if and only if it's an error state
@note EOF doesn't count
@see ferror(), feof()

fesetenv

@param
void** envp
@return
int

fesetround

Sets rounding mode.

This configures the x87 FPU as well as SSE.

@param
int mode
may be FE_TONEAREST, FE_DOWNWARD, FE_UPWARD, or FE_TOWARDZERO
@return
int
0 on success, or -1 on error

fetestexcept

@param
int mask
@return
int

fflush

Blocks until data from stream buffer is written out.

@param
struct FILE* f
is the stream handle, or 0 for all streams
@return
int
is 0 on success or -1 on error
@threadsafe

fflush_unlocked

Blocks until data from stream buffer is written out.

@param
struct FILE* f
is the stream handle, or 0 for all streams
@return
int
is 0 on success 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 byte from stream.

@param
struct FILE* f
is non-null file object stream pointer
@return
int
byte in range 0..255, or -1 w/ errno
@see fgetc_unlocked()
@threadsafe

fgetc_unlocked

Reads byte from stream.

@param
struct FILE* f
is file object stream pointer
@return
int
byte in range 0..255, or -1 w/ errno
@see fgetc()

fgetln

Retrieves line from stream, e.g.

char *line;
while ((line = _chomp(fgetln(stdin, 0)))) {
  printf("%s\n", line);
}
The returned memory is owned by the stream. It'll be reused when fgetln() is called again. It's free()'d upon fclose() / fflush()
@param
struct FILE* stream
specifies non-null open input stream
unsigned long* len
optionally receives byte length of line
@return
char*
nul-terminated line string, including the \n character unless a line happened before EOF without \n, otherwise it returns NULL and feof() and ferror() can examine the state
@see getdelim()

fgetpos

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

fgets

Reads line from stream.

This function is similar to getline() except it'll truncate lines exceeding size. The line ending marker is included and may be removed using _chomp().

@param
char* s
is output buffer
int size
is capacity of s
struct FILE* f
is non-null file object stream pointer
@return
char*
s on success, NULL on error, or NULL if EOF happens when zero characters have been read
@see fgets_unlocked()
@threadsafe

fgets_unlocked

Reads line from stream.

This function is similar to getline() except it'll truncate lines exceeding size. The line ending marker is included and may be removed using _chomp().

@param
char* s
is output buffer
int size
is capacity of s
struct FILE* f
is non-null file object stream pointer
@return
char*
s on success, NULL on error, or NULL if EOF happens when zero characters have been read

fgetwc

Reads UTF-8 character from stream.

@param
struct FILE* f
is non-null file object stream pointer
@return
unsigned int
wide character or -1 on EOF or error
@see fgetwc_unlocked()
@threadsafe

fgetwc_unlocked

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.

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
int* s
is is nul-terminated string that's non-null
int size
is byte length of s
struct FILE* f
is file stream object pointer
@return
int*
@see fgetws()
@threadsafe

fgetws_unlocked

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

This function is similar to getline() except it'll truncate lines exceeding size. The line ending marker is included and may be removed using _chomp().

@param
int* s
is is nul-terminated string that's non-null
int size
is byte length of s
struct FILE* f
is file stream object pointer
@return
int*
@see fgetws()

filecmp

Compares contents of files with memcmp().

@param
const char* pathname1
const 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.

This function is equivalent to:

struct stat st;
return stat(path, &st) != -1;
Please note that things which aren't strictly files, e.g. directories or sockets, could be considered files for the purposes of this function. The stat() function may be used to differentiate them.
@param
const char* path
@return
_Bool

fileno

Returns file descriptor associated with stream.

@param
struct FILE* f
is file stream object pointer
@return
int
fd on success or -1 w/ errno;
@threadsafe

fileno_unlocked

Returns file descriptor associated with stream.

@param
struct FILE* f
is file stream object pointer
@return
int
fd on success or -1 w/ errno;

FindClose

Finds more files in directory.

@param
long hFindFile
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

FindComBinary

Returns path of binary without debug information, or null.

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

FindContentType

Returns Content-Type for file extension.

@param
const char* p
unsigned long n
@return
const char*

FindDebugBinary

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

@return
const char*
path to debug binary, or NULL

FindEmbeddedApe

Returns offset of binary embedded inside binary.

This can be used to load zip assets from an executable that hasn't gone through the objcopy -S -O binary step. We make the assumption that an x86_64-pc-linux-gnu toolchain is being used. This routine would need to be changed to accommodate binaries built locally on Apple, FreeBSD, etc.

@param
const unsigned char* p
needs to be page aligned
unsigned long n
is byte length of p
@return
unsigned char*
base address of image or NULL if not found

FindFirstFile

Finds first file in directory.

@param
const unsigned short* lpFileName
struct NtWin32FindData* out_lpFindFileData
@return
long
@note this wrapper takes care of ABI, STRACE(), and __winerr()

FindNextFile

Finds more files in directory.

@param
long hFindFile
struct NtWin32FindData* out_lpFindFileData
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

finite

Returns nonzero if 𝑥 isn't INFINITY or NAN.

@param
double x
@return
int

finitef

Returns nonzero if 𝑥 isn't INFINITY or NAN.

@param
float x
@return
int

finitel

Returns nonzero if 𝑥 isn't INFINITY or NAN.

@param
long double x
@return
int

_firewall

Checks outbound address against firewall.

The goal is to keep local software local, by raising an error if our Makefile tries to talk to the Internet.

@param
void* addr
unsigned int addrsize
@return
void

FixPath

@param
char* path
@return
void

__fixupnewfd

Applies file descriptor fixups on XNU or old Linux.

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

__fixupnewsockfd

Applies non-atomic file descriptor fixups on XNU or ancient Linux.

@param
int fd
of -1 means no-op
int flags
@return
int

__flbf

Returns nonzero if stream is line buffered.

@param
struct FILE* f
@return
int

flock

Acquires lock on file.

Please note multiple file descriptors means multiple locks.

@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
@restartable

flock2cosmo

@param
unsigned long memory
@return
void

flockfile

Acquires reentrant lock on stdio object, blocking if needed.

@param
struct FILE* f
@return
void

flogf

Writes formatted message w/ timestamp to log.

@param
unsigned int level
const char* file
int line
struct FILE* f
const 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

FlushFileBuffers

Flushes buffers of specified file to disk.

This provides a stronger degree of assurance and blocking for things to be sent to a physical medium, but it's not guaranteed unless your file is opened in a direct non-caching mode. One main advantage here seems to be coherency.

@param
long hFile
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()
@note consider buying a ups
@see FlushViewOfFile()

_flushlbf

Flushes all line-buffered streams.

@return
void

FlushViewOfFile

Syncs memory created by MapViewOfFileEx().

This doesn't wait until the pages are written out to the physical medium. This doesn't update timestamps or file/dir metadata.

@param
void* lpBaseAddress
unsigned long dwNumberOfBytesToFlush
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()
@note consider buying a ups
@see FlushFileBuffers()

fma

@param
double x
double y
double z
@return
double

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
const 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()

__fmt

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)
  • %p pointer (48-bit hexadecimal)
  • %u unsigned
  • %g double (smart formatting)
  • %e double (expo formatting)
  • %f double (ugly formatting)
  • %a double (hex formatting)
  • %Lg long double
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 (64-bit)
  • %jjd int128_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
const char* format
struct __va_list* va
@return
int
@note implementation detail of printf(), snprintf(), etc.
@see printf() for wordier documentation
@note netlib.org is so helpful
@asyncsignalsafe if floating point isn't used
@vforksafe if floating point isn't used

__fmt_stoa

Converts string to array.

This is used by __fmt() to implement the %s and %c directives. The content outputted to the array is always UTF-8, but the input may be UTF-16 or UTF-32.

@param
int(*)() out
void* arg
void* data
unsigned long flags
unsigned long precision
unsigned long width
unsigned char signbit
unsigned char qchar
@return
int
@see __fmt()

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
const char* pat
const char* str
int flags
@return
int
@see glob()

FoldHeader

Collapses repeating headers onto a single line.

@param
struct HttpMessage* msg
char* b
int h
unsigned long* z
@return
char*

fopen

Opens file as stream object.

@param
const char* pathname
is a utf-8 ideally relative filename
const 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
const char* mode
@return
int

fork

Creates new process.

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

FormatBinary64

Converts unsigned 64-bit integer to binary string.

@param
char* p
needs at least 67 bytes
unsigned long x
char z
is 0 for DIGITS, 1 for 0bDIGITS, 2 for 0bDIGITS if ≠0
@return
char*
pointer to nul byte

FormatFlex64

Formats integer using decimal or hexadecimal.

This formats as int64 signed decimal. However it's a:

  1. positive number
  2. with population count of 1
  3. and a magnitude of at least 256
Then we switch to hex notation to make the number more readable.
@param
char* p
long x
char z
@return
char*

FormatHex64

Converts unsigned 64-bit integer to hex string.

@param
char* p
needs at least 19 bytes
unsigned long x
char z
is 0 for DIGITS, 1 for 0xDIGITS, 2 for 0xDIGITS if ≠0
@return
char*
pointer to nul byte

FormatHttpDateTime

Formats HTTP timestamp, e.g.

Sun, 04 Oct 2020 19:50:10 GMT

This function is the same as:

strftime(p, 30, "%a, %d %b %Y %H:%M:%S %Z", tm)
Except this function goes 10x faster:

FormatHttpDateTime  l:        25𝑐         8𝑛𝑠
strftime            l:       709𝑐       229𝑛𝑠
@param
char* p
struct tm* tm
must be zulu see gmtime_r() and nowl()
@return
char*
@see ParseHttpDateTime()

FormatInt32

Converts signed 32-bit integer to string.

@param
char* p
needs at least 12 bytes
int x
@return
char*
pointer to nul byte

FormatInt64

Converts signed 64-bit integer to string.

@param
char* p
needs at least 21 bytes
long x
@return
char*
pointer to nul byte

FormatInt64Thousands

Converts 64-bit integer to string w/ commas.

@param
char* p
needs at least 27 bytes
long x
@return
char*
pointer to nul byte

FormatMemorySize

Represents size of memory readably.

@param
char* p
is output buffer
unsigned long x
@return
char*
pointer to nul byte

FormatOctal32

Converts unsigned 32-bit integer to octal string.

@param
char* p
needs at least 12 bytes
unsigned int x
_Bool z
ensures it starts with zero
@return
char*
pointer to nul byte

FormatOctal64

Converts unsigned 64-bit integer to octal string.

@param
char* p
needs at least 24 bytes
unsigned long x
_Bool z
ensures it starts with zero
@return
char*
pointer to nul byte

FormatUint32

Converts unsigned 32-bit integer to string.

@param
char* p
needs at least 12 bytes
unsigned int x
@return
char*
pointer to nul byte

FormatUint64

Converts unsigned 64-bit integer to string.

@param
char* p
needs at least 21 bytes
unsigned long x
@return
char*
pointer to nul byte

FormatUint64Thousands

Converts unsigned 64-bit integer to string w/ commas.

@param
char* p
needs at least 27 bytes
unsigned long x
@return
char*
pointer to nul byte

__fpending

Returns number of pending output bytes.

@param
struct FILE* f
@return
unsigned long

fprintf

Formats and writes text to stream.

@param
struct FILE* f
const char* fmt
...
@return
int
@see printf() for further documentation

fprintf_unlocked

Formats and writes text to stream.

@param
struct FILE* f
const char* fmt
...
@return
int
@see printf() for further documentation

__fpurge

Discards contents of stream buffer.

@param
struct FILE* f
@return
void

fpurge

Discards contents of stream buffer.

@param
struct FILE* f
@return
int

fputc

Writes byte to stream.

@param
int c
is byte to buffer or write, which is masked
struct FILE* f
@return
int
c as unsigned char if written or -1 w/ errno
@threadsafe

fputc_unlocked

Writes byte to stream.

@param
int c
is byte to buffer or write, which is masked
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
const char* s
is a NUL-terminated string that's non-NULL
struct FILE* f
is an open stream
@return
int
bytes written, or -1 w/ errno
@threadsafe

fputs_unlocked

Writes string to stream.

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

@param
const char* s
is a NUL-terminated string that's non-NULL
struct FILE* f
is an open stream
@return
int
bytes written, or -1 w/ errno

fputwc

Writes wide character to stream.

@param
int wc
has wide character
struct FILE* f
is file object stream pointer
@return
unsigned int
wide character if written or -1 w/ errno
@threadsafe

fputwc_unlocked

Writes wide character to stream.

@param
int wc
has wide character
struct FILE* f
is file object stream pointer
@return
unsigned int
wide character if written or -1 w/ errno

fputws

Writes wide character string to stream.

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

@param
const 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
@threadsafe

fputws_unlocked

Writes wide character string to stream.

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

@param
const 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
@threadsafe

fread_unlocked

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 cause the current program to abort.

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

free_s

@param
void* v
@return
void

freeaddrinfo

Frees addresses returned by getaddrinfo().

@param
struct addrinfo* ai
@return
int
@threadsafe

freedtoa

@param
char* s
@return
void

FreeHostsTxt

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

@param
struct HostsTxt** ht
@return
void

freelocale

@param
struct __locale_struct* l
@return
void

FreeResolvConf

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

@param
struct ResolvConf** rvp
@return
void

_freestack

Frees stack.

@param
void* stk
was allocated by _mapstack()
@return
int

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
const char* pathname
is the file to open or NULL
const char* mode
is the mode string flags, see fopenflags()
struct FILE* stream
is the existing allocated stream memory, which is flushed and closed if already open
@return
struct FILE*
stream object if successful, or NULL w/ errno

frexp

Splits number normalized fraction and exponent.

@param
double x
int* e
@return
double

frexpf

Splits number normalized fraction and exponent.

@param
float x
int* e
@return
float

frexpl

Splits number normalized fraction and exponent.

@param
long double x
int* e
@return
long double

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
const 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
int
@returns 0 on success or -1 on error

fseeko

Repositions open file stream.

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

@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
int
@returns 0 on success or -1 on error
@threadsafe

fseeko_unlocked

Repositions open file stream.

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

@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
int
@returns 0 on success or -1 on error

__fsetlocking

Does nothing and returns FSETLOCKING_INTERNAL.

@param
struct FILE* f
int type
@return
int

fsetpos

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

fstat

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

@param
int fd
struct cosmo* st
@return
int
0 on success or -1 w/ errno
@raise EBADF if fd isn't a valid file descriptor
@raise EIO if an i/o error happens while reading from file system
@raise EOVERFLOW shouldn't be possible on 64-bit systems
@asyncsignalsafe

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
const char* path
struct cosmo* st
is where result is stored
int flags
can have AT_SYMLINK_NOFOLLOW
@return
int
0 on success, or -1 w/ errno
@see S_ISDIR(st.st_mode), S_ISREG()
@asyncsignalsafe
@vforksafe

fsum

Adds doubles in array.

@param
const double* p
unsigned long n
@return
double

fsumf

Adds floats in array.

@param
const float* p
unsigned long n
@return
float

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()
@see __nosync to secretly disable
@asyncsignalsafe

ftell

Returns current position of stream.

@param
struct FILE* f
@return
long
@returns current byte offset from beginning, or -1 w/ errno

ftello

Returns current position of stream.

@param
struct FILE* f
@return
long
@returns current byte offset from beginning, or -1 w/ errno
@threadsafe

ftok

Convert pathname and a project ID to System V IPC key.

@param
const char* path
int id
@return
int

__ftrace

Function tracing enabled state.

After ftrace_install() has been called, the logging of C function calls may be controlled by changing this variable. If __ftrace is greater than zero, functions are logged. Otherwise, they aren't.

By convention, functions wishing to disable function tracing for a short time period should say:

void foo() {
  --__ftrace;
  bar();
  ++__ftrace;
}
This way you still have some flexibility to force function tracing, by setting __ftrace to a higher number like 2 or 200. Even though under normal circumstances, __ftrace should only be either zero or one.
@type
_Atomic int

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.

@return
int
@see libc/runtime/_init.S for documentation


ftracer

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

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

Tries to acquire reentrant stdio object lock.

@param
struct FILE* f
@return
int
0 on success, or non-zero if another thread owns the lock

ftw

Walks file tree.

@param
const char* path
int(*)() fn
int fd_limit
@return
int
@see examples/walk.c for example
@see nftw()

funlockfile

Releases lock on stdio object.

@param
struct FILE* f
@return
void

futimens

Sets atime/mtime on file descriptor.

This function is the same as utimensat(fd, 0, ts, 0).

@param
int fd
ANONYMOUS-STRUCT* ts
is atime/mtime, or null for current time
@return
int
@raise ENOSYS on RHEL5

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
const 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 write
struct FILE* f
@return
unsigned long
count on success, [0,count) on EOF, 0 on error or count==0
@threadsafe

fwrite_unlocked

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 write
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_fds

@type
struct g_fds

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*

gai_strerror

Turns getaddrinfo() return code into string.

@param
int code
@return
const 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

_gc

Frees memory when function returns.

This garbage collector overwrites the return address on the stack so that the RET instruction calls a trampoline which calls free(). It's loosely analogous to Go's defer keyword rather than a true cycle gc.

const char *s = _gc(strdup("hello"));
puts(s);
This macro is equivalent to:

 _defer(free, ptr)
@param
void* thing
@return
void*
@warning do not return a gc()'d pointer
@warning do not realloc() with gc()'d pointer
@warning be careful about static keyword due to impact of inlining
@note you should use -fno-omit-frame-pointer

_gclongjmp

Jumps up stack to previous setjmp() invocation.

This is the same as longjmp() but also unwinds the stack to free memory, etc. that was registered using gc() or defer(). If GC isn't linked, this behaves the same as longjmp().

@param
rdi
points to the jmp_buf which must be the same stack
esi
is returned by setjmp() invocation (coerced nonzero)
@noreturn
@assume system five nexgen32e abi conformant
@see examples/ctrlc.c

gcvt

@param
double x
int n
char* b
@return
char*

gdbexec

Attaches GDB temporarily, to do something like print a variable.

@param
const 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*

GenerateConsoleCtrlEvent

Sends signal to process group that shares console w/ calling process.

@param
unsigned int dwCtrlEvent
can be kNtCtrlCEvent or kNtCtrlBreakEvent
unsigned int dwProcessGroupId
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

get_current_dir_name

Returns current working directory.

If the PWD environment variable is set, and it seems legit, then that'll be returned.

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

__get_symbol

Returns low index into symbol table for address.

@param
struct SymbolTable* t
if null will be auto-populated only if already open
long a
@return
int
index or -1 if nothing found

__get_symbol_by_addr

Returns name of symbol at address.

@param
long addr
@return
char*

__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*

GetAddr2linePath

@return
const char*

getaddrinfo

Resolves address for internet name.

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

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
auxiliary value or 0 if at not found
@see libc/sysv/consts.sh
@see System Five Application Binary Interface § 3.4.3
@error ENOENT when value not found
@asyncsignalsafe

_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
is AT_... search key
@return
struct AuxiliaryValue
true if value was found
@see libc/sysv/consts.sh
@see System Five Application Binary Interface § 3.4.3
@error ENOENT when value not found
@asyncsignalsafe

getc

Reads byte from stream.

@param
struct FILE* f
@return
int
byte in range 0..255, or -1 w/ errno
@threadsafe

getc_unlocked

Reads byte from stream.

@param
struct FILE* f
@return
int
byte in range 0..255, or -1 w/ errno

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

GetCallerName

Returns name of function that called caller function.

@param
struct StackFrame* bp
@return
const char*

getchar

Reads byte from stdin.

@return
int
byte in range 0..255, or -1 w/ errno
@htreadsafe

getchar_unlocked

Reads byte from stdin.

@return
int
byte in range 0..255, or -1 w/ errno

getcontext

Gets machine state.

@return
@note please use longerjmp() and setlongerjmp() for fibers
@note currently only gets general registers
@see setcontext()

GetCpuCount

Returns number of CPUs in system.

On Intel systems with HyperThreading this will return the number of cores multiplied by two.

@return
unsigned int
cpu count or 0 if it couldn't be determined

getcwd

Returns current working directory, e.g.

const char *dirname = gc(getcwd(0,0)); // if malloc is linked
const char *dirname = getcwd(alloca(PATH_MAX),PATH_MAX);
@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+1, which may be 0 if buf is NULL
@return
char*
buf containing system-normative path or NULL w/ errno
@error ERANGE, EINVAL, ENOMEM

getdelim

Reads string from stream, e.g.

char *line = NULL;
size_t linesize = 0;
while (getdelim(&line, &linesize, '\n', stdin) > 0) {
  _chomp(line);
  printf("%s\n", line);
}
free(line);
@param
char** s
is the caller's buffer (in/out) which is extended or allocated automatically, also NUL-terminated is guaranteed
unsigned long* n
is the capacity of s (in/out)
int delim
is the stop char (and NUL is implicitly too)
struct FILE* f
@return
long
number of bytes read >0, including delim, excluding NUL, or -1 w/ errno on EOF or error; see ferror() and feof()
@note this function will ignore EINTR if it occurs mid-line
@raises EBADF if stream isn't open for reading
@see fgetln(), getline(), _chomp(), gettok_r()

getdelim_unlocked

Reads string from unlocked stream.

@param
char** s
unsigned long* n
int delim
struct FILE* f
@return
long
@see getdelim() for documentation

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
const 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
const 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

getegid

Returns effective group ID of calling process.

@return
int
group id

GetElfDynStringTable

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

GetElfDynSymbolTable

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

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
const 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
const char* strtab
unsigned int rva
@return
char*

GetElfStringTable

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

GetElfStrs

@param
struct Elf64_Ehdr* elf
unsigned long mapsize
unsigned long* out_size
@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
const char* s
@return
char*
@note should not be used after __cxa_finalize() is called

geteuid

Returns effective user ID of calling process.

@return
int
user id

GetExitCodeProcess

Obtains exit code for process.

@param
long hProcess
unsigned int* lpExitCode
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

GetFileAttributes

Gets file info on the New Technology.

@param
const unsigned short* lpPathName
@return
unsigned int
handle, or -1u on failure
@note this wrapper takes care of ABI, STRACE(), and __winerr()

getfiledescriptorsize

Determines size of open file.

This function is equivalent to:

struct stat st;
!fstat(fd, &st) ? st.st_size : -1
Except faster on BSD/Windows and a much smaller link size.
@param
int fd
@return
long
file byte length, or -1 w/ errno
@asyncsignalsafe

GetFileSize

Returns the byte length of file by path.

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

GetGdbPath

@return
const 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.

@return
int
@asyncsignalsafe
@vforksafe

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
const char* name
@return
struct gr*

getgrnam_r

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

getgrouplist

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

gethostbyaddr

@param
void* s_addr
unsigned int len
int type
@return
struct he1*

gethostbyname

@param
const char* name
@return
struct he0*

gethostent

@return
struct hostent*

GetHostIps

Returns IP addresses of system.

Normally return values will look like {0x7f000001, 0x0a0a0a7c, 0} which means the same thing as {"127.0.0.1", "10.10.10.124", 0}. Returned IPs will IPv4 anycast addresses bound to network interfaces which come in a NULL-terminated array with no particular ordering.

uint32_t *ip, *ips = GetIps();
for (ip = ips; *ip; ++ip) {
  printf("%hhu.%hhu.%hhu.%hhu\n", *ip >> 24, *ip >> 16, *ip >> 8, *ip);
}
This function supports Windows, Linux, XNU, FreeBSD, NetBSD, OpenBSD.
@return
unsigned int*
null-terminated ip array on success, or null w/ errno

gethostname

Returns name of host system, e.g.

pheidippides.domain.example
^^^^^^^^^^^^
@param
char* name
unsigned long len
@return
int
0 on success or -1 w/ errno

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
int kind
@return
int

GetHostsTxt

Returns hosts.txt map.

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

GetHttpHeader

Returns small number for HTTP header, or -1 if not found.

@param
const char* str
unsigned long len
@return
int

GetHttpHeaderName

@param
int h
@return
const char*

GetHttpMethod

Converts HTTP method string into internal index

@param
const char* str
unsigned long len
if -1 implies strlen
@return
int
small number for HTTP method, or 0 if not found.

GetHttpReason

Returns string describing HTTP reason phrase.

@param
int code
@return
const char*
@see https://tools.ietf.org/html/rfc2616
@see https://tools.ietf.org/html/rfc6585

GetInstructionLengths

Returns lengths of x86 ops in binary.

The first decoded instruction is at _ereal. Lengths can be 1 to 15 bytes. Each byte in the return value is in that range, and the array is NUL terminated. The returned memory is memoized, since this costs some time. For example, for a 10mb Python binary, it takes 20 millis so the basic idea is is you can use this output multiple times which is a faster way to iterate over the binary than calling Xed.

@return
unsigned char*
nul-terminated length array on success, or null

GetInterpreterExecutableName

Returns path of executable interpreter.

Unlike program_executable_name which is designed to figure out the absolute path of the first argument passed to execve(), what we do here is probe things like /proc and sysctl() to figure out if we were launched by something like ape-loader, and then we return its path. If we can't determine that path, possibly because we're on XNU or OpenBSD, then we return -1 with an error code.

@param
char* p
receives utf8 output
unsigned long n
is byte size of res buffer
@return
char*
p on success or null w/ errno if out of buf or error
@see program_invocation_short_name
@see program_invocation_name
@see program_executable_name

GetIpCategoryName

Describes IP address.

@param
int c
@return
const char*
@see CategorizeIp()

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, e.g.

char *line = NULL;
size_t linesize = 0;
while (getline(&line, &linesize, stdin) > 0) {
  _chomp(line);
  printf("%s\n", line);
}
free(line);
This function delegates to getdelim(), which provides further documentation. Concerning lines, please note the \n or \r\n are included in results, and can be removed with _chomp().
@param
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 fgetln(), xgetline(), getdelim(), gettok_r()

getloadavg

Returns system load average.

@param
double* a
should be array of 3 doubles
int n
should be 3
@return
int
number of items placed in a or -1 w/ errno
@raise ENOSYS on metal

GetMagnumStr

@param
struct MagnumStr* ms
int x
@return
char*

GetMaxFd

Returns maximum number of open files.

@return
long

GetMemtrackSize

@param
struct _mmi* mm
@return
unsigned long

getnameinfo

Resolves name/service for socket address.

@param
struct sockaddr* addr
unsigned int addrlen
char* name
unsigned int namelen
char* service
unsigned int servicelen
int flags
@return
int
0 on success or EAI_xxx value

getnetbyaddr

@param
unsigned int net
int type
@return
struct netent*

getnetbyname

@param
const char* name
@return
struct netent*

getnetent

@return
struct netent*

GetNtBaseSocket

@param
long socket
@return
long

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

GetNtOpenFlags

@param
int flags
int mode
unsigned int* out_perm
unsigned int* out_share
unsigned int* out_disp
unsigned int* out_attr
@return
int

GetNtProtocolsTxtPath

@param
char* pathbuf
unsigned int size
@return
char*

GetNtServicesTxtPath

@param
char* pathbuf
unsigned int size
@return
char*

__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
const char* ostr
@return
int
@see optind
@see optarg

getpeername

Returns details about remote end of connected socket.

@param
int fd
void* out_addr
unsigned int* out_addrsize
@return
int
0 on success or -1 w/ errno
@see getsockname()

getpgid

Returns process group id.

@param
int pid
@return
int

getpgrp

Returns process group id of calling process.

@return
int

getpid

Returns process id.

This function does not need to issue a system call. The PID is tracked by a global variable which is updated atfork(). The only exception is when the process is vfork()'d in which case a system call shall be issued.

On Linux, and only Linux, the process id is guaranteed to be the same as gettid() for the main thread.

@return
int
@asyncsignalsafe
@threadsafe
@vforksafe

getppid

Returns parent process id.

@return
int
@asyncsignalsafe

getpriority

Returns nice value of thing.

Since -1 might be a valid return value for this API, it's necessary to clear errno beforehand and see if it changed, in order to truly determine if an error happened.

@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
const char* module
const char* symbol
@return
void*

GetProgramExecutableName

Returns absolute path of program.

@return
char*

getprotobyname

@param
const char* name
@return
struct pe0*

getprotobynumber

@param
int proto
@return
struct pe1*

getprotoent

@return
struct protoent*

getpwent

@return
struct pw*

getpwnam

@param
const char* name
@return
struct pw*

getpwnam_r

@param
const 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 cryptographic random data.

This random number seed generator obtains information from:

  • getrandom() on Linux
  • RtlGenRandom() on Windows
  • getentropy() on XNU and OpenBSD
  • sysctl(KERN_ARND) on FreeBSD and NetBSD
The following flags may be specified:

  • GRND_RANDOM: Halt the entire system while I tap an entropy pool so small that it's hard to use statistics to test if it's random
  • GRND_NONBLOCK: Do not wait for i/o events or me to jiggle my mouse, and instead return immediately the moment data isn't available, even if the result needs to be -1 w/ EAGAIN
This function is safe to use with fork() and vfork(). It will also close any file descriptor it ends up needing before it returns.
@param
void* p
unsigned long n
unsigned int f
@return
long
@note this function could block a nontrivial time on old computers
@note this function is indeed intended for cryptography
@note this function takes around 900 cycles
@asyncsignalsafe
@restartable
@vforksafe

getresgid

Gets real, effective, and "saved" group ids.

@param
unsigned int* real
receives real user id, or null to do nothing
unsigned int* effective
receives effective user id, or null to do nothing
unsigned int* saved
receives saved user id, or null to do nothing
@return
int
0 on success or -1 w/ errno
@see setresuid()

GetResolvConf

Returns singleton with DNS server address.

@return
struct ResolvConf*
@threadsafe

GetResourceLimit

@param
int resource
@return
long

getresuid

Gets real, effective, and "saved" user ids.

@param
unsigned int* real
receives real user id, or null to do nothing
unsigned int* effective
receives effective user id, or null to do nothing
unsigned int* saved
receives saved user id, or null to do nothing
@return
int
0 on success or -1 w/ errno
@see setresuid()

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*

getservbyname

@param
const char* name
const char* proto
@return
struct se0*

getservbyport

@param
int port
const char* proto
@return
struct se1*

getservent

@return
struct servent*

GetSiCodeName

Returns symbolic name for siginfo::si_code value.

@param
int sig
int si_code
@return
const char*

getsid

Creates session and sets the process group id.

@param
int pid
@return
int

getsockname

Returns details about network interface kernel granted socket.

@param
int fd
void* out_addr
unsigned int* out_addrsize
@return
int
0 on success or -1 w/ errno
@see getpeername()

getsockopt

Retrieves socket setting.

@param
int fd
int level
can be SOL_SOCKET, IPPROTO_TCP, etc.
int optname
can be SO_{REUSE{PORT,ADDR},KEEPALIVE,etc.} etc.
void* out_opt_optval
unsigned int* out_optlen
@return
int
0 on success, or -1 w/ errno
@error ENOPROTOOPT for unknown (level,optname)
@error EINVAL if out_optlen is invalid somehow
@error ENOTSOCK if fd is valid but not a socket
@error EBADF if fd isn't valid
@error EFAULT if optval memory isn't valid
@see libc/sysv/consts.sh for tuning catalogue
@see setsockopt()

GetSymbolTable

Returns symbol table singleton.

This uses multiple strategies to find the symbol table. The first strategy, depends on whether or not the following is linked:

STATIC_YOINK("__zipos_get");
In that case, the symbol table may be read from /zip/.symtab which is generated by o//tool/build/symtab.com. The second strategy is to look for the concomitant .com.dbg executable, which may very well be the one currently executing, or it could be placed in the same folder as your .com binary, or lastly, it could be explicitly specified via the COMDBG environment variable.

Function tracing is disabled throughout the duration of this call. Backtraces and other core runtime functionality depend on this.

@return
struct SymbolTable*
symbol table, or NULL if not found

GetTempPathA_flunk

Calls GetTempPathA() w/ different API.

@return
@see GetSystemDirectoryA(), GetWindowsDirectoryA()

gettid

Returns current thread id.

On Linux, and Linux only, this is guaranteed to be equal to getpid() if this is the main thread. On NetBSD, gettid() for the main thread is always 1.

This function issues a system call. That stops being the case as soon as __install_tls() is called. That'll happen automatically, when you call clone() and provide the TLS parameter. We assume that when a TLS block exists, then

*(int *)(__get_tls() + 0x38)
will contain the thread id. Therefore when issuing clone() calls, the CLONE_CHILD_SETTID and CLONE_CHILD_CLEARTID flags should use that index as its ctid memory.

gettid (single threaded) l:       126𝑐        41𝑛𝑠
gettid (tls enabled)     l:         2𝑐         1𝑛𝑠
The TLS convention is important for reentrant lock performance.
@return
int
thread id greater than zero or -1 w/ errno
@asyncsignalsafe
@threadsafe
@vforksafe

gettimeofday

Returns system wall time in microseconds, e.g.

int64_t t;
char p[30];
struct tm tm;
struct timeval tv;
gettimeofday(&tv, 0);
t = tv.tv_sec;
gmtime_r(&t, &tm);
FormatHttpDateTime(p, &tm);
printf("%s\n", p);
@param
struct ru_stime* tv
points to timeval that receives result if non-NULL
struct timezone* tz
receives UTC timezone if non-NULL
@return
int
@error EFAULT if tv or tz isn't valid memory
@see clock_gettime() for nanosecond precision
@see strftime() for string formatting

__gettimeofday_get

Returns pointer to fastest gettimeofday().

@param
_Bool* opt_out_isfast
@return
struct ad(*)()

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.

@return
int
@asyncsignalsafe
@vforksafe

getutf16

Decodes UTF-16 character.

@param
const 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

getwc

Reads UTF-8 character from stream.

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

getwc_unlocked

Reads UTF-8 character from stream.

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

getwchar

Reads UTF-8 character from stream.

@return
unsigned int
wide character or -1 on EOF or error
@threadsafe

getwchar_unlocked

Reads UTF-8 character from stream.

@return
unsigned int
wide character or -1 on EOF or error

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

GetZipCdirComment

Returns comment of zip central directory.

@param
const unsigned char* eocd
@return
void*

GetZipCdirCommentSize

Returns comment of zip central directory.

@param
const unsigned char* eocd
@return
unsigned long

GetZipCdirOffset

Returns offset of zip central directory.

@param
const unsigned char* eocd
@return
unsigned long

GetZipCdirRecords

Returns number of records in zip central directory.

@param
const unsigned char* eocd
@return
unsigned long

GetZipCdirSize

Returns size of zip central directory.

@param
const unsigned char* eocd
@return
unsigned long

GetZipCfileCompressedSize

Returns compressed size in bytes from zip central directory header.

@param
const unsigned char* z
@return
unsigned long

GetZipCfileMode

Returns st_mode from ZIP central directory record.

@param
const unsigned char* p
@return
int

GetZipCfileOffset

Returns offset of local file header.

@param
const unsigned char* z
@return
unsigned long

GetZipCfileTimestamps

Extracts modified/access/creation timestamps from zip entry.

@param
const unsigned char* cf
is pointer to central directory header for file
ANONYMOUS-STRUCT* mtim
optionally receives last modified timestamp
ANONYMOUS-STRUCT* atim
optionally receives modified timestamp
ANONYMOUS-STRUCT* ctim
optionally receives creation timestamp
int gmtoff
is seconds adjustment for legacy dos timestamps
@return
void

GetZipCfileUncompressedSize

Returns uncompressed size in bytes from zip central directory header.

@param
const unsigned char* z
@return
unsigned long

GetZipLfileCompressedSize

Returns compressed size in bytes from zip local file header.

@param
const unsigned char* z
@return
unsigned long

GetZipLfileUncompressedSize

Returns uncompressed size in bytes from zip local file header.

@param
const unsigned char* z
@return
unsigned long

glob

Finds pathnames matching pattern.

For example:

glob_t g = {.gl_offs = 2};
glob("*.*", GLOB_DOOFFS, NULL, &g);
glob("../.*", GLOB_DOOFFS | GLOB_APPEND, NULL, &g);
g.gl_pathv[0] = "ls";
g.gl_pathv[1] = "-l";
execvp("ls", &g.gl_pathv[0]);
globfree(g);
@param
const 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
const long* timep
@return
struct alttm*

gmtime_r

@param
const long* timep
struct alttm* tmp
@return
struct alttm*

GoodSocket

Returns new socket with modern goodness enabled.

@param
int family
int type
int protocol
_Bool isserver
ANONYMOUS-STRUCT* timeout
@return
int

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
const char*

gzflush

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

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

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

@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

h_errno

Error number global for gethostbyname*(), gethostbyaddr*(), etc.

@type
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

HasControlCodes

Returns true if C0 or C1 control codes are present

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
int f
can have kControlWs, kControlC0, kControlC1 to forbid
@return
long
index of first forbidden character or -1
@see VisualizeControlCodes()

HeaderHas

Returns true if standard header has substring.

@param
struct HttpMessage* m
is message parsed by ParseHttpMessage
const char* b
is buffer that ParseHttpMessage parsed
int h
is known header, e.g. kHttpAcceptEncoding
const char* s
should not contain comma
unsigned long n
is byte length of s where -1 implies strlen
@return
_Bool
true if substring present

herror

Prints h_errno description to stderr.

@param
const char* s
@return
void
@see perror()

hextoint

Converts ASCII hexadecimal character to integer case-insensitively.

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

HighwayHash64

Computes Highway Hash.

highwayhash64 n=0                  121 nanoseconds
highwayhash64 n=8                   16 ns/byte         59,865 kb/s
highwayhash64 n=31                   4 ns/byte            222 mb/s
highwayhash64 n=32                   3 ns/byte            248 mb/s
highwayhash64 n=63                   2 ns/byte            387 mb/s
highwayhash64 n=64                   2 ns/byte            422 mb/s
highwayhash64 n=128                  1 ns/byte            644 mb/s
highwayhash64 n=256                  1 ns/byte            875 mb/s
highwayhash64 n=22851              721 ps/byte          1,354 mb/s
@param
void* data
unsigned long size
const 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
int
@see ape/ape.lds

__hostos

Teleports code fragment inside _init().

@type
const int

hstrerror

Turns h_errno value into string.

@param
int err
@return
const char*

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

i128abs

@param
__int128 x
@return
__int128

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
const char* to
const 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
long x
@return
long

IndentLines

Inserts spaces before lines.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
unsigned long j
is number of spaces to use
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

index

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

@param
const 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
const char* s
unsigned int i
@return
const char*

inet_addr

Converts dotted IPv4 address string to network order binary.

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

inet_aton

Converts dotted IPv4 address string to network order binary.

@param
const 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 or AF_INET6
void* src
is the binary-encoded address, e.g. &addr->sin_addr
char* dst
is the output string buffer
unsigned int size
needs to be 16+ for IPv4 and 72+ for IPv6
@return
const char*
dst on success or NULL w/ errno

inet_pton

Converts internet address string to binary.

@param
int af
can be AF_INET
const char* src
is the ASCII-encoded address
void* dst
is where the binary-encoded net-order address goes
@return
int
1 on success, 0 on src malformed, or -1 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

Decompresses raw deflate data.

This uses puff by default since it has a 2kb footprint. If zlib proper is linked, then we favor that instead, since it's faster.

@param
void* out
unsigned long outsize
needs to be known ahead of time by some other means
void* in
unsigned long insize
@return
int
0 on success or nonzero on failure

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

InitHttpMessage

Initializes HTTP message parser.

@param
struct HttpMessage* r
int type
@return
void


initstate

@param
unsigned int seed
char* state
unsigned long size
@return
char*

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

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
...
@return
int
@restartable
@vforksafe

ioctl_default

@param
int fd
unsigned long request
...
@return
int

ioctl_fioclex

Sets "close on exec" on file descriptor the fast way.

@param
int fd
int req
@return
int
@see ioctl(fd, FIOCLEX, 0) dispatches here

ioctl_siocgifaddr

@param
int fd
...
@return
int

ioctl_siocgifaddr_nt

Returns unicast addresses.

@param
int fd
struct ifreq* ifr
@return
int

ioctl_siocgifbrdaddr

@param
int fd
...
@return
int

ioctl_siocgifbrdaddr_nt

Returns broadcast address.

@param
int fd
struct ifreq* ifr
@return
int

ioctl_siocgifconf

Returns information about network interfaces.

@param
int fd
...
@return
int
@see ioctl(fd, SIOCGIFCONF, tio) dispatches here

ioctl_siocgifconf_nt

@param
int fd
struct ifconf* ifc
@return
int

ioctl_siocgifdstaddr

@param
int fd
...
@return
int

ioctl_siocgifflags

@param
int fd
...
@return
int

ioctl_siocgifflags_nt

@param
int fd
struct ifreq* ifr
@return
int

ioctl_siocgifnetmask

@param
int fd
...
@return
int

ioctl_siocgifnetmask_nt

@param
int fd
struct ifreq* ifr
@return
int

ioctl_tcgets

Returns information about terminal.

@param
int fd
...
@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
...
@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
...
@return
int
@see ioctl(fd, TIOCGWINSZ, ws) dispatches here

ioctl_tiocgwinsz_nt

@param
struct Fd* fd
struct winsize* ws
@return
int

ioctl_tiocswinsz

Sets width and height of terminal.

@param
int fd
...
@return
int
@see ioctl(fd, TIOCSWINSZ, ws) dispatches here

ioctl_tiocswinsz_nt

@param
int fd
struct winsize* ws
@return
int

__iovec2nt

Converts I/O vector from System Five to WIN32 ABI.

@param
struct ProviderSpecific* iovnt
struct iovec* iov
unsigned long iovlen
@return
unsigned long
effective iovlen
@see IOV_MAX

_isabspath

Returns true if pathname is considered absolute.

  • /home/jart/foo.txt is absolute
  • C:/Users/jart/foo.txt is absolute on Windows
  • C:\Users\jart\foo.txt is absolute on Windows
  • \??\C:\Users\jart\foo.txt is absolute on Windows
  • \\.\C:\Users\jart\foo.txt is absolute on Windows
  • /Users/jart/foo.txt is effectively absolute on Windows
  • \Users\jart\foo.txt is effectively absolute on Windows
@param
const char* path
@return
_Bool

IsAcceptableHost

Returns true if host seems legit.

This function may be called after ParseUrl() or ParseHost() has already handled things like percent encoding. There's currently no support for IPv6 and IPv7.

Here's examples of permitted inputs:

  • ""
  • 1.2.3.4
  • 1.2.3.4.arpa
  • localservice
  • hello.example
  • _hello.example
  • -hello.example
  • hi-there.example
Here's some examples of forbidden inputs:

  • ::1
  • 1.2.3
  • 1.2.3.4.5
  • .hi.example
  • hi..example
@param
const char* s
unsigned long n
if -1 implies strlen
@return
_Bool

IsAcceptablePath

Returns true if path seems legit.

  1. The substring "//" is disallowed.
  2. We won't serve hidden files (segment starts with '.'). The only exception is /.well-known/.
  3. We won't serve paths with segments equal to "." or "..".
It is assumed that the URI parser already took care of percent escape decoding as well as ISO-8859-1 decoding. The input needs to be a UTF-8 string. This function takes overlong encodings into consideration, so you don't need to call Underlong() beforehand.
@param
const char* data
unsigned long size
if -1 implies strlen
@return
_Bool
@see IsReasonablePath()

IsAcceptablePort

Returns true if port seems legit.

Here's examples of permitted inputs:

  • ""
  • 0
  • 65535
Here's some examples of forbidden inputs:

  • -1
  • 65536
  • https
@param
const char* s
unsigned long n
if -1 implies strlen
@return
_Bool

IsAfrinicIp

Returns true if IPv4 address is managed by AFRINIC.

@param
unsigned int x
@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

IsAnonymousIp

Returns true if IPv4 address is anonymous proxy provider.

@param
unsigned int x
@return
_Bool

IsApnicIp

Returns true if IPv4 address is managed by APNIC.

@param
unsigned int x
@return
_Bool

IsArinIp

Returns true if IPv4 address is managed by ARIN.

@param
unsigned int x
@return
_Bool

isascii

Returns nonzero if c is ascii.

@param
int c
@return
int

IsAtLeastWindows10

Returns true if we're running at least Windows 10.

This function may only be called if IsWindows() is true.

@return
_Bool

isatty

Tells if file descriptor is a terminal.

@param
int fd
is file descriptor
@return
int
1 if is terminal, otherwise 0 w/ errno
@raise EBADF if fd isn't a valid file descriptor
@raise ENOTTY if fd is something other than a terminal
@raise EPERM if pledge() was used without tty

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.

This function is equivalent to:

struct stat st;
return stat(path, &st) != -1 && S_ISCHR(st.st_mode);
Except faster and with fewer dependencies.
@param
int fd
@return
int
@see isregularfile(), isdirectory(), issymlink(), fileexists()

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

isdigit_l

@param
int c
struct __locale_struct* l
@return
int

isdirectory

Returns true if file exists and is a directory.

This function is equivalent to:

struct stat st;
return fstatat(AT_FDCWD, path, &st, AT_SYMLINK_NOFOLLOW) != -1 &&
       S_ISDIR(st.st_mode);
Except faster, with fewer dependencies, and less errno clobbering.
@param
const char* path
@return
_Bool
@see isregularfile(), issymlink(), ischardev()

isdirectory_nt

Returns true if file exists and is a directory on Windows NT.

@param
const char* path
@return
_Bool

_isdirsep

Returns true if character is directory separator slash.

@param
int c
@return
_Bool

IsDodIp

Returns true if IP is owned by the U.S. Department of Defense.

@param
unsigned int x
@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
const char* path
@return
_Bool
@see access(exe, X_OK) which is more accurate on NT
@asyncsignalsafe
@vforksafe

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)

IsLacnicIp

Returns true if IPv4 address is managed by LACNIC.

@param
unsigned int x
@return
_Bool

IsLoopbackIp

Returns true if IPv4 address is used for localhost.

@param
unsigned int x
@return
_Bool

islower

Returns nonzero if c is lowercase alpha ascii character.

@param
int c
@return
int

islower_l

@param
int c
struct __locale_struct* l
@return
int

IsMemtracked

@param
int x
int y
@return
_Bool

IsMimeType

Returns true if content-type 𝑡 has mime-type 𝑠.

@param
const char* t
unsigned long n
const char* s
@return
_Bool

IsMulticastIp

Returns true if IPv4 address is used for multicast.

@param
unsigned int x
@return
_Bool

iso8601

Converts timestamp to ISO-8601 formatted string.

@param
char* p
struct tm* tm
@return
char*

isprint

Returns nonzero if c is printable ascii including space.

@param
int c
@return
int

IsPrivateIp

Returns true if IPv4 address is intended for private networks.

@param
unsigned int x
@return
_Bool

IsPublicIp

Returns true if IPv4 address is Globally Reachable.

We intentionally omit TEST-NET here which can be used to simulate public Internet traffic using non-Internet IPs.

@param
unsigned int x
@return
_Bool
true 92.4499% of the time
@see IANA IPv4 Special-Purpose Address Registry

ispunct

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

@param
int c
@return
int

IsReasonablePath

Returns true if path doesn't contain "." or ".." segments.

@param
const char* data
unsigned long size
if -1 implies strlen
@return
_Bool
@see IsAcceptablePath()

isregularfile

Returns true if file exists and is a regular file.

This function is equivalent to:

return fstatat(AT_FDCWD, path, &st, AT_SYMLINK_NOFOLLOW) != -1 &&
       S_ISREG(st.st_mode);
Except faster, with fewer dependencies, and less errno clobbering.
@param
const char* path
@return
_Bool
@see isdirectory(), ischardev(), issymlink()

isregularfile_nt

Returns true if file exists and is a regular file on Windows NT.

@param
const char* path
@return
_Bool

IsRipeIp

Returns true if IPv4 address is managed by RIPE NCC.

@param
unsigned int x
@return
_Bool

IsRunningUnderMake

Returns true if current process was spawned by GNU Make.

@return
_Bool

issetugid

Determines if process is tainted.

This function returns 1 if process was launched as a result of an execve() call on a binary that had the setuid or setgid bits set. FreeBSD defines tainted as including processes that changed their effective user / group ids at some point.

@return
int
always successful, 1 if yes, 0 if no

isspace

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

@param
int c
@return
int
@see isblank()



IsTestnetIp

Returns true if IPv4 address is intended for documentation.

@param
unsigned int x
@return
_Bool
@see RFC5737

_istext

Returns true if buffer is most likely plaintext.

@param
void* data
unsigned long size
@return
_Bool

isupper

Returns nonzero if c is uppercase alpha ascii character.

@param
int c
@return
int

isupper_l

@param
int c
struct __locale_struct* l
@return
int

IsValidCookieValue

Returns true if string is a valid cookie value (any ASCII excluding control char, whitespace, double quotes, comma, semicolon, and backslash).

@param
const char* s
unsigned long n
if -1 implies strlen
@return
_Bool

IsValidHttpToken

Returns true if string is ASCII without delimiters.

@param
const char* s
unsigned long n
if -1 implies strlen
@return
_Bool

iswalnum

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

@param
unsigned int c
@return
int

iswalpha

Returns nonzero if c is alphabetical.

@param
unsigned int c
@return
int

iswalpha_l

@param
unsigned int c
struct __locale_struct* l
@return
int

iswblank

Returns nonzero if c is space or tab.

@param
unsigned int c
@return
int

iswblank_l

@param
unsigned int c
struct __locale_struct* l
@return
int

iswcntrl

Returns nonzero if c is C0 or C1 control code.

@param
unsigned int c
@return
int

iswcntrl_l

@param
unsigned int c
struct __locale_struct* l
@return
int

iswctype

Returns nonzero if c has property.

@param
unsigned int c
unsigned int t
is number returned by wctype
@return
int

iswdigit

Returns nonzero if c is decimal digit.

@param
unsigned int c
@return
int

iswdigit_l

@param
unsigned int c
struct __locale_struct* l
@return
int

iswgraph

Returns nonzero if c is printable and not a space.

@param
unsigned int c
@return
int

iswlower

Returns nonzero if c is lowercase letter.

@param
unsigned int c
@return
int

iswlower_l

@param
unsigned int c
struct __locale_struct* l
@return
int

__isworker

Indicates if current execution context is a worker task.

Setting this to true on things like the forked process of a web server is a good idea since it'll ask the C runtime to not pull magical stunts like attaching GDB to the process on crash.

@type
_Bool

iswprint

Returns nonzero if c is printable.

@param
unsigned int c
@return
int

iswprint_l

@param
unsigned int c
struct __locale_struct* l
@return
int

iswpunct

Returns nonzero if c is punctuation mark.

@param
unsigned int c
@return
int

iswpunct_l

@param
unsigned int c
struct __locale_struct* l
@return
int

iswseparator

Returns nonzero if 𝑐 isn't alphanumeric.

Line reading interfaces generally define this operation as UNICODE characters that aren't in the letter category (Lu, Ll, Lt, Lm, Lo) and aren't in the number categorie (Nd, Nl, No). We also add a few other things like blocks and emoji (So).

@param
unsigned int c
@return
int

iswspace

Returns nonzero if c is space character.

We define this as invisible characters which move the cursor. That means \t\r\n\f\v and unicodes whose category begins with Z but not ogham since it's not invisible and non-breaking spaces neither since they're not invisible to emacs users.

@param
unsigned int c
@return
int

iswspace_l

@param
unsigned int c
struct __locale_struct* l
@return
int

iswupper

Returns nonzero if c is uppercase letter.

@param
unsigned int c
@return
int

iswupper_l

@param
unsigned int c
struct __locale_struct* l
@return
int

iswxdigit

Returns nonzero if c is ascii hex digit.

@param
unsigned int c
@return
int

iswxdigit_l

@param
unsigned int c
struct __locale_struct* l
@return
int

isxdigit

Returns true if c is hexadecimal digit.

@param
int c
@return
int

isxdigit_l

@param
int c
struct __locale_struct* l
@return
int

IsZipCdir32

Returns true if zip end of central directory header seems legit.

@param
const unsigned char* p
unsigned long n
unsigned long i
@return
_Bool

IsZipCdir64

Returns true if zip64 end of central directory header seems legit.

@param
const unsigned char* p
unsigned long n
unsigned long i
@return
_Bool

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

_join

Waits for thread created by _spawn() to terminate.

This will free your thread's stack and tls memory too.

@param
struct ths* th
@return
int

_joinpaths

Joins paths, e.g.

0    + 0    → 0
""   + ""   → ""
"a"  + 0    → "a"
"a"  + ""   → "a/"
0    + "b"  → "b"
""   + "b"  → "b"
"."  + "b"  → "./b"
"b"  + "."  → "b/."
"a"  + "b"  → "a/b"
"a/" + "b"  → "a/b"
"a"  + "b/" → "a/b/"
"a"  + "/b" → "/b"
@param
char* buf
unsigned long size
const char* path
const char* other
@return
char*
joined path, which may be buf, path, or other, or null if (1) buf didn't have enough space, or (2) both path and other were null

kappendf

Appends formatted string to buffer w/ kprintf, e.g.

char *b = 0;
kappendf(&b, "hello %d\n", 123);
free(b);
@param
char** b
const char* fmt
...
@return
long
bytes appended or -1 if ENOMEM
@see appendz(b).i to get buffer length
@note O(1) amortized buffer growth
@see kprintf()

kConsoleHandles

@type
const char[3]

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

Globally precomputed CPUID.

This module lets us check CPUID in 0.06ns rather than 51.00ns. If every piece of native software linked this module, then the world would be a much better place; since all the alternatives are quite toilsome.

@return
@see www.felixcloutier.com/x86/cpuid

kCrashSigs

@type
int[8]

kDos2Errno

data structure for __dos2errno()

@return

kHexToInt

@type
const char[256]

kHttpMethod

@type
const char[8][18]

kHttpRepeatable

Set of standard comma-separate HTTP headers that may span lines.

These headers may specified on multiple lines, e.g.

Allow: GET
Allow: POST
Is the same as:

Allow: GET, POST
Standard headers that aren't part of this set will be overwritten in the event that they're specified multiple times. For example,

Content-Type: application/octet-stream
Content-Type: text/plain; charset=utf-8
Is the same as:

Content-Type: text/plain; charset=utf-8
This set exists to optimize header lookups and parsing. The existence of standard headers that aren't in this set is an O(1) operation. The repeatable headers in this list require an O(1) operation if they are not present, otherwise the extended headers list needs to be crawled.

Please note non-standard headers exist, e.g. Cookie, that may span multiple lines, even though they're not comma-delimited. For those headers we simply don't add them to the perfect hash table.

@type
_Bool[87]
@note we choose to not recognize this grammar for kHttpConnection
@note grep '[A-Z][a-z]*".*":"' rfc2616
@note grep ':.*#' rfc2616
@see RFC7230 § 4.2

kHttpToken

generated by: o//tool/build/xlat.com -TiC ' ()<>@,;:\"/[]?={}' -iskHttpToken

present            absent
────────────────   ────────────────
                   ∅☺☻♥♦♣♠•◘○◙♂♀♪♫☼   0x00
                   ►◄↕‼¶§▬↨↑↓→←∟↔▲▼   0x10
 ! #$%&‘  *+ -.    ␠ “     ()  ,  /   0x20
0123456789                   :;<=>⁇   0x30
 ABCDEFGHIJKLMNO   @                  0x40
PQRSTUVWXYZ   ^_              [⭝]     0x50
`abcdefghijklmno                      0x60
pqrstuvwxyz | ~               { } ⌂   0x70
                   ÇüéâäàåçêëèïîìÄÅ   0x80
                   ÉæÆôöòûùÿÖÜ¢£¥€ƒ   0x90
                   áíóúñѪº¿⌐¬½¼¡«»   0xa0
                   ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐   0xb0
                   └┴┬├─┼╞╟╚╔╩╦╠═╬╧   0xc0
                   ╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀   0xd0
                   αßΓπΣσμτΦΘΩδ∞φε∩   0xe0
                   ≡±≥≤⌠⌡÷≈°∙×√ⁿ²■λ   0xf0
const char kHttpToken[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x00 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x10 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 0x20 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 0x30 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 0x50 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, // 0x70 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x90 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xa0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xb0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xc0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xd0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xe0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xf0 };
@return
@see RFC2616 CHAR = <any US-ASCII character (octets 0 - 127)> SP = <US-ASCII SP, space (32)> HT = <US-ASCII HT, horizontal-tab (9)> CTL = <any US-ASCII control character
         (octets 0 - 31) and DEL (127)>
token = 1*<any CHAR except CTLs or separators> separators = "(" | ")" | "<" | ">" | "@"
       | "," | ";" | ":" | "\" | <">
       | "/" | "[" | "]" | "?" | "="
       | "{" | "}" | SP | HT

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 checks both if pid exists and we can signal it
@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

kisdangerous

@param
void* p
@return
_Bool

kMbBittab

@type
const unsigned int[51]

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

kNtWsaData

Information about underlying Windows Sockets implementation.

Cosmopolitan automatically calls YOINK() on this symbol when its Berkeley Socket wrappers are linked. The latest version of Winsock was introduced alongside x64, so this should never fail.

@type
struct kNtWsaData

kprintf

Privileged printf().

This function is intended for crash reporting. It's designed to be as unbreakable as possible, so that error messages can always be printed even when the rest of the runtime is broken. As such, it has continue on error semantics, doesn't support buffering between invocations and floating point is not supported. Output is also truncated if the line gets too long, but care is taken to preserve your newline characters. Your errno and GetLastError() state will not be clobbered, and ftrace and other runtime magic won't be invoked, since all the runtime magic depends on this function.

Directives:

%[FLAGS][WIDTH|*][.[PRECISION|*]][TYPE]SPECIFIER
Specifiers:

  • c char
  • o octal
  • b binary
  • s string
  • t symbol
  • p pointer
  • d decimal
  • n newline
  • u unsigned
  • r carriage
  • m strerror
  • G strsignal
  • X uppercase
  • T timestamp
  • x hexadecimal
  • P PID (or TID if TLS is enabled)
Types:

  • hhh bool
  • hh char or cp437
  • h short or char16_t
  • l long or wchar_t
  • ll long long
Flags:

  • 0 zero padding
  • - flip alignment
  • ! bypass memory safety
  • , thousands grouping w/ comma
  • ' thousands grouping w/ apostrophe
  • _ thousands grouping w/ underscore
  • + plus leftpad if positive (aligns w/ negatives)
  • space leftpad if positive (aligns w/ negatives)
  • # represent value with literal syntax, e.g. 0x, 0b, quotes
  • ^ uppercasing w/ towupper() if linked, otherwise toupper()
Error numbers:

  • %m formats error (if strerror_wr if is linked)
  • %m formats errno number (if strerror_wr isn't linked)
  • % m formats error with leading space if errno isn't zero
  • %lm means favor WSAGetLastError() over GetLastError() if linked
You need to link and load the symbol table before %t will work. You can do that by calling GetSymbolTable(). If that hasn't happened it will print &hexnumber instead.
@param
const char* fmt
...
@return
void
@asyncsignalsafe
@vforksafe

ksnprintf

Privileged snprintf().

@param
char* b
is buffer, and guaranteed a NUL-terminator if n>0
unsigned long n
is number of bytes available in buffer
const char* fmt
...
@return
unsigned long
length of output excluding NUL, which may exceed n
@see kprintf() for documentation
@asyncsignalsafe
@vforksafe

kStartTsc

Timestamp of process start.

@type
unsigned long
@see libc/runtime/winmain.greg.h
@see libc/crt/crt.S

kTmpPath

RII constant holding temporary file directory.

The order of precedence is:

  • $TMPDIR/
  • GetTempPath()
  • /tmp/
This guarantees trailing slash.
@type
char[1024]

kToLower

ASCII uppercase → lowercase translation tables.

char kToLower[256];

@return
@see kToUpper

kToUpper

ASCII lowercase → uppercase translation tables.

char kToUpper[256];

@return
@see kToLower

kvappendf

Appends formatted string to buffer.

This is an alternative to vappendf() that uses the kprintf() formatting facility. This has some advantages in terms of performance, code size, and memory safety. There's also disadvantages, such as lack of floating-point directives.

@param
char** b
const char* f
struct __va_list* v
@return
long
@see kprintf()

kvprintf

Privileged vprintf.

@param
const char* fmt
struct __va_list* v
@return
void
@see kprintf() for documentation
@asyncsignalsafe
@vforksafe

kvsnprintf

Privileged vsnprintf().

@param
char* b
is buffer, and guaranteed a NUL-terminator if n>0
unsigned long n
is number of bytes available in buffer
const char* fmt
struct __va_list* v
@return
unsigned long
length of output excluding NUL, which may exceed n
@see kprintf() for documentation
@asyncsignalsafe
@vforksafe

kX86GradeNames

@type
struct IdName[10]

kX86MarchNames

@type
struct IdName[23]

kXedChipFeatures

Mapping of enum XedChip -> bitset<enum XedIsaSet>.

See related APIs, e.g. xed_isa_set_is_valid_for_chip().

This information can be reproduced by building Xed and running the C preprocessor on xed-chip-features-table.c (see xed-chips.txt) which turns several thousand lines of non-evolving code into fifty. For example, 0x2800000ul was calculated as: 1UL<<(XED_ISA_SET_I86-64) | 1UL<<(XED_ISA_SET_LAHF-64).

@type
const unsigned long[3][53]

kXedEamode

@type
const unsigned char[3][2]

kXedErrorNames

Xed error code names.

puts(IndexDoubleNulString(kXedErrorNames, xedd->op.error));

@type
const char[338]
@see XedError

l64a

Converts 32-bit integer to base64, the posix way.

@param
long x
@return
char*
@see a64l() for inverse
@see EncodeBase64()

labs

Returns absolute value of long integer.

@param
long x
@return
long
@note labs(LONG_MIN) returns LONG_MIN unless -ftrapv
@note consider ABS() to avoid narrowing

landlock_add_rule

Adds new rule to Landlock ruleset.

@param
int fd
enum rule_type rule_type
void* rule_attr
unsigned int flags
@return
int
@error ENOSYS if Landlock isn't supported
@error EPERM if Landlock supported but SECCOMP BPF shut it down
@error EOPNOTSUPP if Landlock supported but disabled at boot time
@error EINVAL if flags not 0, or inconsistent access in the rule, i.e. landlock_path_beneath_attr::allowed_access is not a subset of the ruleset handled accesses
@error ENOMSG empty allowed_access
@error EBADF fd is not a file descriptor for current thread, or member of rule_attr is not a file descriptor as expected
@error EBADFD fd is not a ruleset file descriptor, or a member of rule_attr is not the expected file descriptor type
@error EPERM fd has no write access to the underlying ruleset
@error EFAULT rule_attr inconsistency

landlock_create_ruleset

Create new Landlock filesystem sandboxing ruleset.

You may also use this function to query the current ABI version:

landlock_create_ruleset(0, 0, LANDLOCK_CREATE_RULESET_VERSION);
@param
struct landlock_ruleset_attr* attr
unsigned long size
unsigned int flags
@return
int
close exec file descriptor for new ruleset
@error ENOSYS if not running Linux 5.13+
@error EPERM if pledge() or seccomp bpf shut it down
@error EOPNOTSUPP Landlock supported but disabled at boot
@error EINVAL unknown flags, or unknown access, or too small size
@error E2BIG attr or size inconsistencies
@error EFAULT attr or size inconsistencies
@error ENOMSG empty landlock_ruleset_attr::handled_access_fs

landlock_restrict_self

Enforces Landlock ruleset on calling thread.

@param
int fd
unsigned int flags
@return
int
@error EOPNOTSUPP if Landlock supported but disabled at boot time
@error EINVAL if flags isn't zero
@error EBADF if fd isn't file descriptor for the current thread
@error EBADFD if fd is not a ruleset file descriptor
@error EPERM if fd has no read access to underlying ruleset, or current thread is not running with no_new_privs, or it doesn’t have CAP_SYS_ADMIN in its namespace
@error E2BIG if the maximum number of stacked rulesets is reached for current thread

lchown

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

@param
const char* pathname
unsigned int uid
is user id, or -1u to not change
unsigned int gid
is group id, or -1u to not change
@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
double x
int n
@return
double

ldexpf

Returns 𝑥 × 2ʸ.

@param
float x
int n
@return
float

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

LengthInt64

Returns len(str(x)) where x is a signed 64-bit integer.

@param
long x
@return
unsigned int

LengthInt64Thousands

Returns decimal string length of int64 w/ thousands separators.

@param
long x
@return
unsigned int

LengthUint64

Returns len(str(x)) where x is an unsigned 64-bit integer.

@param
unsigned long x
@return
unsigned int

LengthUint64Thousands

Returns decimal string length of uint64 w/ thousands separators.

@param
unsigned long x
@return
unsigned int

lgamma

Returns natural logarithm of absolute value of gamma function.

@param
double x
@return
double

lgamma_r

@param
double x
int* signgamp
@return
double

lgammaf

@param
float x
@return
float

lgammaf_r

Returns natural logarithm of absolute value of Gamma function.

@param
float x
int* signgamp
@return
float


linkat

Creates hard filesystem link.

This allows two names to point to the same file data on disk. They can only be differentiated by examining the inode number.

@param
int olddirfd
const char* oldpath
int newdirfd
const char* newpath
int flags
can have AT_EMPTY_PATH or AT_SYMLINK_NOFOLLOW
@return
int
0 on success, or -1 w/ errno
@asyncsignalsafe

listen

Asks system to accept incoming connections on socket.

The socket() and bind() functions need to be called beforehand. Once this function is called, accept() is used to wait for connections. Using this on connectionless sockets will allow it to receive packets on a designated address.

@param
int fd
int backlog
<= SOMAXCONN
@return
int
0 on success or -1 w/ errno

llabs

Returns absolute value of long long integer.

@param
long x
@return
long
@note llabs(LONG_LONG_MIN) returns LONG_LONG_MIN unless -ftrapv
@note consider ABS() to avoid narrowing

lldiv

@param
long num
long den
@return
struct lldiv_t

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 lconv*

localtime

@param
const long* timep
@return
struct alttm*


localtime_r

@param
const long* timep
struct alttm* tmp
@return
struct alttm*


_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() if only written by one thread

_lockxadd

Compares and exchanges w/ lock prefix.

@param
void* ifthing
is uint𝑘_t[hasatleast 1] where 𝑘 ∈ {8,16,32,64}
long replaceitwithme
unsigned long size
is automatically supplied by macro wrapper
@return
long
value at location *ifthing *before* addition
@see InterlockedAdd() for a very similar API
@see xadd() if only written by one thread

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

longerjmp

Loads previously saved processor state.

@param
rdi
points to the jmp_buf
rsi
is returned by setlongerjmp() invocation

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

longsort

Sorting algorithm for longs that doesn't take long.

"What disorder is this? Give me my long sort!"
                          -Lord Capulet
@param
long* x
unsigned long n
@return
void

LookupProtoByName

Opens and searches /etc/protocols to find number for a given name.

@param
const char* protoname
is a NULL-terminated string
char* buf
is a buffer to store the official name of the protocol
unsigned long bufsize
is the size of buf
const char* filepath
is the location of protocols file
 (if NULL, uses /etc/protocols)
@return
int
-1 on error, or
 positive protocol number
@note aliases are read from file for comparison, but not returned.
@see LookupProtoByNumber

LookupProtoByNumber

Opens and searches /etc/protocols to find name for a given number.

The format of /etc/protocols is like this:

# comment
# NAME           PROTOCOL        ALIASES
ip               0               IP
icmp             1               ICMP
@param
const int protonum
is the protocol number
char* buf
is a buffer to store the official name of the protocol
unsigned long bufsize
is the size of buf
const char* filepath
is the location of the protocols file
 (if NULL, uses /etc/protocols)
@return
int
0 on success, -1 on error
@note aliases are not read from the file.

LookupServicesByName

Opens and searches /etc/services to find port for a given name.

@param
const char* servname
is a NULL-terminated string
char* servproto
is a NULL-terminated string (eg "tcp", "udp")
 (if servproto is an empty string,
  if is filled with the first matching
  protocol)
unsigned long servprotolen
the size of servproto
char* buf
is a buffer to store the official name of the service
 (if NULL, the official name is not stored)
unsigned long bufsize
is the size of buf
const char* filepath
is the location of services file
 (if NULL, uses /etc/services)
@return
int
-1 on error, or positive port number
@note aliases are read from file for comparison, but not returned.
@see LookupServicesByPort
@threadsafe

LookupServicesByPort

Opens and searches /etc/services to find name for a given port.

The format of /etc/services is like this:

# comment
# NAME       PORT/PROTOCOL       ALIASES
ftp          21/tcp
fsp          21/udp              fspd
ssh          22/tcp
@param
const int servport
is the port number
char* servproto
is a NULL-terminated string (eg "tcp", "udp")
 (if servproto is an empty string,
  if is filled with the first matching
  protocol)
unsigned long servprotolen
the size of servproto
char* buf
is a buffer to store the official name of the service
unsigned long bufsize
is the size of buf
const char* filepath
is the location of the services file
 (if NULL, uses /etc/services)
@return
int
0 on success, -1 on error
@note aliases are not read from the file.

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
const char* pathname
struct stat* st
@return
int
@asyncsignalsafe

lutimes

Changes file timestamps, the legacy way.

@param
const char* filename
struct it_value* tv
@return
int

lz4check

@param
void* data
@return
const 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()

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()

major

@param
unsigned long x
@return
unsigned int

makedev

@param
unsigned int x
unsigned int y
@return
unsigned long

makedirs

Recursively creates directory a.k.a. folder.

This function won't fail if the directory already exists.

@param
const 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

@param
struct mallinfo*
@return
struct mallinfo

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, coerced to 1+
@return
new memory, or NULL w/ errno
@threadsafe

malloc_inspect_all

@param
void(*)() handler
void* arg
@return
void


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()
@threadsafe

__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);
If mmap() fails, possibly because the parent process did this:

if (!vfork()) {
  setrlimit(RLIMIT_AS, &(struct rlimit){maxbytes, maxbytes});
  execv(prog, (char *const[]){prog, 0});
}
wait(0);
Then this function will call:

__oom_hook(size);
If it's linked. The LIBC_TESTLIB library provides an implementation, which can be installed as follows:

int main() {
    InstallQuotaHandlers();
    // ...
}
That is performed automatically for unit test executables.
@param
unsigned long size
@return
void*
memory map address on success, or null w/ errno

_mapshared

Creates anonymous shared memory mapping.

@param
unsigned long size
@return
void*
memory map address on success, or null w/ errno

_mapstack

Allocates stack.

The size of your returned stack is always GetStackSize().

The bottom 4096 bytes of your stack can't be used, since it's always reserved for a read-only guard page. With ASAN it'll be poisoned too.

The top 16 bytes of a stack can't be used due to openbsd:stackbound and those bytes are also poisoned under ASAN build modes.

@return
void*
stack bottom address on success, or null w/ errrno

MapViewOfFileEx

Maps view of file mapping into memory on the New Technology.

@param
long hFileMappingObject
was returned by CreateFileMapping()
unsigned int dwDesiredAccess
has kNtFileMap... flags
unsigned int dwFileOffsetHigh
unsigned int dwFileOffsetLow
unsigned long dwNumberOfBytesToMap
void* opt_lpDesiredBaseAddress
may be NULL to let o/s choose
@return
void*
base address, or NULL on failure
@note this wrapper takes care of ABI, STRACE(), and __winerr()

MapViewOfFileExNuma

Maps view of file mapping into memory on the New Technology.

@param
long hFileMappingObject
was returned by CreateFileMapping()
unsigned int dwDesiredAccess
has kNtFileMap... flags
unsigned int dwFileOffsetHigh
unsigned int dwFileOffsetLow
unsigned long dwNumberOfBytesToMap
void* opt_lpDesiredBaseAddress
may be NULL to let o/s choose
unsigned int nndDesiredNumaNode
@return
void*
base address, or NULL on failure
@note this wrapper takes care of ABI, STRACE(), and __winerr()

MarsagliaXorshift32

@param
unsigned int* state
@return
unsigned int

MarsagliaXorshift64

@param
unsigned long* state
@return
unsigned long

mblen

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

mbrlen

@param
const char* s
unsigned long n
unsigned int* t
@return
unsigned long

mbrtoc16

@param
unsigned short* pc16
const char* s
unsigned long n
unsigned int* ps
@return
unsigned long

mbrtoc32

@param
unsigned int* pc32
const char* s
unsigned long n
unsigned int* ps
@return
unsigned long

mbrtowc

@param
int* wc
const char* src
unsigned long n
unsigned int* st
@return
unsigned long

mbsinit

@param
const unsigned int* t
@return
int

mbsnrtowcs

@param
int* wcs
const char** src
unsigned long n
unsigned long wn
unsigned int* st
@return
unsigned long

mbsrtowcs

@param
int* ws
const char** src
unsigned long wn
unsigned int* st
@return
unsigned long

mbstowcs

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

mbtowc

@param
int* wc
const char* src
unsigned long n
@return
int

MeasureEntropy

Returns Shannon entropy of array.

This gives you an idea of the density of information. Cryptographic random should be in the ballpark of 7.9 whereas plaintext will be more like 4.5.

@param
const char* p
is treated as binary octets
unsigned long n
should be at least 1000
@return
double
number between 0 and 8

memalign

Allocates aligned memory.

Returns a pointer to a newly allocated chunk of n bytes, aligned in accord with the alignment argument. The alignment argument shall be rounded up to the nearest two power and higher 2 powers may be used if the allocator imposes a minimum alignment requirement.

@param
rdi
is alignment in bytes, coerced to 1+ w/ 2-power roundup
rsi
is number of bytes needed, coerced to 1+
@return
rax is memory address, or NULL w/ errno
@see valloc(), pvalloc()
@threadsafe

memcasecmp

Compares memory case-insensitively.

memcasecmp n=0                     992 picoseconds
memcasecmp n=1                       1 ns/byte            590 mb/s
memcasecmp n=2                       1 ns/byte            843 mb/s
memcasecmp n=3                       1 ns/byte            885 mb/s
memcasecmp n=4                       1 ns/byte            843 mb/s
memcasecmp n=5                       1 ns/byte            820 mb/s
memcasecmp n=6                       1 ns/byte            770 mb/s
memcasecmp n=7                       1 ns/byte            765 mb/s
memcasecmp n=8                     206 ps/byte          4,724 mb/s
memcasecmp n=9                     220 ps/byte          4,428 mb/s
memcasecmp n=15                    617 ps/byte          1,581 mb/s
memcasecmp n=16                    124 ps/byte          7,873 mb/s
memcasecmp n=17                    155 ps/byte          6,274 mb/s
memcasecmp n=31                    341 ps/byte          2,860 mb/s
memcasecmp n=32                     82 ps/byte         11,810 mb/s
memcasecmp n=33                    100 ps/byte          9,743 mb/s
memcasecmp n=80                     53 ps/byte         18,169 mb/s
memcasecmp n=128                    49 ps/byte         19,890 mb/s
memcasecmp n=256                    45 ps/byte         21,595 mb/s
memcasecmp n=16384                  42 ps/byte         22,721 mb/s
memcasecmp n=32768                  40 ps/byte         24,266 mb/s
memcasecmp n=131072                 40 ps/byte         24,337 mb/s
@param
void* p
void* q
unsigned long n
@return
int
is <0, 0, or >0 based on uint8_t comparison

memccpy

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

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

For example, strictly:

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

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

char cstrbuf[16];
snprintf(cstrbuf, sizeof(cstrbuf), "%s", CSTR);
@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

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

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

memmove

Copies memory.

memmove n=0                        661 picoseconds
memmove n=1                        661 ps/byte          1,476 mb/s
memmove n=2                        330 ps/byte          2,952 mb/s
memmove n=3                        330 ps/byte          2,952 mb/s
memmove n=4                        165 ps/byte          5,904 mb/s
memmove n=7                        141 ps/byte          6,888 mb/s
memmove n=8                         82 ps/byte             11 GB/s
memmove n=15                        44 ps/byte             21 GB/s
memmove n=16                        41 ps/byte             23 GB/s
memmove n=31                        32 ps/byte             29 GB/s
memmove n=32                        31 ps/byte             30 GB/s
memmove n=63                        21 ps/byte             45 GB/s
memmove n=64                        15 ps/byte             61 GB/s
memmove n=127                       13 ps/byte             73 GB/s
memmove n=128                       31 ps/byte             30 GB/s
memmove n=255                       20 ps/byte             45 GB/s
memmove n=256                       19 ps/byte             49 GB/s
memmove n=511                       16 ps/byte             56 GB/s
memmove n=512                       17 ps/byte             54 GB/s
memmove n=1023                      18 ps/byte             52 GB/s
memmove n=1024                      13 ps/byte             72 GB/s
memmove n=2047                       9 ps/byte             96 GB/s
memmove n=2048                       9 ps/byte             98 GB/s
memmove n=4095                       8 ps/byte            112 GB/s
memmove n=4096                       8 ps/byte            109 GB/s
memmove n=8191                       7 ps/byte            124 GB/s
memmove n=8192                       7 ps/byte            125 GB/s
memmove n=16383                      7 ps/byte            134 GB/s
memmove n=16384                      7 ps/byte            134 GB/s
memmove n=32767                     13 ps/byte             72 GB/s
memmove n=32768                     13 ps/byte             72 GB/s
memmove n=65535                     13 ps/byte             68 GB/s
memmove n=65536                     14 ps/byte             67 GB/s
memmove n=131071                    14 ps/byte             65 GB/s
memmove n=131072                    14 ps/byte             64 GB/s
memmove n=262143                    15 ps/byte             63 GB/s
memmove n=262144                    15 ps/byte             63 GB/s
memmove n=524287                    15 ps/byte             61 GB/s
memmove n=524288                    15 ps/byte             61 GB/s
memmove n=1048575                   15 ps/byte             61 GB/s
memmove n=1048576                   15 ps/byte             61 GB/s
memmove n=2097151                   19 ps/byte             48 GB/s
memmove n=2097152                   27 ps/byte             35 GB/s
memmove n=4194303                   28 ps/byte             33 GB/s
memmove n=4194304                   28 ps/byte             33 GB/s
memmove n=8388607                   28 ps/byte             33 GB/s
memmove n=8388608                   28 ps/byte             33 GB/s
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

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

memset16

Sets wide memory.

@param
unsigned short* p
unsigned short c
unsigned long n
@return
unsigned short*
@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
const char* fmt
...
@return
void

mincore

Tells you which pages are resident in memory.

@param
void* addr
unsigned long length
unsigned char* vec
@return
int

minor

@param
unsigned long x
@return
unsigned int

mkdir

Creates directory a.k.a. folder.

mkdir o               →  0
mkdir o/yo/yo/yo      → -1 w/ ENOENT
if o/yo is file       → -1 w/ ENOTDIR
if o/yo/yo/yo is dir  → -1 w/ EEXIST
if o/yo/yo/yo is file → -1 w/ EEXIST
@param
const 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 ENAMETOOLONG if >246 characters on NT
@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
const 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()

mkdtemp

Creates temporary directory.

@param
char* template
must end with XXXXXX which is replaced with nondeterministic base36 random data
@return
char*
pointer to template on success, or NULL w/ errno
@raise EINVAL if template didn't end with XXXXXX

mkfifo

Creates named pipe.

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

mknod

Creates filesystem inode.

@param
const char* path
unsigned int mode
is octal mode, e.g. 0600; needs to be or'd with one of: S_IFDIR: directory S_IFIFO: named pipe S_IFREG: regular file S_IFSOCK: named socket S_IFBLK: block device (root has authorization) S_IFCHR: character device (root has authorization)
unsigned long dev
it's complicated
@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
const 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
@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
const char* extravar
is a VAR=val string we consider part of envp or NULL
char* buf
@return
int
0 on success, or -1 w/ errno
@error E2BIG if total number of shorts exceeded ARG_MAX/2 (32767)

__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
const char* path
unsigned short* path16
is shortened so caller can prefix, e.g. \\.\pipe\, and due to a plethora of special-cases throughout the Win32 API
int flags
is used by open()
@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 alttm* tmp
@return
long

_mktls

Allocates thread-local storage memory for new thread.

@param
char** out_tib
@return
char*
buffer that must be released with free()

mmap

Beseeches system for page-table entries, e.g.

char *m;
m = mmap(NULL, FRAMESIZE, PROT_READ | PROT_WRITE,
         MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
munmap(m, FRAMESIZE);
@param
void* addr
should be 0 to let your memory manager choose address; unless MAP_FIXED or MAP_FIXED_NOREPLACE are specified in flags in which case this function will do precicely as you ask, even if p=0 (in which you need -fno-delete-null-pointer-checks); it needs to be 64kb aligned because it's a wise choice that sadly needs to be made mandatory because of Windows although you can use __sys_mmap() to circumvent it on System Five in which case runtime support services, e.g. asan memory safety, could break
unsigned long size
must be >0 and needn't be a multiple of FRAMESIZE, but will be rounded up to FRAMESIZE automatically if MAP_ANONYMOUS is specified
int prot
can have PROT_READ/PROT_WRITE/PROT_EXEC/PROT_NONE/etc.
int flags
should have one of the following masked by MAP_TYPE
  • MAP_FILE in which case fd != -1 should be the case
  • MAP_PRIVATE for copy-on-write behavior of writeable pages
  • MAP_SHARED to create shared memory between processes
  • MAP_STACK to create a grows-down alloc, where a guard page is automatically protected at the bottom: FreeBSD's behavior is polyfilled across platforms; uses MAP_GROWSDOWN on Linux too for extra oomph (do not use MAP_GROWSDOWN!) and this is completely mandatory on OpenBSD but helps perf elsewhere if you need to create 10,000 threads. This flag is the reason why STACK_FRAME_UNLIMITED toil is important, because this only allocates a 4096-byte guard page, thus we need the GCC compile-time checks to ensure some char[8192] vars will not create an undetectable overflow into another thread's stack
Your flags may optionally bitwise or any of the following:
  • MAP_ANONYMOUS in which case fd == -1 should be the case
  • MAP_FIXED in which case addr becomes more than a hint
  • MAP_FIXED_NOREPLACE to protect existing mappings; this is always polyfilled by mmap() which tracks its own memory and removed before passing to the kernel, in order to support old versions; if you believe mappings exist which only the kernel knows, then this flag may be passed to sys_mmap() on Linux 4.17+ and FreeBSD (where it has multiple bits)
  • MAP_CONCEAL is FreeBSD/NetBSD/OpenBSD-only
  • MAP_NORESERVE is Linux/XNU/NetBSD-only
  • MAP_POPULATE is Linux/FreeBSD-only
  • MAP_NONBLOCK is Linux-only
  • MAP_NOSYNC is FreeBSD-only
  • MAP_INHERIT is NetBSD-only
  • MAP_LOCKED is Linux-only
int fd
is an open()'d file descriptor, whose contents shall be made available w/ automatic reading at the chosen address and must be -1 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

modf

@param
double x
double* iptr
@return
double

modff

@param
float x
float* iptr
@return
float

__morph_begin

Begins code morphing executable.

@return
void
0 on success, or -1 w/ errno

__morph_end

Begins code morphing executable.

@return
void

morton

Interleaves bits.

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

mount

Mounts file system.

The following flags may be specified:

  • MS_RDONLY (mount read-only)
  • MS_NOSUID (don't honor S_ISUID bit)
  • MS_NODEV (disallow special files)
  • MS_NOEXEC (disallow program execution)
  • MS_SYNCHRONOUS (writes are synced at once)
  • MS_NOATIME (do not update access times)
  • MS_REMOUNT (tune existing mounting)
The following flags may also be used, but could be set to zero at runtime if the underlying kernel doesn't support them.

  • MNT_ASYNC (xnu, freebsd, openbsd, netbsd)
  • MNT_RELOAD (xnu, freebsd, openbsd, netbsd)
  • MS_STRICTATIME (linux, xnu)
  • MS_RELATIME (linux, netbsd)
  • MNT_SNAPSHOT (xnu, freebsd)
  • MS_MANDLOCK (linux)
  • MS_DIRSYNC (linux)
  • MS_NODIRATIME (linux)
  • MS_BIND (linux)
  • MS_MOVE (linux)
  • MS_REC (linux)
  • MS_SILENT (linux)
  • MS_POSIXACL (linux)
  • MS_UNBINDABLE (linux)
  • MS_PRIVATE (linux)
  • MS_SLAVE (linux)
  • MS_SHARED (linux)
  • MS_KERNMOUNT (linux)
  • MS_I_VERSION (linux)
  • MS_LAZYTIME (linux)
  • MS_ACTIVE (linux)
  • MS_NOUSER (linux)
  • MS_RMT_MASK (linux)
  • MNT_SUIDDIR (freebsd)
  • MNT_NOCLUSTERR (freebsd)
  • MNT_NOCLUSTERW (freebsd)
Some example values for the type parameter:

  • "nfs"
  • "vfat"
  • "tmpfs"
  • "iso8601"
@param
const char* source
const char* target
const char* type
unsigned long flags
void* data
@return
int

MoveFileEx

Deletes existing empty directory.

@param
const unsigned short* lpExistingFileName
const unsigned short* lpNewFileName
int dwFlags
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

mprotect

Modifies restrictions on virtual memory address range.

@param
void* addr
needs to be 4kb aligned
unsigned long size
int prot
can have PROT_{NONE,READ,WRITE,EXEC,GROWSDOWN,GROWSUP}
@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
const unsigned char* b
const 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

Extends and/or relocates memory pages.

@param
void* p
is old address
unsigned long n
is old size
unsigned long m
is new size
int f
should have MREMAP_MAYMOVE and may have MAP_FIXED
...
@return
void*

msync

Synchronize memory mapping changes to disk.

Without this, there's no guarantee memory is written back to disk. Particularly on RHEL5, OpenBSD, and Windows NT.

@param
void* addr
needs to be 4096-byte page aligned
unsigned long size
int flags
needs MS_ASYNC or MS_SYNC and can have MS_INVALIDATE
@return
int
0 on success or -1 w/ errno

_mt19937

Generates random integer on [0, 2^64)-interval.

This uses the Mersenne Twister pseudorandom number generator.

@return
unsigned long
@see smt19937(), Smt19937()

Mul4x4Adx

Computes 512-bit product of 256-bit and 256-bit numbers.

Instructions: 88 Total Cycles: 36 Total uOps: 120 uOps Per Cycle: 3.33 IPC: 2.44 Block RThroughput: 20.0

@param
rdi
receives 8 quadword result
rsi
is left hand side which must have 4 quadwords
rdx
is right hand side which must have 4 quadwords
@return
@note words are host endian while array is little endian
@mayalias

Mul6x6Adx

Computes 768-bit product of 384-bit and 384-bit numbers.

Instructions: 152 Total Cycles: 65 Total uOps: 260 uOps Per Cycle: 4.00 IPC: 2.34 Block RThroughput: 43.3

@param
rdi
receives 8 quadword result
rsi
is left hand side which must have 4 quadwords
rdx
is right hand side which must have 4 quadwords
@return
@note words are host endian while array is little endian
@mayalias

Mul8x8Adx

Computes 1024-bit product of 512-bit and 512-bit numbers.

Instructions: 260 Total Cycles: 98 Total uOps: 452 uOps Per Cycle: 4.61 IPC: 2.65 Block RThroughput: 75.3

@param
rdi
receives 16 quadword result
rsi
is left hand side which must have 8 quadwords
rdx
is right hand side which must have 8 quadwords
@return
@note words are host endian while array is little endian
@mayalias

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

@param
void* p
is the beginning of the memory region to unmap
unsigned long n
is the number of bytes to be unmapped
@return
int
0 on success, or -1 w/ errno
@raises EINVAL if n == 0
@raises EINVAL if n isn't 48-bit
@raises EINVAL if p+(n-1) isn't 48-bit
@raises EINVAL if p isn't 65536-byte aligned

nan

@param
const char* s
@return
double

nanf

@param
const char* s
@return
float

nanl

@param
const char* s
@return
long double

_nanos

Returns nanoseconds since UNIX epoch.

@param
int timer
@return
__int128

nanosleep

Sleeps for a particular amount of time.

@param
struct st_birthtim* req
is the duration of time we should sleep
struct st_birthtim* rem
if non-NULL will receive the amount of time that wasn't slept because a signal was delivered. If no signal's delivered then this value will be set to {0, 0}. It's also fine to set this value to the same pointer as req.
@return
int
0 on success, or -1 w/ errno
@raise EINVAL if req->tv_nsec ∉ [0,1000000000)
@raise EINTR if a signal was delivered, and rem is updated
@raise EFAULT if req is NULL or req / rem is a bad pointer
@raise ENOSYS on bare metal
@note POSIX.1 specifies nanosleep() measures against CLOCK_REALTIME however Linux measures uses CLOCK_MONOTONIC. This shouldn't matter, since POSIX.1 further specifies that discontinuous changes in CLOCK_REALTIME shouldn't impact nanosleep()
@norestart

__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*

newlocale

@param
int catmask
const char* locale
struct __locale_struct* base
@return
struct __locale_struct*

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

nexttoward

@param
double x
long double y
@return
double

nexttowardf

@param
float x
long double y
@return
float

nexttowardl

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

nftw

Walks file tree.

@param
const char* path
int(*)() fn
int fd_limit
int flags
@return
int
@see examples/walk.c for example

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

nl_langinfo

@param
int item
@return
char*

nl_langinfo_l

@param
int item
struct __locale_struct* loc
@return
char*

__nocolor

Indicates if ANSI terminal colors are inappropriate.

Normally this variable should be false. We only set it to true if we're running on an old version of Windows or the environment variable TERM is set to dumb.

We think colors should be the norm, since most software is usually too conservative about removing them. Rather than using isatty consider using sed for instances where color must be removed:

 sed 's/\x1b\[[;[:digit:]]*m//g' <color.txt >uncolor.txt
For some reason, important software is configured by default in many operating systems, to not only disable colors, but utf-8 too! Here's an example of how a wrapper script can fix that for less.

 #!/bin/sh
 LESSCHARSET=UTF-8 exec /usr/bin/less -RS "$@"
Thank you for using colors!
@type
_Bool

__nosync

Tunes sync system call availability.

If this value is set to 0x5453455454534146, then the system calls sync(), fsync(), and fdatasync() system calls will do nothing and return success. This is intended to be used for things like making things like Python unit tests go faster because fsync is extremely slow and using tmpfs requires root privileges.

@type
unsigned long

nowl_setup

@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
const 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

NtGetVersion

Returns New Technology version, e.g.

This can only be called on Windows.

@return
int
@see IsAtLeastWindows10()

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
const 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
const char* prog
won't be PATH searched
char** argv
specifies prog arguments
char** envp
const char* extravar
is added to envp to avoid setenv() in caller
struct NtSecurityAttributes* opt_lpProcessAttributes
struct NtSecurityAttributes* opt_lpThreadAttributes
int bInheritHandles
means handles already marked inheritable will be inherited; which, assuming the System V wrapper functions are being used, should mean (1) all files and sockets that weren't opened with O_CLOEXEC; and (2) all memory mappings
unsigned int dwCreationFlags
const unsigned short* opt_lpCurrentDirectory
struct NtStartupInfo* lpStartupInfo
struct NtProcessInformation* opt_out_lpProcessInformation
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

__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
@threadsafe
@vforksafe

__onfork

Triggers callbacks registered by atfork().

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

open

Opens file.

@param
const 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 (zip files may have issues)
@vforksafe (raises error if zip file)
@restartable
@threadsafe

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
const 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 (zip files may have issues)
@vforksafe (raises error if zip file)
@threadsafe

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
const char* name
@return
struct dirstream*
@returns newly allocated DIR object, or NULL w/ errno
@errors ENOENT, ENOTDIR, EACCES, EMFILE, ENFILE, ENOMEM
@see glob()

OpenExecutable

Opens executable in O_RDWR mode.

To avoid ETXTBSY we need to unmap the running executable first, then open the file, and finally load the code back into memory.

@return
file descriptor
@note only works on .com binary (not .com.dbg)
@note only supports linux, freebsd, openbsd, and netbsd

openlog

Opens a connection to the system logger

Calling this function before calling syslog() is optional and only allow customizing the identity, options and facility of the messages logged.

@param
const char* ident
a string that prepends every logged message. If it set to NULL, the program name is used.
int opt
specifies flags which control the operation of openlog(). Only the following flags are supported:
LOG_CONS = Write directly to the system console if there is
           an error while sending to the system logger.
LOG_NDELAY = Open the connection with the system logger
             immediately instead of waiting for the first
             message to be logged.
LOG_ODELAY = The converse of LOG_NDELAY.
LOG_PERROR = Also log the message to stderr.
LOG_PID = Include the caller's PID with each message
int facility
specifies the default facitlity value that defines what kind of program is logging the message. Possible values are: LOG_AUTH, LOG_AUTHPRIV, LOG_CRON, LOG_DAEMON, LOG_FTP, LOG_LOCAL0 through LOG_LOCAL7, LOG_LPR, LOG_MAIL, LOG_NEWS, LOG_SYSLOG, LOG_USER (default), LOG_UUCP.
@return
void
@asyncsignalsafe

OpenProcess

Creates file mapping object on the New Technology.

@param
unsigned int dwDesiredAccess
should be kNtProcess... combination
int bInheritHandle
unsigned int dwProcessId
@return
long
ehandle, or 0 on failure
@note this wrapper takes care of ABI, STRACE(), and __winerr()
@see MapViewOfFileEx()

openpty

Opens new pseudo teletypewriter.

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

OpenSymbolTable

Maps debuggable binary into memory and indexes symbol addresses.

@param
const 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
const 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
const 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
const 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
const int* b
const int* c
@return
void
@mayalias

packsswb

Casts shorts to signed chars w/ saturation.

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

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

packusdw

Casts ints to shorts w/ saturation.

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

packuswb

Casts shorts to unsigned chars w/ saturation.

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

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

paddb

Adds 8-bit integers.

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

paddd

Adds 32-bit integers.

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

paddq

Adds 64-bit integers.

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

paddsb

Adds signed 8-bit integers w/ saturation.

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

paddsw

Adds signed 16-bit integers w/ saturation.

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

paddusb

Adds unsigned 8-bit integers w/ saturation.

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

paddusw

Adds unsigned 16-bit integers w/ saturation.

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

paddw

Adds 16-bit integers.

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

__paginate

Displays wall of text in terminal with pagination.

@param
int fd
const char* s
@return
void

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
const unsigned long* b
const unsigned long* c
@return
void
@mayalias

pandn

Nands 128-bit integers.

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

ParseContentLength

Parses Content-Length header.

@param
const char* s
unsigned long n
@return
long
-1 on invalid or overflow, otherwise >=0 value

ParseForwarded

Parses X-Forwarded-For.

This header is used by reverse proxies. For example:

X-Forwarded-For: 203.0.110.2, 203.0.113.42:31337
The port is optional and will be set to zero if absent.
@param
const char* s
is input data
unsigned long n
if -1 implies strlen
unsigned int* ip
receives last/right ip on success if not NULL
unsigned short* port
receives port on success if not NULL
@return
int
0 on success or -1 on failure
@see RFC7239's poorly designed Forwarded header

ParseHost

Parses HTTP Host header.

The input is ISO-8859-1 which is transcoded to UTF-8. Therefore we assume percent-encoded bytes are expressed as UTF-8. Returned values might contain things like NUL characters, C0, and C1 control codes. UTF-8 isn't checked for validity and may contain overlong values. Absent can be discerned from empty by checking if the pointer is set.

This function turns an HTTP header HOST[:PORT] into two strings, one for host and the other for port. You may then call IsAcceptableHost() and IsAcceptablePort() to see if they are valid values. After that a function like sscanf() can be used to do the thing you likely thought this function would do.

This function doesn't initialize h since it's assumed this will be called conditionally after ParseRequestUri() if the host is absent. Fields unrelated to authority won't be impacted by this function.

@param
const char* s
is value like 127.0.0.1 or foo.example:80
unsigned long n
is byte length and -1 implies strlen
struct Url* h
is needs to be initialized by caller
@return
char*
memory backing UrlView needing free

ParseHostsTxt

Parses HOSTS.TXT contents.

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

# this is a comment
# IP            CANON [ALT...]
203.0.113.1     lol.example. lol
203.0.113.2     cat.example. cat
@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

ParseHttpDateTime

Parses HTTP timestamp, e.g.

Sun, 04 Oct 2020 19:50:10 GMT

@param
const char* p
unsigned long n
if -1 implies strlen
@return
long
seconds from unix epoch
@see FormatHttpDateTime()

ParseHttpMessage

Parses HTTP request or response.

This parser is responsible for determining the length of a message and slicing the strings inside it. Performance is attained using perfect hash tables. No memory allocation is performed for normal messages. Line folding is forbidden. State persists across calls so that fragmented messages can be handled efficiently. A limitation on message size is imposed to make the header data structures smaller.

This parser assumes ISO-8859-1 and guarantees no C0 or C1 control codes are present in message fields, with the exception of tab. Please note that fields like kHttpStateUri may use UTF-8 percent encoding. This parser doesn't care if you choose ASA X3.4-1963 or MULTICS newlines.

kHttpRepeatable defines which standard header fields are O(1) and which ones may have comma entries spilled over into xheaders. For most headers it's sufficient to simply check the static slice. If r->headers[kHttpFoo].a is zero then the header is totally absent.

This parser has linear complexity. Each character only needs to be considered a single time. That's the case even if messages are fragmented. If a message is valid but incomplete, this function will return zero so that it can be resumed as soon as more data arrives.

This parser takes about 400 nanoseconds to parse a 403 byte Chrome HTTP request under MODE=rel on a Core i9 which is about three cycles per byte or a gigabyte per second of throughput per core.

@param
struct HttpMessage* r
const char* p
unsigned long n
@return
int
@note we assume p points to a buffer that has >=SHRT_MAX bytes
@see HTTP/1.1 RFC2616 RFC2068
@see HTTP/1.0 RFC1945

ParseHttpRange

Parses HTTP Range request header.

Here are some example values:

Range: bytes=0-                 (everything)
Range: bytes=0-499              (first 500 bytes)
Range: bytes=500-999            (second 500 bytes)
Range: bytes=-500               (final 500 bytes)
Range: bytes=0-0,-1             (first and last and always)
Range: bytes=500-600,601-999    (overlong but legal)
@param
const char* p
unsigned long n
long resourcelength
long* out_start
long* out_length
@return
_Bool

ParseIp

Parse IPv4 address.

@param
const char* s
unsigned long n
if -1 implies strlen
@return
long
-1 on failure, otherwise 32-bit host-order unsigned integer

ParseParams

Parses HTTP POST key-value params.

These are similar to the parameters found in a Request-URI. The main difference is that + is translated into space here. The mime type for this is application/x-www-form-urlencoded.

This parser is charset agnostic. Returned values might contain things like NUL characters, NUL, control codes, and non-canonical encodings. Absent can be discerned from empty by checking if the pointer is set.

There's no failure condition for this routine. This is a permissive parser that doesn't impose character restrictions beyond what is necessary for parsing.

@param
const char* s
is value like foo=bar&x=y&z
unsigned long n
is byte length and -1 implies strlen
struct params* h
must be zeroed by caller and this appends if reused
@return
char*
UrlView memory with same n needing free (h.p needs free too)

parseport

@param
const char* service
@return
int

ParseRequestUri

Parses HTTP Request-URI.

The input is ISO-8859-1 which is transcoded to UTF-8. Therefore we assume percent-encoded bytes are expressed as UTF-8. Returned values might contain things like NUL characters, C0, and C1 control codes. UTF-8 isn't checked for validity and may contain overlong values. Absent can be discerned from empty by checking if the pointer is set.

There's no failure condition for this routine. This is a permissive parser that doesn't impose character restrictions beyond what is necessary for parsing. This doesn't normalize path segments like . or ... Use IsAcceptablePath() to check for those.

@param
const char* s
is value like /hi?x=y&z or http://a.example/hi#x
unsigned long n
is byte length and -1 implies strlen
struct Url* h
is assumed to be uninitialized
@return
char*
memory backing UrlView needing free (and h.params.p too)

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

ParseUrl

Parses URL.

This parser is charset agnostic. Percent encoded bytes are decoded for all fields (with the exception of scheme). Returned values might contain things like NUL characters, spaces, control codes, and non-canonical encodings. Absent can be discerned from empty by checking if the pointer is set.

There's no failure condition for this routine. This is a permissive parser. This doesn't normalize path segments like . or .. so use IsAcceptablePath() to check for those. No restrictions are imposed beyond that which is strictly necessary for parsing. All the s that is provided will be consumed to the one of the fields. Strict conformance is enforced on some fields more than others, like scheme, since it's the most non-deterministically defined field of them all.

Please note this is a URL parser, not a URI parser. Which means we support everything everything the URI spec says we should do except for the things we won't do, like tokenizing path segments into an array and then nesting another array beneath each of those for storing semicolon parameters. So this parser won't make SIP easy. What it can do is parse HTTP URLs and most URIs like s:opaque, better in fact than most things which claim to be URI parsers.

@param
const char* s
is value like /hi?x=y&z or http://a.example/hi#x
unsigned long n
is byte length and -1 implies strlen
struct Url* h
is assumed to be uninitialized
@return
char*
memory backing UrlView needing free (and h.params.p too)
@see URI Generic Syntax RFC3986 RFC2396
@see EncodeUrl()

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
const 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. If the signal delivery kills the process, this won't return. The signal mask of the current thread is used. If a signal handler exists, this shall return after it's been invoked.

This function is equivalent to:

select(0, 0, 0, 0, 0);
However this has a tinier footprint and better logging.
@return
int
-1 w/ errno set to EINTR
@see sigsuspend()
@norestart

pavgb

Averages packed 8-bit unsigned integers w/ rounding.

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

pavgw

Averages packed 16-bit unsigned integers w/ rounding.

@param
unsigned short* a
const unsigned short* b
const 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
const unsigned char* b
const unsigned char* c
@return
void
@mayalias

pcmpeqd

Compares signed 32-bit integers w/ equal to predicate.

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

pcmpeqw

Compares signed 16-bit integers w/ equal to predicate.

@param
short* a
const short* b
const 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
const char* b
const char* c
@return
void
@mayalias

pcmpgtd

Compares signed 32-bit integers w/ greater than predicate.

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

pcmpgtw

Compares signed 16-bit integers w/ greater than predicate.

@param
short* a
const short* b
const 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
const 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
unsigned int* a
const unsigned int* b
const unsigned 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
const short* b
const 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
const short* b
const short* c
@return
void
@note goes fast w/ ssse3 (intel c. 2004, amd c. 2011)
@mayalias

phsubd

Subtracts adjacent 32-bit integers.

@param
unsigned int* a
const unsigned int* b
const unsigned int* c
@return
void
@note goes fast w/ ssse3
@mayalias

phsubsw

Subtracts adjacent shorts w/ saturation.

@param
short* a
const short* b
const 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
const short* b
const 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
@raise EFAULT if pipefd is NULL or an invalid address
@raise EMFILE if RLIMIT_NOFILE is exceedde
@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 or O_DIRECT or O_NONBLOCK
@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
const unsigned char* b
const 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
const short* b
const short* c
@return
void
@mayalias

pmaxsw

Gets maximum of signed 16-bit integers.

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

pmaxub

Returns minimum of 8-bit unsigned integers.

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

pminsw

Gets minimum of signed 16-bit integers.

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

pminub

Returns minimum of 8-bit unsigned integers.

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

pmovmskb

Turns result of byte comparison into bitmask.

@param
const unsigned char* p
@return
unsigned int
@see pcmpeqb(), bsf(), etc.

pmulhrsw

Multiplies Q15 numbers.

@param
short* a
const short* b
const 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
const unsigned short* b
const unsigned short* c
@return
void
@mayalias

pmulhw

Multiplies 16-bit signed integers and stores high word.

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

pmulld

Multiplies 32-bit integers.

@param
unsigned int* a
const unsigned int* b
const unsigned int* c
@return
void
@see pmuludq()
@mayalias

pmullw

Multiplies 16-bit signed integers.

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

pmuludq

Multiplies 32-bit unsigned integers w/ promotion.

@param
unsigned long* a
const unsigned int* b
const unsigned int* c
@return
void
@see pmulld()
@mayalias

pochisq

@param
const double ax
const int df
@return
double

poll

Waits for something to happen on multiple file descriptors at once.

Warning: XNU has an inconsistency with other platforms. If you have pollfds with fd≥0 and none of the meaningful events flags are added e.g. POLLIN then XNU won't check for POLLNVAL. This matters because one of the use-cases for poll() is quickly checking for open files.

Note: Polling works best on Windows for sockets. We're able to poll input on named pipes. But for anything that isn't a socket, or pipe with POLLIN, (e.g. regular file) then POLLIN/POLLOUT are always set into revents if they're requested, provided they were opened with a mode that permits reading and/or writing.

Note: Windows has a limit of 64 file descriptors and ENOMEM with -1 is returned if that limit is exceeded. In practice the limit is not this low. For example, pollfds with fd<0 don't count. So the caller could flip the sign bit with a short timeout, to poll a larger set.

@param
struct pollfd* fds
unsigned long nfds
int timeout_ms
if 0 means don't wait and -1 means wait forever
@return
int
number of items fds whose revents field has been set to nonzero to describe its events, or 0 if the timeout elapsed, or -1 w/ errno
fds[𝑖].revents is always zero initializaed and then will be populated with POLL{IN,OUT,PRI,HUP,ERR,NVAL} if something was determined about the file descriptor
@asyncsignalsafe
@threadsafe
@norestart

popcnt

Returns number of bits set in integer.

@param
unsigned long x
@return
unsigned long

popen

Spawns subprocess and returns pipe stream.

@param
const char* cmdline
const char* mode
@return
struct FILE*
@see pclose()

por

Ors 128-bit integers.

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

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
void** pp
receives pointer, only on success
unsigned long alignment
must be 2-power multiple of sizeof(void *)
unsigned long bytes
is number of bytes to allocate
@return
int
return 0 or EINVAL or ENOMEM w/o setting errno
@see memalign()
@threadsafe

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

posix_spawn

Spawns process the POSIX way.

@param
int* pid
is non-NULL and will be set to child pid in parent
const char* path
of executable that is not PATH searched
char** file_actions
struct _posix_spawnattr* attrp
char** argv
char** envp
@return
int
0 on success or error number on failure

posix_spawn_file_actions_addclose

Add a close action to object.

@param
char** file_actions
int fildes
@return
int

posix_spawn_file_actions_adddup2

Add a dup2 action to object.

@param
char** file_actions
int fildes
int newfildes
@return
int

posix_spawn_file_actions_addopen

Add an open action to object.

@param
char** file_actions
int fildes
const char* path
int oflag
unsigned int mode
@return
int

posix_spawn_file_actions_destroy

Frees object storage and make invalid.

@param
char** file_actions
@return
int

posix_spawn_file_actions_init

Creates object with no actions.

@param
char** file_actions
@return
int

posix_spawnattr_destroy

@param
struct _posix_spawnattr* attr
@return
int

posix_spawnattr_getflags

@param
struct _posix_spawnattr* attr
short* flags
@return
int

posix_spawnattr_getpgroup

@param
struct _posix_spawnattr* attr
int* pgroup
@return
int

posix_spawnattr_getschedparam

@param
struct _posix_spawnattr* attr
struct posix_attr_schedparam* schedparam
@return
int

posix_spawnattr_getschedpolicy

@param
struct _posix_spawnattr* attr
int* schedpolicy
@return
int

posix_spawnattr_getsigdefault

@param
struct _posix_spawnattr* attr
struct posix_attr_sigdefault* sigdefault
@return
int

posix_spawnattr_getsigmask

@param
struct _posix_spawnattr* attr
struct posix_attr_sigdefault* sigmask
@return
int

posix_spawnattr_init

Initialize object with default values.

@param
struct _posix_spawnattr* attr
@return
int

posix_spawnattr_setflags

@param
struct _posix_spawnattr* attr
short flags
@return
int

posix_spawnattr_setpgroup

@param
struct _posix_spawnattr* attr
int pgroup
@return
int

posix_spawnattr_setschedparam

@param
struct _posix_spawnattr* attr
struct posix_attr_schedparam* schedparam
@return
int

posix_spawnattr_setschedpolicy

@param
struct _posix_spawnattr* attr
int schedpolicy
@return
int

posix_spawnattr_setsigdefault

@param
struct _posix_spawnattr* attr
struct posix_attr_sigdefault* sigdefault
@return
int

posix_spawnattr_setsigmask

@param
struct _posix_spawnattr* attr
struct posix_attr_sigdefault* sigmask
@return
int

posix_spawnp

Spawns process the POSIX way w/ PATH search.

@param
int* pid
is non-NULL and will be set to child pid in parent
const char* path
of executable is PATH searched unless it contains a slash
char** file_actions
struct posix_spawnattr_t* attrp
char** argv
char** envp
@return
int
0 on success or error number on failure

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

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

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

prctl

Tunes process on Linux.

@param
int operation
...
@return
int
@raise ENOSYS on non-Linux

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 with maximum generality.

@param
int fd
struct iovec* iov
int iovlen
long off
@return
long
number of bytes actually read, or -1 w/ errno
@asyncsignalsafe
@vforksafe

__print_maps

Prints memory mappings to stderr.

@return
void

__printargs

Prints lots of information about this process, e.g.

__printargs("");
This is called automatically in MODE=dbg if --strace is used.
@param
const char* prologue
needs to be a .rodata kprintf string
@return
void

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 text to stdout.

Cosmopolitan supports most of the standard formatting behaviors described by man 3 printf, in addition to the following

  • %jjd, %jjx, etc. are {,u}int128_t (cosmopolitan only)
  • %'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.
  • %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
const char* fmt
...
@return
int
@see __fmt() for intuitive reference documentation
@see {,v}{,s{,n},{,{,x}as},f,d}printf

PrintGarbage

Prints list of deferred operations on shadow stack.

@return
void

PrintGarbageNumeric

Prints list of deferred operations on shadow stack w/o symbols.

@param
struct FILE* f
@return
void

PrintMemoryIntervals

@param
int fd
struct _mmi* mm
@return
void

PrintSystemMappings

@param
int outfd
@return
void


program_invocation_name

Supplies argv[0] the GNU way.

If argv[0] isn't supplied, this value will be null.

@return
@see program_invocation_short_name
@see GetProgramExecutableName()

program_invocation_short_name

Supplies basename(argv[0]) The GNU Way.

If argv[0] isn't supplied, this value will be null.

@return
@see GetProgramExecutableName()
@see program_invocation_name

psadbw

Computes sum of absolute differences.

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

pselect

Does what poll() does except with bitset API.

This system call is supported on all platforms. It's like select() except that it atomically changes the sigprocmask() during the op.

@param
int nfds
struct fd_set* readfds
struct fd_set* writefds
struct fd_set* exceptfds
struct st_birthtim* timeout
struct sa_mask* sigmask
@return
int

pshufb

Shuffles and/or clears 8-bit integers.

@param
unsigned char* a
const unsigned char* b
const 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
const int* a
unsigned char m
@return
void
@mayalias

pshufhw

Shuffles lower half of word vector.

@param
short* b
const short* a
unsigned char m
@return
void
@mayalias

pshuflw

Shuffles lower half of word vector.

@param
short* b
const short* a
unsigned char m
@return
void
@mayalias

pshufw

Shuffles mmx vector.

@param
short* b
const short* a
unsigned char m
@return
void
@mayalias

psignb

Conditionally negates or zeroes signed bytes.

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

psignd

Conditionally negates or zeroes ints.

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

psignw

Conditionally negates or zeroes shorts.

@param
short* a
const short* b
const 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
const unsigned int* b
unsigned char c
@return
void
@note c needs to be a literal, asmconstexpr, or linkconstsym
@mayalias

pslldq

Shifts vector left by n bytes w/ zero-fill.

@param
unsigned char* b
receives output
const unsigned char* a
is input vector
unsigned long n
@return
void
@mayalias

pslldv

Multiplies ints by two power.

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

psllq

Multiplies longs by two power.

@param
unsigned long* a
const 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
const unsigned long* b
const unsigned long* c
@return
void
@mayalias

psllw

Multiplies shorts by two power.

@param
unsigned short* a
const 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
const unsigned short* b
const unsigned long* c
@return
void
@mayalias

psrad

Divides ints by two power.

@param
int* a
const 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
const int* b
const unsigned long* c
@return
void
@note arithmetic shift right will sign extend negatives
@mayalias

psraw

Divides shorts by two power.

@param
short* a
const 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
const short* b
const 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
const 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
const unsigned char* a
is input vector
unsigned long n
@return
void
@mayalias

psrldv

Divides ints by two power.

@param
unsigned int* a
const unsigned int* b
const 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
const 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
const unsigned long* b
const 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
const 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
const unsigned short* b
const unsigned long* c
@return
void
@note logical shift does not sign extend negatives
@mayalias

psubb

Subtracts 8-bit integers.

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

psubd

Subtracts 32-bit integers.

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

psubq

Subtracts 64-bit integers.

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

psubsb

Subtracts signed 8-bit integers w/ saturation.

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

psubsw

Subtracts signed 16-bit integers w/ saturation.

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

psubusb

Subtracts unsigned 8-bit integers w/ saturation.

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

psubusw

Subtracts unsigned 16-bit integers w/ saturation.

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

psubw

Subtracts 16-bit integers.

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

pthread_cancel

@param
unsigned long* thread
@return
int

pthread_getspecific

Gets value of TLS slot for current thread.

@param
unsigned int key
@return
void*

pthread_key_create

Allocates TLS slot.

@param
unsigned int* key
void(*)() dtor
@return
int

pthread_key_delete

Deletes TLS slot.

@param
unsigned int key
@return
int

pthread_mutex_destroy

Destroys mutex.

@param
struct pthread_mutex_t* mutex
@return
int
0 on success, or error number on failure

pthread_mutex_init

Initializes mutex.

@param
struct pthread_mutex_t* mutex
struct pthread_mutexattr_t* attr
may be NULL
@return
int
0 on success, or error number on failure

pthread_mutex_lock

Locks mutex.

_spinlock()         l:   181,570c    58,646ns
mutex normal        l:   297,965c    96,241ns
mutex recursive     l: 1,112,166c   359,223ns
mutex errorcheck    l: 1,449,723c   468,252ns
@param
struct pthread_mutex_t* mutex
@return
int
0 on success, or error number on failure

pthread_mutex_trylock

Tries to acquire mutex.

@param
struct pthread_mutex_t* mutex
@return
int

pthread_mutex_unlock

Releases mutex.

@param
struct pthread_mutex_t* mutex
@return
int
0 on success or error number on failure
@raises EPERM if in error check mode and not owned by caller

pthread_mutexattr_destroy

Destroys mutex attr.

@param
struct pthread_mutexattr_t* attr
@return
int
0 on success, or error number on failure

pthread_mutexattr_gettype

Gets mutex type.

@param
struct pthread_mutexattr_t* attr
int* type
will be set to one of these on success
  • PTHREAD_MUTEX_NORMAL
  • PTHREAD_MUTEX_DEFAULT
  • PTHREAD_MUTEX_RECURSIVE
  • PTHREAD_MUTEX_ERRORCHECK
@return
int
0 on success, or error on failure

pthread_mutexattr_init

Initializes mutex attr.

@param
struct pthread_mutexattr_t* attr
@return
int
0 on success, or error number on failure

pthread_mutexattr_settype

Sets mutex type.

@param
struct pthread_mutexattr_t* attr
int type
can be one of
  • PTHREAD_MUTEX_NORMAL
  • PTHREAD_MUTEX_DEFAULT
  • PTHREAD_MUTEX_RECURSIVE
  • PTHREAD_MUTEX_ERRORCHECK
@return
int
0 on success, or error on failure
@raises EINVAL if type is invalid

pthread_once

@param
int* once
void(*)() init
@return
int

pthread_setspecific

Sets value of TLS slot for current thread.

@param
unsigned int key
void* val
@return
int

ptrace

Traces process.

@param
int request
can be PTRACE_xxx
...
@return
long
@note de facto linux only atm
@vforksafe

ptsname

@param
int fd
@return
char*

ptsname_r

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

puff

@param
unsigned char* dest
unsigned long* destlen
const unsigned char* source
unsigned long* sourcelen
@return
int

punpckhbw

Interleaves high bytes.

@param
unsigned char* a
const unsigned char* b
const 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
const unsigned int* b
const unsigned int* c
@return
void
@mayalias

punpckhqdq

Interleaves high quadwords.

@param
unsigned long* a
const unsigned long* b
const 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
const unsigned short* b
const 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
const unsigned char* b
const 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
const unsigned int* b
const unsigned int* c
@return
void
@mayalias

punpcklqdq

Interleaves low quadwords.

@param
unsigned long* a
const unsigned long* b
const 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
const unsigned short* b
const unsigned short* c
@return
void
@mayalias

putc

Writes byte to stream.

@param
int c
is byte to buffer or write, which is masked
struct FILE* f
@return
int
c as unsigned char if written or -1 w/ errno
@threadsafe

putc_unlocked

Writes byte to stream.

@param
int c
is byte to buffer or write, which is masked
struct FILE* f
@return
int
c as unsigned char if written or -1 w/ errno

putchar

Writes byte to stdout.

@param
int c
@return
int
c (as unsigned char) if written or -1 w/ errno
@threadsafe

putchar_unlocked

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* s
@return
int
0 on success or non-zero on error
@see setenv(), getenv()

PutEnvImpl

@param
char* s
_Bool overwrite
@return
int

puts

Writes string w/ trailing newline to stdout.

@param
const char* s
@return
int
non-negative number on success, or EOF on error with errno set and the ferror(stdout) state is updated

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
int wc
struct FILE* f
@return
unsigned int
wc if written or -1 w/ errno
@threadsafe

putwc_unlocked

Writes wide character to stream.

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

putwchar

Writes wide character to stdout.

@param
int wc
@return
unsigned int
wc if written or -1 w/ errno
@threadsafe

putwchar_unlocked

Writes wide character to stdout.

@param
int wc
@return
unsigned int
wc if written or -1 w/ errno

pvalloc

Equivalent to memalign(PAGESIZE, ROUNDUP(n, PAGESIZE)).

@param
unsigned long n
number of bytes needed
@return
void*
memory address, or NULL w/ errno
@see valloc()
@threadsafe

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, which can exceed or overlap the end of file, in which case your file will be extended
@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* iov
int iovlen
long off
@return
long
number of bytes actually sent, or -1 w/ errno
@asyncsignalsafe
@vforksafe

pxor

Xors 128-bit integers.

@param
unsigned long* a
const unsigned long* b
const 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 longsort(), djbsort()

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()

quick_exit

Exits process faster.

@param
int exitcode
is masked with 255
@noreturn

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 linear congruential pseudorandom number, e.g.

int x = rand();
assert(x >= 0);
This function always returns a positive number. If srand() isn't called, then it'll return the same sequence each time your program runs. Faster and more modern alternatives exist to this function.

This function is not thread safe in the sense that multiple threads might simultaneously generate the same random values.

@return
int
@note this function does well on bigcrush and practrand
@note this function is not intended for cryptography
@see lemur64(), rand64(), rdrand()

rand64

Returns nondeterministic random data.

This function is similar to lemur64() except that it doesn't produce the same sequences of numbers each time your program is run. This is the case even across forks and threads, whose sequences will differ.

@return
unsigned long
@see rdseed(), rdrand(), rand(), random(), rngset()
@note this function takes 5 cycles (30 if __threaded)
@note this function is not intended for cryptography
@note this function passes bigcrush and practrand
@asyncsignalsafe
@threadsafe
@vforksafe

random

@return
long

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

Retrieves 64-bits of hardware random data from RDRAND instruction.

If RDRAND isn't available (we check CPUID and we also disable it automatically for microarchitectures where it's slow or buggy) then we try getrandom(), RtlGenRandom(), or sysctl(KERN_ARND). If those aren't available then we try /dev/urandom and if that fails, we try getauxval(AT_RANDOM), and if not we finally use RDTSC and getpid().

@return
unsigned long
@note this function could block a nontrivial time on old computers
@note this function is indeed intended for cryptography
@note this function takes around 300 cycles
@see rngset(), rdseed(), rand64()
@asyncsignalsafe
@vforksafe

rdrand_init

@param
int argc
char** argv
char** envp
long* auxv
@return
void

rdseed

Retrieves 64-bits of true random data from RDSEED instruction.

If RDSEED isn't available, we'll try RDRAND (which we automatically disable for microarchitectures where it's known to be slow or buggy). If RDRAND isn't available then we try getrandom(), RtlGenRandom(), or sysctl(KERN_ARND). If those aren't available then we try /dev/urandom and if that fails, we use RDTSC and getpid().

@return
unsigned long
@note this function could block a nontrivial time on old computers
@note this function is indeed intended for cryptography
@note this function takes around 800 cycles
@see rngset(), rdrand(), rand64()
@asyncsignalsafe
@vforksafe

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
@restartable

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
"\e[38;5;202m"    ORANGERED
"\e[A"            UP
"\e\e[A"          ALT-UP
"\001"            CTRL-ALFA
"\e\001"          ALT-CTRL-ALFA
"\eOP"            PF1
"\000"            NUL
"\e]rm -rf /\e\\" OSC
"\302\233A"       UP
"\300\200"        NUL
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.

@param
int fd
char* p
is guaranteed to receive a NUL terminator if n>0
unsigned long n
@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


readlinkat

Reads symbolic link.

This does *not* nul-terminate the buffer.

@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
const char* path
must be a symbolic link pathname
char* buf
will receive symbolic link contents, and won't be modified unless the function succeeds (with the exception of no-malloc nt) and this buffer will *not* be nul-terminated
unsigned long bufsiz
@return
long
number of bytes written to buf, or -1 w/ errno; if the return is equal to bufsiz then truncation may have occurred
@error EINVAL if path isn't a symbolic link
@asyncsignalsafe

readv

Reads data to multiple buffers.

This is the same thing as read() except it has multiple buffers. This yields a performance boost in situations where it'd be expensive to stitch data together using memcpy() or issuing multiple syscalls. This wrapper is implemented so that readv() calls where iovlen<2 may be passed to the kernel as read() instead. This yields a 100 cycle performance boost in the case of a single small iovec.

@param
int fd
struct iovec* iov
int iovlen
@return
long
number of bytes actually read, or -1 w/ errno
@restartable

_real1

Generates number on [0,1]-real-interval, e.g.

double x = _real1(lemur64())
@param
unsigned long x
@return
double
@see lemur64(), mt19937()

_real2

Generates number on [0,1)-real-interval, e.g.

double x = _real2(lemur64())
@param
unsigned long x
@return
double
@see lemur64(), mt19937()

_real3

Generates number on (0,1)-real-interval, e.g.

double x = _real3(lemur64())
@param
unsigned long x
@return
double
@see lemur64(), mt19937()

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()
@threadsafe

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()
@threadsafe

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
@threadsafe

realpath

Returns absolute pathname.

This function removes /./ and /../ components. IF the path is a symbolic link then it's resolved.

@param
const char* filename
char* resolved
needs PATH_MAX bytes or NULL to use malloc()
@return
char*
resolved or NULL w/ errno

reboot

Reboots system.

The howto argument may be one of the following:

  • RB_AUTOBOOT
  • RB_POWER_OFF
  • RB_HALT_SYSTEM
  • RB_SW_SUSPEND (linux and windows only)
  • RB_KEXEC (linux only)
  • RB_ENABLE_CAD (linux only)
  • RB_DISABLE_CAD (linux only)
There's an implicit sync() operation before the reboot happens. This can be prevented by or'ing howto with RB_NOSYNC. Setting this option will also prevent apps on Windows from having time to close themselves.
@param
int howto
@return
int

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
@restartable (unless SO_RCVTIMEO)

recvfrom

Receives data from network.

This function blocks unless MSG_DONTWAIT is passed.

@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
unsigned int flags
can have MSG_{WAITALL,DONTROUTE,PEEK,OOB}, etc.
void* opt_out_srcaddr
receives the binary ip:port of the data's origin
unsigned int* opt_inout_srcaddrsize
is srcaddr capacity which gets updated
@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
@restartable (unless SO_RCVTIMEO)

recvmsg

Sends a message from a socket.

@param
int fd
is the file descriptor returned by socket()
struct msg2* msg
is a pointer to a struct msghdr containing all the allocated
   buffers where to store incoming data.
int flags
MSG_OOB, MSG_DONTROUTE, MSG_PARTIAL, MSG_NOSIGNAL, etc.
@return
long
number of bytes received, or -1 w/ errno
@error EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable), EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
@asyncsignalsafe
@restartable (unless SO_RCVTIMEO)

RefreshTime

@return
void

regcomp

Compiles regular expression, e.g.

regex_t rx;
CHECK_EQ(REG_OK, regcomp(&rx, "^[A-Za-z]{2}$", REG_EXTENDED));
CHECK_EQ(REG_OK, regexec(&rx, "→A", 0, NULL, 0));
regfree(&rx);
@param
struct regex_t* preg
points to caller allocated memory that's used to store your regular expression. This memory needn't be initialized. If this function succeeds, then preg must be passed to regfree() later on, to free its associated resources
const char* regex
is utf-8 regular expression nul-terminated 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()
const 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().

The same object may be destroyed by regfree() multiple times, in which case subsequent calls do nothing. Once a regex is freed, it may be passed to regcomp() to reinitialize it.

@param
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

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
const char* name
@return
int
0 on success or -1 w/ errno
@see unlink() and rmdir() which this abstracts

RemoveDirectory

Deletes existing empty directory on the New Technology.

@param
const unsigned short* lpPathName
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

remquo

Computes remainder and part of quotient.

@param
double x
double y
int* quo
@return
double

remquof

Computes remainder and part of quotient.

@param
float x
float y
int* quo
@return
float

remquol

Computes remainder and part of quotient.

@param
long double x
long double y
int* quo
@return
long double

rename

Moves file the Unix way.

This is generally an atomic operation with the file system, since all it's doing is changing a name associated with an inode. However, that means rename() doesn't permit your oldpathname and newpathname to be on separate file systems, in which case this returns EXDEV. That's also the case on Windows.

@param
const char* oldpathname
const char* newpathname
@return
int
0 on success or -1 w/ errno
@asyncsignalsafe

renameat

Renames files relative to directories.

This is generally an atomic operation with the file system, since all it's doing is changing a name associated with an inode. However, that means rename() doesn't permit your oldpathname and newpathname to be on separate file systems, in which case this returns EXDEV. That's also the case on Windows.

@param
int olddirfd
is normally AT_FDCWD but if it's an open directory and oldpath is relative, then oldpath become relative to dirfd
const 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
const char* newpath
@return
int
0 on success, or -1 w/ errno

ReOpenFile

Reopens file on the New Technology.

@param
long hOriginalFile
unsigned int dwDesiredAccess
unsigned int dwShareMode
unsigned int dwFlagsAndAttributes
@return
long
handle, or -1 on failure
@note this wrapper takes care of ABI, STRACE(), and __winerr()

replacestr

Replaces all instances of NEEDLE in S with REPLACEMENT.

@param
const char* s
const char* needle
can't be empty
const 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
const char* path
is NULL propagating
@return
char*
must be free()'d

__replmode

Controls ANSI prefix for log emissions.

This should be true in raw tty mode repls.

@type
char
@see kprintf(), vflogf(), linenoise()

__reservefd

Finds open file descriptor slot.

@param
int start
@return
int
@asyncsignalsafe
@threadsafe

__reservefd_unlocked

Finds open file descriptor slot.

@param
int start
@return
int
@asyncsignalsafe

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
const char* name
can be a local or fully-qualified hostname
struct sa* 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

ResolveDnsReverse

Performs reverse DNS lookup with IP address.

@param
struct ResolvConf* resolvconf
can be GetResolvConf()
int af
can be AF_INET, AF_UNSPEC
const char* name
is a reversed IP address string ending with .in-addr.arpa
char* buf
to store the obtained hostname if any
unsigned long bufsize
is size of buf
@return
int
0 on success, or -1 w/ errno
@error EAFNOSUPPORT, ENETDOWN, ENAMETOOLONG, EBADMSG

ResolveHostsReverse

Finds name associated with address in HOSTS.TXT table.

@param
struct HostsTxt* ht
can be GetHostsTxt()
int af
can be AF_INET
const unsigned char* ip
is IP address in binary (sin_addr)
char* buf
is buffer to store the name
unsigned long bufsize
is length of buf
@return
int
1 if found, 0 if not found, or -1 w/ errno
@error EAFNOSUPPORT

ResolveHostsTxt

Finds address associated with name in HOSTS.TXT table.

@param
struct HostsTxt* ht
can be GetHostsTxt()
int af
can be AF_INET, AF_UNSPEC
const 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
const char** canon
be used to return a pointer to the canonical name
@return
int
number of matches found, or -1 w/ errno
@error EAFNOSUPPORT


__restorewintty

Puts cmd.exe gui back the way it was.

@return
void

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* f
@return
void

rewinddir

Seeks to beginning of directory stream.

@param
struct dirstream* dir
@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

Thirteen byte decompressor.

@param
di
points to output buffer
si
points to uint8_t {len₁,byte₁}, ..., {0,0}
@return
@mode long,legacy,real

rldecode2

@param
void* d
struct RlDecode* r
@return
void

rmdir

Deletes empty directory.

@param
const char* path
@return
int
0 on success or -1 w/ errno on error

rmrf

Recursively removes file or directory.

@param
const char* path
@return
int

rngset

Fills memory with random bytes, e.g.

char buf[512];
rngset(buf, sizeof(buf), 0, 0);
If reseed is zero then the internal PRNG is disabled and bytes are simply copied in little-endian order from the seed function. If seed is NULL then the reseed parameter is used as the seed value for the internal PRNG. If seed!=NULL and reseed>8 then reseed is the number of bytes after which the seed() function should be called again, to freshen up the PRNG.

The main advantage of this generator is that it produces data at 13 gigabytes per second since Vigna's Algorithm vectorizes better than alternatives, going even faster than xorshift.

@param
void* b
unsigned long n
unsigned long(*)() seed
unsigned long reseed
@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,𝑥))

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

__sample_pids

Returns handles of windows pids being tracked.

We return 64 at most because Windows can't await on a larger number of things at the same time. If we have a lot of subprocesses, then we choose a subgroup to monitor at random.

@param
int* pids
long* handles
_Bool exploratory
@return
int
number of items returned in pids and handles

_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
double x
long n
@return
double

scalblnf

Returns 𝑥 × 2ʸ.

@param
float x
long n
@return
float

scalblnl

Returns 𝑥 × 2ʸ.

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

scalbn

Returns 𝑥 × 2ʸ.

@param
double x
int n
@return
double

scalbnf

Returns 𝑥 × 2ʸ.

@param
float x
int n
@return
float

scalbnl

Returns 𝑥 × 2ʸ.

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

scanf

Standard input decoder.

@param
const char* fmt
...
@return
int
@see libc/fmt/vcscanf.h

sched_get_priority_max

Returns maximum sched_param::sched_priority for policy.

@param
int policy
@return
int
priority, or -1 w/ errno
@raise ENOSYS on XNU, Windows, OpenBSD
@raise EINVAL if policy is invalid

sched_get_priority_min

Returns minimum sched_param::sched_priority for policy.

@param
int policy
@return
int
priority, or -1 w/ errno
@raise ENOSYS on XNU, Windows, OpenBSD
@raise EINVAL if policy is invalid

sched_getaffinity

Gets kernel scheduling for particular CPUs.

@param
int tid
unsigned long size
is byte length of bitset
void* bitset
receives bitset and should be uint64_t[16] in order to work on older versions of Linux
@return
int
0 on success, or -1 w/ errno
@raise ENOSYS on non-Linux

sched_getparam

Gets scheduler policy parameter.

@param
int pid
struct sched_param* param
@return
int
0 on success, or -1 w/ errno
@raise ENOSYS on XNU, Windows

sched_getscheduler

Gets scheduler policy for pid.

@param
int pid
is the id of the process whose scheduling policy should be queried. Setting pid to zero means the same thing as getpid(). This applies to all threads associated with the process. Linux is special; the kernel treats this as a thread id (noting that getpid() == gettid() is always the case on Linux for the main thread) and will only take effect for the specified tid. Therefore this function is POSIX-compliant iif !__threaded.
@return
int
scheduler policy, or -1 w/ errno
@error ESRCH if pid not found
@error EPERM if not permitted
@error EINVAL if pid is negative on Linux

sched_rr_get_interval

Returns round-robin SCHED_RR quantum for pid.

@param
int pid
is id of process (where 0 is same as getpid())
struct st_birthtim* tp
receives output interval
@return
int
0 on success, or -1 w/ errno
@error ENOSYS if not Linux or FreeBSD
@error EFAULT if tp memory is invalid
@error EINVAL if invalid pid
@error ESRCH if could not find pid

sched_setaffinity

Asks kernel to only schedule process on particular CPUs.

@param
int tid
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
@raise ENOSYS if not Linux or Windows

sched_setparam

Sets scheduler policy parameter.

@param
int pid
struct sched_param* param
@return
int
@raise ENOSYS on XNU, Windows

sched_setscheduler

Sets scheduling policy of process, e.g.

struct sched_param p = {sched_get_priority_max(SCHED_OTHER)};
LOGIFNEG1(sched_setscheduler(0, SCHED_OTHER, &p));
Processes with numerically higher priority values are scheduled before processes with numerically lower priority values.
@param
int pid
is the id of the process whose scheduling policy should be changed. Setting pid to zero means the same thing as getpid(). This applies to all threads associated with the process. Linux is special; the kernel treats this as a thread id (noting that getpid() == gettid() is always the case on Linux for the main thread) and will only take effect for the specified tid. Therefore this function is POSIX-compliant iif !__threaded.
int policy
specifies the kernel's timesharing strategy.

The policy must have one of:

  • SCHED_OTHER (or SCHED_NORMAL) for the default policy
  • SCHED_RR for real-time round-robin scheduling
  • SCHED_FIFO for real-time first-in first-out scheduling
  • SCHED_BATCH for "batch" style execution of processes if supported (Linux), otherwise it's treated as SCHED_OTHER
  • SCHED_IDLE for running very low priority background jobs if it's supported (Linux), otherwise this is SCHED_OTHER. Pledging away scheduling privilege is permanent for your process; if a subsequent attempt is made to restore the SCHED_OTHER policy then this system call will EPERM (but on older kernels like RHEL7 this isn't the case). This policy isn't available on old Linux kernels like RHEL5, where it'll raise EINVAL.
The policy may optionally bitwise-or any one of:

  • SCHED_RESET_ON_FORK will cause the scheduling policy to be automatically reset to SCHED_NORMAL upon fork() if supported; otherwise this flag is polyfilled as zero, so that it may be safely used (without having to check if the o/s is Linux).
struct sched_param* param
must be set to the scheduler parameter, which should be greater than or equal to sched_get_priority_min(policy) and less than or equal to sched_get_priority_max(policy). Linux allows the static priority range 1 to 99 for the SCHED_FIFO and SCHED_RR policies, and the priority 0 is used for the remaining policies. You should still consider calling the function, because on NetBSD the correct priority might be -1.
@return
int
the former scheduling policy of the specified process. If this function fails, then the scheduling policy is not changed, and -1 w/ errno is returned.
@raise ENOSYS on XNU, Windows, OpenBSD
@raise EPERM if not authorized to use scheduler in question (e.g. trying to use a real-time scheduler as non-root on Linux) or possibly because pledge() was used and isn't allowing this
@raise EINVAL if param is NULL
@raise EINVAL if policy is invalid
@raise EINVAL if param has value out of ranges defined by policy

sched_yield

Asks kernel to let other threads be scheduled.

@return
0 on success, or non-zero on failure
@norestart

seccomp

Tunes Linux security policy.

This system call was first introduced in Linux 3.17. We polyfill automatically features like SECCOMP_SET_MODE_STRICT, for kernels dating back to 2.6.23, whenever possible.

@param
unsigned int operation
unsigned int flags
void* args
@return
int
@raise ENOSYS on non-Linux.

seekdir

Seeks in directory stream.

@param
struct dirstream* dir
long off
@return
void

select

Does what poll() does except with bitset API.

This system call is supported on all platforms. However, on Windows, this is polyfilled to translate into poll(). So it's recommended that poll() be used instead.

@param
int nfds
struct fd_set* readfds
struct fd_set* writefds
struct fd_set* exceptfds
ANONYMOUS-STRUCT* timeout
@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
@restartable (unless SO_RCVTIMEO)

sendfile

Transfers data from file to network.

@param
int outfd
needs to be a socket
int infd
needs to be a file
long* inout_opt_inoffset
may be specified for pread()-like behavior
unsigned long uptobytes
is usually the number of bytes remaining in file; it can't exceed INT_MAX-1; some platforms block until everything's sent, whereas others won't; zero isn't allowed
@return
long
number of bytes transmitted which may be fewer than requested
@see copy_file_range() for file ↔ file
@see splice() for fd ↔ pipe

sendmsg

Sends a message on a socket.

@param
int fd
is the file descriptor returned by socket()
struct msghdr* msg
is a pointer to a struct msghdr containing all the required
   parameters (the destination address, buffers, ...)
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
@restartable (unless SO_RCVTIMEO)

sendto

Sends data over network.

This function blocks unless MSG_DONTWAIT is passed. In that case, the non-error EWOULDBLOCK might be returned. It basically means we didn't wait around to learn an amount of bytes were written that we know in advance are guaranteed to be atomic.

@param
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
unsigned int flags
MSG_OOB, MSG_DONTROUTE, MSG_PARTIAL, MSG_NOSIGNAL, etc.
void* opt_addr
is a binary ip:port destination override, which is mandatory for UDP if connect() wasn't called
unsigned int addrsize
is the byte-length of addr's true polymorphic form
@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
@restartable (unless SO_RCVTIMEO)

SerializeDnsHeader

Serializes DNS message h to wire.

@param
unsigned char* p
struct DnsHeader* h
@return
void
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 DnsQuestion* 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
may optionally be non-NULL to set the stream's underlying buffer, which the stream will own, but won't free
unsigned long size
is ignored if buf is NULL
@return
void

setcontext

Sets machine state.

@return
@note please use longerjmp() and setlongerjmp() for fibers
@note currently only sets general registers
@see getcontext()

SetCurrentDirectory

Sets current directory.

@param
const unsigned short* lpPathName
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

setegid

Sets effective group ID.

@param
unsigned int egid
@return
int
0 on success, or -1 w/ errno
@raise EINVAL if euid not in legal range
@raise EPERM if lack privileges

setenv

Copies variable to environment.

@param
const char* name
const char* value
int overwrite
@return
int
0 on success, or -1 w/ errno
@see putenv(), getenv()

seteuid

Sets effective user ID.

@param
unsigned int euid
@return
int
0 on success, or -1 w/ errno
@raise EINVAL if euid not in legal range
@raise EPERM if lack privileges

setfsgid

Sets user id of current process for file system ops.

@param
int gid
@return
int
previous filesystem gid

setfsuid

Sets user id of current process for file system ops.

@param
int uid
@return
int
previous filesystem uid

setgid

Sets group id of current process.

@param
int gid
@return
int
0 on success, or -1 w/ errno
@raise EINVAL if gid not in legal range
@raise EPERM if lack privileges

setgrent

@return
void

sethostent

@param
int stayopen
@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.

Timers are not inherited across fork.

@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* 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()

setkey

@param
const char* key
@return
void

setlinebuf

Puts stream in line-buffering mode.

@param
struct FILE* f
@return
void

setlocale

Sets program locale.

Cosmopolitan only supports the C or POSIX locale.

@param
int category
const char* locale
@return
char*

setlogmask

Sets log priority mask

Modifies the log priority mask that determines which calls to syslog() may be logged. Log priority values are LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, and LOG_DEBUG.

@param
int maskpri
@return
int
the previous log priority mask
@asyncsignalsafe

setlongerjmp

Saves caller CPU state to cacheline.

@param
rdi
points to jmp_buf
@return
eax contains 0 when set, and 1 if jumped
rdx contains value passed to longerjmp()
@returnstwice

setnetent

@param
int stayopen
@return
void

setpgid

Changes process group for process.

@param
int pid
int pgid
@return
int
@vforksafe

setpgrp

Sets the process group ID.

@return
int

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
0 on success or -1 w/ errno
@error EACCES if lower that RLIMIT_NICE
@error EACCES on Linux without CAP_SYS_NICE
@see getpriority(), nice()

setprotoent

@param
int stayopen
@return
void

setpwent

@return
void

setregid

Sets real and/or effective group ids.

@param
unsigned int rgid
is real group id or -1 to leave it unchanged
unsigned int egid
is effective group id or -1 to leave it unchanged
@return
int
0 on success or -1 w/ errno

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 setresuid(), getauxval(AT_SECURE)
@raise ENOSYS on Windows NT

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 setresgid(), getauxval(AT_SECURE)
@raise ENOSYS on Windows NT

setreuid

Sets real and/or effective user ids.

@param
unsigned int ruid
is real user id or -1 to leave it unchanged
unsigned int euid
is effective user id or -1 to leave it unchanged
@return
int
0 on success or -1 w/ errno

setrlimit

Sets resource limit for current process.

The following resources are recommended:

  • RLIMIT_AS limits the size of the virtual address space. This will work on all platforms. It's emulated on XNU and Windows which means it won't propagate across execve() currently.
  • RLIMIT_CPU causes SIGXCPU to be sent to the process when the soft limit on CPU time is exceeded, and the process is destroyed when the hard limit is exceeded. It works everywhere but Windows where it should be possible to poll getrusage() with setitimer()
  • RLIMIT_FSIZE causes SIGXFSZ to sent to the process when the soft limit on file size is exceeded and the process is destroyed when the hard limit is exceeded. It works everywhere but Windows
  • RLIMIT_NPROC limits the number of simultaneous processes and it should work on all platforms except Windows. Please be advised it limits the process, with respect to the activities of the user id as a whole.
  • RLIMIT_NOFILE limits the number of open file descriptors and it should work on all platforms except Windows (TODO)
The rlimit magnums differ for each platform but occupy the interval zero through RLIM_NLIMITS. Usually they're set to RLIM_INFINITY which is -1 on Linux/Windows, and LONG_MAX on BSDs. In any case they're both very large numbers under the Cosmopolitan unsigned ABI because struct rlimit uses uint64_t. The special magnum 127 is used for constant values that aren't supported by the host platform.
@param
int resource
struct rlimit* rlim
specifies new resource limit
@return
int
0 on success or -1 w/ errno
@see libc/sysv/consts.sh
@vforksafe

setservent

@param
int stayopen
@return
void

setsid

Creates session and sets the process group id.

@return
int
new session id, or -1 w/ errno

setsockopt

Modifies socket settings.

This function is the ultimate rabbit hole. Basic usage:

int yes = 1; setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes));

@param
int fd
int level
can be SOL_SOCKET, SOL_IP, SOL_TCP, etc.
int optname
can be SO_{REUSE{PORT,ADDR},KEEPALIVE,etc.} etc.
void* optval
unsigned int optlen
@return
int
0 on success, or -1 w/ errno
@error ENOPROTOOPT for unknown (level,optname)
@error EINVAL if optlen is invalid somehow
@error ENOTSOCK if fd is valid but not a socket
@error EBADF if fd isn't valid
@error EFAULT if optval memory isn't valid
@see libc/sysv/consts.sh for tuning catalogue
@see getsockopt()

_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

setstate

@param
char* state
@return
char*

setuid

Sets user id of current process.

@param
int uid
@return
int
0 on success, or -1 w/ errno
@raise EINVAL if uid not in legal range
@raise EAGAIN on temporary failure
@raise EAGAIN change would cause RLIMIT_NPROC to be exceeded
@raise EPERM if lack privileges

SetUp

User-defined test setup function.

The test runner will call this function before each TEST() if it's defined by the linkage.

@return
void

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 caller still owns and won't free, otherwise the existing buffer is used
int mode
may be _IOFBF, _IOLBF, or _IONBF
unsigned long size
is ignored if buf is NULL
@return
int
0 on success or -1 on error

sha1_transform_avx2

Performs Intel® AVX2™ optimized SHA-1 update.

This implementation is based on the previous SSSE3 release: Visit http://software.intel.com/en-us/articles/ and refer to improving-the-performance-of-the-secure-hash-algorithm-1/

Updates 20-byte SHA-1 record at start of 'state', from 'input', for even number of 'blocks' consecutive 64-byte blocks.

void sha1_transform_avx2(struct sha1_state *state,
                         const uint8_t *input,
                         int blocks);
@param
%rdi
points to output digest
%rsi
points to input data
%rdx
is number of 64-byte blocks to process
@return
@see X86_HAVE(SHA)

sha1_transform_ni

Performs Intel® SHA-NI™ optimized SHA-1 update.

The function takes a pointer to the current hash values, a pointer to the input data, and a number of 64 byte blocks to process. Once all blocks have been processed, the digest pointer is updated with the resulting hash value. The function only processes complete blocks, there is no functionality to store partial blocks. All message padding and hash value initialization must be done outside the update function.

The indented lines in the loop are instructions related to rounds processing. The non-indented lines are instructions related to the message schedule.

void sha1_transform_ni(uint32_t digest[static 5],
                       const void *data,
                       uint32_t numBlocks);
@param
%rdi
points to output digest
%rsi
points to input data
%rdx
is number of 64-byte blocks to process
@return
@see X86_HAVE(SHA)

sha256_transform_ni

Performs Intel® SHA-NI™ optimized SHA-256 update.

The function takes a pointer to the current hash values, a pointer to the input data, and a number of 64 byte blocks to process. Once all blocks have been processed, the digest pointer is updated with the resulting hash value. The function only processes complete blocks, there is no functionality to store partial blocks. All message padding and hash value initialization must be done outside the update function.

The indented lines in the loop are instructions related to rounds processing. The non-indented lines are instructions related to the message schedule.

void sha256_transform_ni(uint32_t digest[static 8],
                         const void *data,
                         int32_t numBlocks);
@param
%rdi
points to output digest
%rsi
points to input data
%rdx
is number of blocks to process
@return
@see X86_HAVE(SHA)

ShowBacktrace

@param
int fd
struct StackFrame* bp
@return
void

ShowCrashReport

@param
int err
int sig
struct siginfo_t* si
struct ucontext_t* ctx
@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
const double* b
const double* a
unsigned char m
@return
void
@mayalias

shufps

Shuffles float vector.

@param
float* c
const float* b
const float* a
unsigned char m
@return
void
@mayalias

shutdown

Disables sends or receives on a socket, without closing.

@param
int fd
is the open file descriptor for the socket
int how
can be SHUT_RD, SHUT_WR, or SHUT_RDWR
@return
int
0 on success or -1 on error
@asyncsignalsafe

__sig_add

Enqueues generic signal for delivery on New Technology.

@param
int sig
int si_code
@return
int
0 on success, otherwise -1 w/ errno
@threadsafe

__sig_check

Enqueues generic signal for delivery on New Technology.

@param
_Bool restartable
is for functions like read() but not poll()
@return
_Bool
true if EINTR should be returned by caller
@note called from main thread
@threadsafe

__sig_handle

Handles signal.

@param
_Bool restartable
can be used to suppress true return if SA_RESTART
int sig
int si_code
struct ucontext_t* ctx
@return
_Bool
true if signal was delivered

__sig_mask

Changes signal mask for main thread.

@param
int how
struct mask* neu
struct mask* old
@return
int
0 on success, or -1 w/ errno

__sig_raise

Handles signal immediately if not blocked.

@param
int sig
int si_code
@return
int
true if EINTR should be returned by caller
1 if delivered, 0 if enqueued, otherwise -1 w/ errno
@note called from main thread
@threadsafe

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));
The following flags are supported across platforms:

  • SA_SIGINFO: Causes the siginfo_t and ucontext_t parameters to be passed. This not only gives you more information about the signal, but also allows your signal handler to change the CPU registers. That's useful for recovering from crashes. If you don't use this attribute, then signal delivery will go a little faster.
  • SA_RESTART: Enables BSD signal handling semantics. Normally i/o entrypoints check for pending signals to deliver. If one gets delivered during an i/o call, the normal behavior is to cancel the i/o operation and return -1 with EINTR in errno. If you use the SA_RESTART flag then that behavior changes, so that any function that's been annotated with @restartable will not return EINTR and will instead resume the i/o operation. This makes coding easier but it can be an anti-pattern if not used carefully, since poor usage can easily result in latency issues. It also requires one to do more work in signal handlers, so special care needs to be given to which C library functions are @asyncsignalsafe.
  • SA_RESETHAND: Causes signal handler to be single-shot. This means that, upon entry of delivery to a signal handler, it's reset to the SIG_DFL handler automatically. You may use the alias SA_ONESHOT for this flag, which means the same thing.
  • SA_NODEFER: Disables the reentrancy safety check on your signal handler. Normally that's a good thing, since for instance if your SIGSEGV signal handler happens to segfault, you're going to want your process to just crash rather than looping endlessly. But in some cases it's desirable to use SA_NODEFER instead, such as at times when you wish to longjmp() out of your signal handler and back into your program. This is only safe to do across platforms for non-crashing signals such as SIGCHLD and SIGINT. Crash handlers should use Xed instead to recover execution, because on Windows a SIGSEGV or SIGTRAP crash handler might happen on a separate stack and/or a separate thread. You may use the alias SA_NOMASK for this flag, which means the same thing.
  • SA_NOCLDWAIT: Changes SIGCHLD so the zombie is gone and you can't call wait() anymore; similar but may still deliver the SIGCHLD.
  • SA_NOCLDSTOP: Lets you set SIGCHLD handler that's only notified on exit/termination and not notified on SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU, or SIGCONT.
Here's an example of the most professional way to handle signals in an i/o event loop. It's generally a best practice to have signal handlers do the fewest number of things possible. The trick is to have your signals work hand-in-glove with the EINTR errno. This obfuscates the need for having to worry about @asyncsignalsafe.

static volatile bool gotctrlc;

void OnCtrlC(int sig) {
  gotctrlc = true;
}

int main() {
  size_t got;
  ssize_t rc;
  char buf[1];
  struct sigaction oldint;
  struct sigaction saint = {.sa_handler = GotCtrlC};
  if (sigaction(SIGINT, &saint, &oldint) == -1) {
    perror("sigaction");
    exit(1);
  }
  for (;;) {
    rc = read(0, buf, sizeof(buf));
    if (rc == -1) {
      if (errno == EINTR) {
        if (gotctrlc) {
          break;
        }
      } else {
        perror("read");
        exit(2);
      }
    }
    if (!(got = rc)) {
      break;
    }
    for (;;) {
      rc = write(1, buf, got);
      if (rc != -1) {
        assert(rc == 1);
        break;
      } else if (errno != EINTR) {
        perror("write");
        exit(3);
      }
    }
  }
  sigaction(SIGINT, &oldint, 0);
}
Please note that you can't do the above if you use SA_RESTART. Since the purpose of SA_RESTART is to restart i/o operations whose docs say that they're @restartable and read() is one such function. Here's some even better news: if you don't install any signal handlers at all, then your i/o calls will never be interrupted!

Here's an example of the most professional way to recover from SIGSEGV, SIGFPE, and SIGILL.

void ContinueOnCrash(void);

void SkipOverFaultingInstruction(struct ucontext *ctx) {
  struct XedDecodedInst xedd;
  xed_decoded_inst_zero_set_mode(&xedd, XED_MACHINE_MODE_LONG_64);
  xed_instruction_length_decode(&xedd, (void *)ctx->uc_mcontext.rip, 15);
  ctx->uc_mcontext.rip += xedd.length;
}

void OnCrash(int sig, struct siginfo *si, struct ucontext *ctx) {
  SkipOverFaultingInstruction(ctx);
  ContinueOnCrash();  // reinstall here in case *rip faults
}

void ContinueOnCrash(void) {
  struct sigaction sa = {.sa_handler = OnSigSegv,
                         .sa_flags = SA_SIGINFO | SA_RESETHAND};
  sigaction(SIGSEGV, &sa, 0);
  sigaction(SIGFPE, &sa, 0);
  sigaction(SIGILL, &sa, 0);
}

int main() {
  ContinueOnCrash();
  // ...
}
You may also edit any other CPU registers during the handler. For example, you can use the above technique so that division by zero becomes defined to a specific value of your choosing!

Please note that Xed isn't needed to recover from SIGTRAP which can be raised at any time by embedding DebugBreak() or asm("int3") in your program code. Your signal handler will automatically skip over the interrupt instruction, assuming your signal handler returns.

The important signals supported across all platforms are:

  • SIGINT: When you press Ctrl-C this signal gets broadcasted to your process session group. This is the normal way to terminate console applications.
  • SIGQUIT: When you press CTRL-\ this signal gets broadcasted to your process session group. This is the irregular way to kill an application in cases where maybe your SIGINT handler is broken although, Cosmopolitan Libc ShowCrashReports() should program it such as to attach a debugger to the process if possible, or else show a crash report. Also note that in New Technology you should press CTRL+BREAK rather than CTRL+\ to get this signal.
  • SIGHUP: This gets sent to your non-daemon processes when you close your terminal session.
  • SIGTERM is what the kill command sends by default. It's the choice signal for terminating daemons.
  • SIGUSR1 and SIGUSR2 can be anything you want. Their default action is to kill the process. By convention SIGUSR1 is usually used by daemons to reload the config file.
  • SIGCHLD is sent when a process terminates and it takes a certain degree of UNIX mastery to address sanely.
  • SIGALRM is invoked by setitimer() and alarm(). It can be useful for interrupting i/o operations like connect().
  • SIGTRAP: This happens when an INT3 instruction is encountered.
  • SIGILL happens on illegal instructions, e.g. UD2.
  • SIGABRT happens when you call abort().
  • SIGFPE happens when you divide ints by zero, among other things.
  • SIGSEGV and SIGBUS indicate memory access errors and they have inconsistent semantics across platforms like FreeBSD.
  • SIGWINCH is sent when your terminal window is resized.
  • SIGXCPU and SIGXFSZ may be raised if you run out of resources, which can happen if your process, or the parent process that spawned your process, happened to call setrlimit(). Doing this is a wonderful idea.
@param
int sig
struct copy* act
struct copy* oldact
@return
int
0 on success or -1 w/ errno
@see xsigaction() for a much better api
@asyncsignalsafe
@vforksafe

sigaddset

Adds signal to set.

@param
struct sigset_t* set
int sig
@return
int
0 on success, or -1 w/ errno
@raises EINVAL if 1 ≤ sig ≤ NSIG isn't the case
@asyncsignalsafe

sigaltstack

Sets and/or gets alternate signal stack, e.g.

struct sigaction sa;
struct sigaltstack ss;
ss.ss_flags = 0;
ss.ss_size = GetStackSize();
ss.ss_sp = mmap(0, GetStackSize(), PROT_READ | PROT_WRITE,
                MAP_STACK | MAP_ANONYMOUS, -1, 0);
sa.sa_flags = SA_ONSTACK;
sa.sa_handler = OnStackOverflow;
__cxa_atexit(free, ss[0].ss_sp, 0);
sigemptyset(&sa.ss_mask);
sigaltstack(&ss, 0);
sigaction(SIGSEGV, &sa, 0);
It's strongly recommended that you allocate a stack with the same size as GetStackSize() and that it have GetStackSize() alignment. Otherwise some of your runtime support code (e.g. ftrace stack use logging, kprintf() memory safety) won't be able to work as well.
@param
struct uc_stack* neu
if non-null will install new signal alt stack
struct uc_stack* old
if non-null will receive current signal alt stack
@return
int
0 on success, or -1 w/ errno

sigdelset

Removes signal from set.

@param
struct sigset_t* set
int sig
@return
int
0 on success, or -1 w/ errno
@raises EINVAL if 1 ≤ sig ≤ NSIG isn't the case
@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
@vforksafe

sigignore

Configures process to ignore signal.

@param
int sig
@return
int

siginterrupt

Tunes whether signal can interrupt restartable system calls.

@param
int sig
int flag
@return
int

sigismember

Returns true if signal is member of set.

@param
struct sigset_t* set
int sig
@return
int
1 if set, 0 if not set, or -1 w/ errno
@raises EINVAL if 1 ≤ sig ≤ NSIG isn't the case
@asyncsignalsafe
@vforksafe

signal

Installs kernel interrupt handler, e.g.

void GotCtrlC(int sig) { ... }
CHECK_NE(SIG_ERR, signal(SIGINT, GotCtrlC));
@param
int sig
void(*)() func
@return
void(*)()
old signal handler on success or SIG_ERR w/ errno
@note this function has BSD semantics, i.e. SA_RESTART
@see sigaction() which has more features and docs

sigprocmask

Changes signal blocking state of calling thread, e.g.:

sigset_t neu,old;
sigfillset(&neu);
sigprocmask(SIG_BLOCK, &neu, &old);
sigprocmask(SIG_SETMASK, &old, NULL);
@param
int how
can be SIG_BLOCK (U), SIG_UNBLOCK (/), SIG_SETMASK (=)
struct sa_mask* opt_set
struct old* opt_out_oldset
@return
int
0 on success, or -1 w/ errno
@asyncsignalsafe
@restartable
@vforksafe

sigqueue

Sends signal to process, with data.

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 checks both if pid exists and we can signal it
union value value
@return
int
0 if something was accomplished, or -1 w/ errno
@note this isn't supported on OpenBSD
@asyncsignalsafe

sigsuspend

Blocks until SIG ∉ MASK is delivered to process.

This temporarily replaces the signal mask until a signal that it doesn't contain is delivered.

@param
struct sa_mask* ignore
is a bitset of signals to block temporarily, which if NULL is equivalent to passing an empty signal set
@return
int
-1 w/ EINTR (or possibly EFAULT)
@asyncsignalsafe
@norestart

sin

Returns sine of 𝑥.

@param
double x
@return
double
@note should take ~5ns

sincos

Returns sine and cosine of 𝑥.

@param
double x
double* sin
double* cos
@return
void
@note should take ~10ns

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

sinh

Returns hyperbolic sine of 𝑥.

sinh(x) = (exp(x) - 1/exp(x))/2
        = (exp(x)-1 + (exp(x)-1)/exp(x))/2
        = x + x^3/6 + o(x^5)
@param
double x
@return
double

sinhf

Returns hyperbolic sine of 𝑥.

sinh(x) = (exp(x) - 1/exp(x))/2
        = (exp(x)-1 + (exp(x)-1)/exp(x))/2
        = x + x^3/6 + o(x^5)
@param
float x
@return
float

sinhl

Returns hyperbolic sine of 𝑥.

sinh(x) = (exp(x) - 1/exp(x))/2
        = (exp(x)-1 + (exp(x)-1)/exp(x))/2
        = x + x^3/6 + o(x^5)
@param
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

sizetol

Converts size string to long.

The following unit suffixes may be used

  • k or K for kilo (multiply by 𝑏¹)
  • m or M for mega (multiply by 𝑏²)
  • g or G for giga (multiply by 𝑏³)
  • t or T for tera (multiply by 𝑏⁴)
  • p or P for peta (multiply by 𝑏⁵)
  • e or E for exa (multiply by 𝑏⁶)
If a permitted alpha character is supplied, then any additional characters after it (e.g. kbit, Mibit, TiB) are ignored. Spaces before the integer are ignored, and overflows will be detected.
@param
const char* s
is non-null nul-terminated input string
long b
is multiplier which should be 1000 or 1024
@return
long
size greater than or equal 0 or -1 on error

sleb128

Encodes signed leb128 integer.

@param
char* p
__int128 x
@return
char*

sleb64

Encodes signed integer to array.

uleb64 INT64_MAX    l:        10𝑐         3𝑛𝑠
zleb64 INT64_MAX    l:        13𝑐         4𝑛𝑠
sleb64 INT64_MAX    l:        16𝑐         5𝑛𝑠
uleb128 INT64_MAX   l:        18𝑐         6𝑛𝑠
zleb128 INT64_MAX   l:        18𝑐         6𝑛𝑠
sleb128 INT64_MAX   l:        24𝑐         8𝑛𝑠
zleb64 INT64_MIN    l:        13𝑐         4𝑛𝑠
sleb64 INT64_MIN    l:        16𝑐         5𝑛𝑠
zleb128 INT64_MIN   l:        19𝑐         6𝑛𝑠
sleb128 INT64_MIN   l:        24𝑐         8𝑛𝑠
@param
char* p
is output array
long x
is number
@return
char*
p + i

sleep

Sleeps for particular number of seconds.

@param
unsigned int seconds
@return
unsigned int
0 if the full time elapsed, otherwise we assume an interrupt was delivered, in which case the errno condition is ignored, and this function shall return the number of unslept seconds rounded using the ceiling function
@see nanosleep(), usleep()
@asyncsignalsafe
@norestart

_smt19937

Initializes mt[NN] with small seed value.

@param
unsigned long seed
@return
void
@see mt19937(), Smt19937()

_Smt19937

Initializes mt[NN] with array.

@param
unsigned long* K
is the array for initializing keys
unsigned long n
is its length
@return
void
@see mt19937(), smt19937()

snprintf

Formats string to buffer.

@param
char* buf
unsigned long count
const 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 __fmt() and printf() for detailed documentation
@asyncsignalsafe
@vforksafe

sockaddr2bsd

Converts sockaddr (Linux/Windows) → sockaddr_bsd (XNU/BSD).

@param
void* addr
unsigned int addrsize
union sockaddr_storage_bsd* out_addr
unsigned int* out_addrsize
@return
int

sockaddr2linux

Converts sockaddr_bsd (XNU/BSD) → sockaddr (Linux/Windows).

@param
union sockaddr_storage_bsd* addr
unsigned int addrsize
union sockaddr_storage_linux* out_addr
unsigned int* inout_addrsize
@return
void

socket

Creates new system resource for network communication, e.g.

int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
@param
int family
can be AF_UNIX, AF_INET, etc.
int type
can be SOCK_STREAM (for TCP), SOCK_DGRAM (e.g. UDP), or SOCK_RAW (IP) so long as IP_HDRINCL was passed to setsockopt(); and additionally, may be or'd with SOCK_NONBLOCK, SOCK_CLOEXEC
int protocol
can be IPPROTO_TCP, IPPROTO_UDP, or IPPROTO_ICMP
@return
int
socket file descriptor or -1 w/ errno
@error ENETDOWN, EPFNOSUPPORT, etc.
@see libc/sysv/consts.sh
@asyncsignalsafe

socketpair

Creates bidirectional pipe, e.g.

int sv[2];
socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
@param
int family
should be AF_UNIX or synonymously AF_LOCAL
int type
can be SOCK_STREAM or SOCK_DGRAM and additionally, may be or'd with SOCK_NONBLOCK, SOCK_CLOEXEC
int protocol
int* sv
a vector of 2 integers to store the created sockets
@return
int
0 if success, -1 in case of error
@error EFAULT, EPFNOSUPPORT, etc.
@see libc/sysv/consts.sh
@asyncsignalsafe

_spawn

Spawns thread, e.g.

int worker(void *arg, int tid) {
  const char *s = arg;
  printf("%s\n", s);
  return 0;
}

int main() {
  struct spawn th;
  _spawn(worker, "hi", &th);
  _join(&th);
}
@param
int(*)() fun
is thread worker callback, which receives arg and ctid
void* arg
shall be passed to fun
struct ths* opt_out_thread
needn't be initialiized and is always clobbered except when it isn't specified, in which case, the thread is kind of detached and will (currently) just leak the stack / tls memory
@return
int
0 on success, or -1 w/ errno

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
const char* fmt
...
@return
int
@see __fmt() 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

srandom

@param
unsigned int seed
@return
void

sscanf

String decoder.

@param
const char* str
const char* fmt
...
@return
int
@see libc/fmt/vcscanf.h (for docs and implementation)

__start_fatal

Prints initial part of fatal message.

@param
const char* file
int line
@return
void
@note this is support code for __check_fail(), __assert_fail(), etc.

startswith

Returns true if s has prefix.

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

startswith16

Returns true if s has prefix.

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

startswithi

@param
const char* s
const char* prefix
@return
_Bool

stat

Returns information about thing.

@param
const char* path
struct stat* st
is where result is stored
@return
int
@see S_ISDIR(st.st_mode), S_ISREG(), etc.
@raise EACCES if denied access to component in path prefix
@raise EIO if i/o error occurred while reading from filesystem
@raise ELOOP if a symbolic link loop exists in path
@raise ENAMETOOLONG if a component in path exceeds NAME_MAX
@raise ENOENT on empty string or if component in path doesn't exist
@raise ENOTDIR if a parent component existed that wasn't a directory
@raise EOVERFLOW shouldn't be possible on 64-bit systems
@raise ELOOP may ahappen if SYMLOOP_MAX symlinks were dereferenced
@raise ENAMETOOLONG may happen if path exceeded PATH_MAX
@asyncsignalsafe

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
const 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
const char* src
unsigned long stride
@return
char*
dest + stride
@see stncpy(), memccpy()
@asyncsignalsafe

__strace

System call logging enabled state.

If Cosmopolitan was compiled with the SYSDEBUG macro (this is the default behavior, except in tiny and release modes) then __strace shall control whether or not system calls are logged to fd 2. If it's greater than zero, syscalls are logged. Otherwise, they're aren't.

By convention, functions wishing to disable syscall tracing for a short time period should say:

void foo() {
  --__strace;
  bar();
  ++__strace;
}
This way you still have some flexibility to force syscall tracing, by setting __strace to a higher number like 2 or 200. Even though under normal circumstances, __strace should only be either zero or one.
@type
_Atomic int

__strace_init

Enables plaintext system call logging if --strace flag is passed.

@param
int argc
char** argv
char** envp
long* auxv
@return
int

strcasecmp

Compares NUL-terminated strings ascii case-insensitively.

@param
const char* a
is first non-null nul-terminated string pointer
const char* b
is second non-null nul-terminated string pointer
@return
int
is <0, 0, or >0 based on tolower(uint8_t) comparison
@asyncsignalsafe

strcasecmp16

Compares NUL-terminated UCS-2 strings case-insensitively.

@param
const unsigned short* l
const unsigned short* r
@return
int
is <0, 0, or >0 based on uint16_t comparison
@asyncsignalsafe

strcasecmp16to8

@param
const unsigned short* s1
const char* s2
@return
int

strcasecmp8to16

Compares UTF-8 and UTF-16 strings, ignoring case.

@param
const char* s1
const unsigned short* s2
@return
int

strcat

Appends 𝑠 to 𝑑.

@param
char* d
const char* s
@return
char*
𝑑
@asyncsignalsafe

strcat16

Appends 𝑠 to 𝑑.

@param
unsigned short* d
const unsigned short* s
@return
unsigned short*
𝑑
@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

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
const char* s
@return
unsigned long

strclen16

Returns number of characters in UTF-16 or UCS-2 string.

@param
const unsigned short* s
@return
unsigned long

strcmp

Compares NUL-terminated strings.

@param
const char* a
is first non-null NUL-terminated string pointer
const 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
const unsigned short* l
const unsigned short* r
@return
int
is <0, 0, or >0 based on uint16_t comparison
@asyncsignalsafe

strcmp16to8

@param
const unsigned short* s1
const char* s2
@return
int

strcmp8to16

Compares UTF-8 and UTF-16 strings.

@param
const char* s1
const unsigned short* s2
@return
int

strcoll

Compares strings in the C locale.

@param
const char* p
const char* q
@return
int

strcoll_l

@param
const char* p
const char* q
struct __locale_struct* l
@return
int

strcpy

Copies bytes from 𝑠 to 𝑑 until a NUL is encountered.

@param
char* d
const 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
const 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. a.k.a. Return index of first byte that's in charset.

@param
const char* s
const char* reject
is nul-terminated character set
@return
unsigned long
@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
const unsigned short* s
const unsigned short* reject
is nul-terminated character set
@return
unsigned long
@see strspn(), strtok_r()
@asyncsignalsafe

strdup

Allocates new copy of string.

@param
const char* s
is a NUL-terminated byte string
@return
char*
new string or NULL w/ errno
@error ENOMEM
@threadsafe

strerdoc

Converts errno value to descriptive sentence.

@param
int x
@return
char*
non-null rodata string or null if not found

strerrno

Converts errno value to symbolic name.

@param
int x
@return
char*
non-null rodata string or null if not found

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
is error number or zero if unknown
char* buf
unsigned long size
@return
int
0 on success, or error code

strerror_wr

Converts errno value to string with explicit windows errno too.

@param
int err
is error number or zero if unknown
unsigned int winerr
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 maxsize
const char* format
struct tm_1* t
@return
unsigned long
bytes copied excluding nul, or 0 on error
@see FormatHttpDateTime()

strftime_l

@param
char* s
unsigned long maxsize
const char* format
struct tm_1* t
struct __locale_struct* locale
@return
unsigned long

stripext

Removes file extension.

@param
char* s
is mutated
@return
char*
s

stripexts

Removes file extensions.

@param
char* s
is mutated
@return
char*
s

strlcat

Appends string SRC to DEST, the BSD way.

@param
char* dest
is a buffer holding a NUL-terminated string
const 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
const 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
const char* s
is non-null NUL-terminated string pointer
@return
unsigned long
number of bytes (excluding NUL)
@asyncsignalsafe

strlen16

Returns length of NUL-terminated utf-16 string.

@param
const unsigned short* s
is non-null NUL-terminated string pointer
@return
unsigned long
number of shorts (excluding NUL)
@asyncsignalsafe

strncasecmp

Compares NUL-terminated strings case-insensitively w/ limit.

@param
const char* a
is first non-null NUL-terminated string pointer
const 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
const unsigned short* a
is first non-null NUL-terminated char16 string pointer
const 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
const unsigned short* s1
const char* s2
unsigned long n
@return
int

strncasecmp8to16

Compares UTF-8 and UTF-16 strings, ignoring case, with limit.

@param
const char* s1
const unsigned short* s2
unsigned long n
@return
int

strncat

Appends at most 𝑛 bytes from 𝑠 to 𝑑.

@param
char* d
const char* s
unsigned long n
@return
char*
𝑑
@note 𝑑 and 𝑠 can't overlap
@asyncsignaslenafe

strncat16

Appends at most 𝑛 shorts from 𝑠 to 𝑑.

@param
unsigned short* d
const unsigned short* s
unsigned long n
@return
unsigned short*
𝑑
@note 𝑑 and 𝑠 can't overlap
@asyncsignaslenafe

strnclen

@param
const char* s
unsigned long n
@return
unsigned long

strnclen16

@param
const unsigned short* p
unsigned long n
@return
unsigned long

strncmp

Compares NUL-terminated strings w/ limit.

@param
const char* a
is first non-null NUL-terminated string pointer
const 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
const unsigned short* a
is first non-null NUL-terminated char16 string pointer
const 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
const unsigned short* s1
const char* s2
unsigned long n
@return
int

strncmp8to16

Compares UTF-8 and UTF-16 strings, with limit.

@param
const char* s1
const 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.

Here's an example of the only use case we know of for strncpy:

static const struct People {
  char name[8];
  int age;
} kPeople[] = {
    {"alice", 29},  //
    {"bob", 42},    //
};

int GetAge(const char *name) {
  char k[8];
  int m, l, r;
  l = 0;
  r = ARRAYLEN(kPeople) - 1;
  strncpy(k, name, 8);
  while (l <= r) {
    m = (l + r) >> 1;
    if (READ64BE(kPeople[m].name) < READ64BE(k)) {
      l = m + 1;
    } else if (READ64BE(kPeople[m].name) > READ64BE(k)) {
      r = m - 1;
    } else {
      return kPeople[m].age;
    }
  }
  return -1;
}
@param
char* dest
const char* src
unsigned long stride
@return
char*
dest
@see stpncpy(), memccpy()
@asyncsignalsafe

strndup

Allocates new copy of string, with byte limit.

@param
const 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
@threadsafe

strnlen

Returns length of NUL-terminated string w/ limit.

@param
const char* s
is string
unsigned long n
is max length
@return
unsigned long
byte length
@asyncsignalsafe

strnlen16

Returns length of NUL-terminated 16-bit string w/ limit.

@param
const unsigned short* s
is utf16 string pointer
unsigned long n
is max length in shorts
@return
unsigned long
number of shorts
@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... securely.

This is like strnlen() except it'll return 0 if s is null. We also make the assumption for the purposes of ASAN that n is the size of the buffer if s is non-null.

@param
const char* s
is string
unsigned long n
is max length
@return
unsigned long
byte length
@asyncsignalsafe

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
const 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
const unsigned short* p
unsigned long n
unsigned long o
@return
int

strpbrk

Returns pointer to first byte matching any in accept, or NULL.

@param
const char* s
const char* accept
@return
char*
@asyncsignalsafe

strpbrk16

Returns pointer to first byte matching any in accept, or NULL.

@param
const unsigned short* s
const unsigned short* accept
@return
unsigned short*
@asyncsignalsafe

strptime

@param
const char* s
const char* f
struct tm* tm
@return
char*

strrchr

Searches for last instance of character in string.

@param
const 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
const 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

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
const 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 string describing signal code.

This returns SIGZERO for 0 which is the empty value. Textual names should be available for signals 1 through 32. Signals in the range 33 and 128 are returned as a SIG%03d string. Everything else is SIGWUT

This function is thread safe when sig is a known signal magnum. Otherwise a pointer to static memory is returned which is unsafe.

@param
int sig
is signal number which should be in range 1 through 128
@return
char*
pointer to static memory that mutates on subsequent calls
@see sigaction()
@threadsafe

strspn

Returns prefix length, consisting of chars in accept.

@param
const char* s
const 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
const unsigned short* s
const unsigned short* accept
is nul-terminated character set
@return
unsigned long
@see strcspn(), strtok_r()
@asyncsignalsafe

strstr16

Searches for substring.

@param
const unsigned short* haystack
is the search area, as a NUL-terminated string
const 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
const char* s00
char** se
@return
double

strtod_l

@param
const char* s
char** endptr
struct __locale_struct* l
@return
double

strtodg

@param
const char* s00
char** se
struct FPI* fpi
int* exp
unsigned int* bits
@return
int

strtodI

@param
const char* s
char** sp
double* dd
@return
int

strtof

@param
const char* s
char** sp
@return
float

strtof_l

@param
const char* s
char** sp
struct __locale_struct* l
@return
float

strtoi128

Decodes 128-bit signed integer from ASCII string.

@param
const 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
decoded saturated integer
@see strtou128()

strtoId

@param
const char* s
char** sp
double* f0
double* f1
@return
int

strtoIdd

@param
const char* s
char** sp
double* f0
double* f1
@return
int

strtoIf

@param
const char* s
char** sp
float* f0
float* f1
@return
int

strtoimax

Decodes intmax_t from ASCII string.

@param
const 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
long
decoded saturated integer
@see strtoumax()

strtoIx

@param
const 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
const 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
const 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

Decodes signed integer from ASCII string.

atoi 10⁸              22𝑐         7𝑛𝑠
strtol 10⁸            37𝑐        12𝑛𝑠
strtoul 10⁸           35𝑐        11𝑛𝑠
wcstol 10⁸            30𝑐        10𝑛𝑠
wcstoul 10⁸           30𝑐        10𝑛𝑠
strtoimax 10⁸         80𝑐        26𝑛𝑠
strtoumax 10⁸         78𝑐        25𝑛𝑠
wcstoimax 10⁸         77𝑐        25𝑛𝑠
wcstoumax 10⁸         76𝑐        25𝑛𝑠
@param
const 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
long
the decoded signed saturated number

strtold

Converts string to long double.

@param
const char* s
char** endptr
@return
long double

strtold_l

Converts string to long double.

@param
const char* s
char** endptr
struct __locale_struct* l
@return
long double

strtoll

Decodes signed integer from ASCII string.

@param
const 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
long
decoded signed saturated integer

strtoll_l

@param
const char* nptr
char** endptr
int base
struct __locale_struct* l
@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
const char* nptr
long minval
long maxval
const char** errstr
@return
long

strtopd

@param
const char* s
char** sp
double* d
@return
int

strtopdd

@param
const char* s
char** sp
double* dd
@return
int

strtopf

@param
const char* s
char** sp
float* f
@return
int

strtopx

@param
const char* s
char** sp
void* V
@return
int

strtord

@param
const char* s
char** sp
int rounding
double* d
@return
int

strtordd

@param
const char* s
char** sp
int rounding
double* dd
@return
int

strtorf

@param
const char* s
char** sp
int rounding
float* f
@return
int

strtorx

@param
const char* s
char** sp
int rounding
void* L
@return
int

strtou128

Decodes 128-bit unsigned integer from ASCII string.

@param
const 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
unsigned __int128
decoded integer mod 2¹²⁸ negated if leading -
@see strtoi128()

strtoul

Decodes unsigned integer from ASCII string.

@param
const 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
unsigned long
decoded integer mod 2⁶⁴ negated if leading -

strtoull

Decodes unsigned integer from ASCII string.

@param
const 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
unsigned long
decoded integer mod 2⁶⁴ negated if leading -

strtoull_l

@param
const char* nptr
char** endptr
int base
struct __locale_struct* l
@return
unsigned long

strtoumax

Decodes uintmax_t from ASCII string.

@param
const 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
unsigned long
decoded integer mod 2¹²⁸ negated if leading -
@see strtoimax()

strtoupper

Mutates string to ASCII uppercase.

@param
char* s
@return
char*
string
@praam s is string

strverscmp

Compares two version strings.

@param
const char* l0
const 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
const 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
const unsigned short* s
unsigned long o
@return
int

strxfrm

Transforms strings into current C locale. calling strcmp() on two strxfrm()-ed strings is same as calling strcoll() on the originals.

@param
char* dest
is buffer which needn't be initialized
const char* src
is a NUL-terminated string
unsigned long count
is number of bytes to write to destination
@return
unsigned long
length of transformed string
@note dest and src can't overlap
@note dest array size should be greater than count
@note if dest is NULL, count has to be zero

strxfrm_l

@param
char* dest
const char* src
unsigned long count
struct __locale_struct* l
@return
unsigned long

__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

svigna

Seeds vigna() pseudorandom number generator.

@param
unsigned long seed
@return
void
@see vigna(), vigna_r()

swprintf

@param
int* ws
unsigned long n
const int* format
...
@return
int


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
const char* target
can be relative and needn't exist
int newdirfd
const char* linkpath
is what gets created
@return
int
0 on success, or -1 w/ errno
@raise EPERM if a non-admin on Windows NT tries to use this
@asyncsignalsafe

sync

Flushes file system changes to disk by any means necessary.

@return
void
@see __nosync to secretly disable

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_accept

@param
int server
void* addr
unsigned int* addrsize
@return
int

sys_accept4

@param
int server
void* addr
unsigned int* addrsize
int flags
@return
int

sys_accept_nt

@param
struct Fd* fd
void* addr
unsigned int* addrsize
int flags
@return
int

sys_bind

@param
int fd
void* addr
unsigned int addrsize
@return
int

sys_bind_nt

@param
struct Fd* fd
void* addr
unsigned int addrsize
@return
int

sys_chdir_nt

@param
const char* path
@return
int

sys_clock_gettime_mono

@param
struct res* ts
@return
int

sys_clock_gettime_nt

@param
int clock
ANONYMOUS-STRUCT* ts
@return
int

sys_clock_gettime_xnu

@param
int clock
struct st_birthtim* ts
@return
int

sys_clone_linux

Invokes clone() system call on GNU/Systemd.

@param
rdi
is flags
rsi
is top of stack
rdx
is ptid
rcx
is ctid
r8
is tls
r9
is func(void*,int)→int
8(rsp)
is arg
@return
tid of child on success, or -1 w/ errno

sys_close_epoll_nt

@param
int fd
@return
int

sys_close_nt

@param
struct Fd* fd
@return
int

sys_closesocket_nt

Closes socket on Windows.

This function should only be called by close().

@param
struct Fd* fd
@return
int

sys_connect

@param
int fd
void* addr
unsigned int addrsize
@return
int

sys_connect_nt

@param
struct Fd* fd
void* addr
unsigned int addrsize
@return
int

sys_dup3

@param
int oldfd
int newfd
int flags
@return
int

sys_dup_nt

Implements dup(), dup2(), dup3(), and F_DUPFD for Windows.

@param
int oldfd
int newfd
int flags
int start
@return
int

sys_execve

@param
const char* prog
char** argv
char** envp
@return
int

sys_execve_nt

@param
const char* program
char** argv
char** envp
@return
int

sys_faccessat_nt

@param
int dirfd
const 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_fchmodat_nt

@param
int dirfd
const char* path
unsigned int mode
int flags
@return
int

sys_fcntl

@param
int fd
int cmd
unsigned long arg
@return
int

sys_fcntl_nt

@param
int fd
int cmd
unsigned long 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 cosmo* st
@return
int
@asyncsignalsafe

sys_fstat_metal

@param
int fd
struct cosmo* 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
const char* path
struct cosmo* st
int flags
@return
int
@asyncsignalsafe

sys_fstatat_nt

@param
int dirfd
const char* path
struct cosmo* st
int flags
@return
int

sys_ftruncate_nt

@param
long handle
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_getloadavg_nt

@param
double* a
int n
@return
int

sys_getpeername

@param
int fd
void* out_addr
unsigned int* out_addrsize
@return
int

sys_getpeername_nt

@param
struct Fd* fd
void* out_addr
unsigned int* out_addrsize
@return
int


sys_getpriority_nt

@param
int ignored
@return
int

sys_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

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_getsockname

@param
int fd
void* out_addr
unsigned int* out_addrsize
@return
int

sys_getsockname_nt

@param
struct Fd* fd
void* out_addr
unsigned int* out_addrsize
@return
int

sys_getsockopt_nt

@param
struct Fd* fd
int level
int optname
void* out_opt_optval
unsigned int* inout_optlen
@return
int


sys_gettimeofday_metal

@param
struct ru_stime* tv
struct timezone* tz
void* wut
@return
struct axdx_t

sys_gettimeofday_nt

@param
ANONYMOUS-STRUCT* tv
struct timezone* tz
void* wut
@return
struct axdx_t

sys_gettimeofday_xnu

@param
struct ru_stime* tv
struct timezone* tz
void* wut
@return
struct ad

sys_isatty_metal

@param
int fd
@return
int

sys_isatty_nt

@param
int fd
@return
int

sys_kill_nt

@param
int pid
int sig
@return
int

sys_linkat_nt

@param
int olddirfd
const char* oldpath
int newdirfd
const char* newpath
@return
int

sys_listen_nt

@param
struct Fd* fd
int backlog
@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
const 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 d
@asyncsignalsafe
@threadsafe

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
int fd
long off
@return
struct dm

sys_mprotect_nt

@param
void* addr
unsigned long size
int prot
@return
int

sys_msync_nt

@param
char* addr
unsigned long size
int flags
@return
int

sys_munmap

Unmaps memory directly with system.

This function bypasses memtrack. Therefore it won't work on Windows, but it works on everything else including bare metal.

@param
void* p
unsigned long n
@return
int
@asyncsignalsafe
@threadsafe

sys_munmap_metal

@param
void* addr
unsigned long size
@return
int

sys_nanosleep_nt

@param
struct st_birthtim* req
struct elapsed* rem
@return
int

sys_nanosleep_xnu

@param
ANONYMOUS-STRUCT* req
struct elapsed* rem
@return
int

sys_open_nt

@param
int dirfd
const char* file
unsigned int flags
int mode
@return
int

sys_openat

@param
int dirfd
const char* file
int flags
unsigned int mode
@return
int

sys_openat_metal

@param
int dirfd
const 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_poll_metal

@param
struct pollfd* fds
unsigned long nfds
unsigned int timeout_ms
@return
int

sys_poll_nt

Polls on the New Technology.

This function is used to implement poll() and select(). You may poll on both sockets and files at the same time. We also poll for signals while poll is polling.

@param
struct pollfd* fds
unsigned long nfds
unsigned long* ms
@return
int

sys_read_nt

@param
struct Fd* fd
struct iovec* iov
unsigned long iovlen
long opt_offset
@return
long

sys_readlinkat_nt

@param
int dirfd
const char* path
char* buf
unsigned long bufsiz
@return
long

sys_readv_metal

@param
struct Fd* fd
struct iovec* iov
int iovlen
@return
long

sys_readv_nt

@param
struct Fd* fd
struct iovec* iov
int iovlen
@return
long

sys_readv_serial

@param
struct Fd* fd
struct iovec* iov
int iovlen
@return
long

sys_recv_nt

Performs stream socket receive on New Technology.

@param
struct Fd* fd
must be a socket
struct iovec* iov
unsigned long iovlen
unsigned int flags
@return
long
number of bytes received, or -1 w/ errno

sys_recvfrom_nt

Performs datagram receive on New Technology.

@param
struct Fd* fd
must be a socket
struct iovec* iov
unsigned long iovlen
unsigned int flags
void* opt_out_srcaddr
unsigned int* opt_inout_srcaddrsize
@return
long
number of bytes received, or -1 w/ errno

sys_renameat_nt

@param
int olddirfd
const char* oldpath
int newdirfd
const char* newpath
@return
int


sys_send_nt

Performs stream socket send on the New Technology.

@param
int fd
must be a socket
struct iovec* iov
unsigned long iovlen
unsigned int flags
@return
long
number of bytes handed off, or -1 w/ errno

sys_sendto_nt

Performs datagram socket send on the New Technology.

@param
int fd
must be a socket
struct iovec* iov
unsigned long iovlen
unsigned int flags
void* opt_in_addr
unsigned int in_addrsize
@return
long
number of bytes handed off, or -1 w/ errno

sys_setitimer_nt

@param
int which
struct itimerval* newvalue
struct itimerval* out_opt_oldvalue
@return
int

sys_setpriority_nt

@param
int nice
@return
int

sys_setsockopt_nt

@param
struct Fd* fd
int level
int optname
void* optval
unsigned int optlen
@return
int

sys_shutdown_nt

@param
struct Fd* fd
int how
@return
int

sys_sigprocmask

@param
int how
struct uc_sigmask* opt_set
struct old* opt_out_oldset
@return
int

sys_socket

@param
int family
int type
int protocol
@return
int

sys_socket_nt

@param
int family
int type
int protocol
@return
int

sys_socketpair

@param
int family
int type
int protocol
int* sv
@return
int

sys_socketpair_nt

@param
int family
int type
int proto
int* sv
@return
int

sys_symlinkat_nt

@param
const char* target
int newdirfd
const 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
const char* path
unsigned long length
@return
int

sys_unlinkat_nt

@param
int dirfd
const char* path
int flags
@return
int

sys_unveil_linux

@param
const char* path
const char* permissions
@return
int

sys_utimensat

@param
int dirfd
const char* path
ANONYMOUS-STRUCT* ts
int flags
@return
int

sys_utimensat_nt

@param
int dirfd
const char* path
ANONYMOUS-STRUCT* ts
int flags
@return
int

sys_utimensat_xnu

@param
int dirfd
const char* path
ANONYMOUS-STRUCT* ts
int flags
@return
int

sys_utimes_nt

@param
const char* path
struct ru_stime* tv
@return
int

sys_wait4

@param
int pid
int* opt_out_wstatus
int options
struct rusage* opt_out_rusage
@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
int fd
struct iovec* iov
unsigned long iovlen
long opt_offset
@return
long

sys_writev_metal

@param
struct Fd* fd
struct iovec* iov
int iovlen
@return
long

sys_writev_nt

@param
int fd
struct iovec* iov
int iovlen
@return
long

sys_writev_serial

@param
struct Fd* 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

__syscall__

Invokes SYSCALL for libfatal forceinline asm() routines.

@param
rax
is ordinal
rdi
is arg1
rsi
is arg2
rdx
is arg3
rcx
is arg4
r8
is arg5
r9
is arg6
rsp
may contain more args
@return
rdx:rax where rax holds -errno on error
@clob rax,rdx,memory,cc

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.

The following parameters are supported:

  • _SC_CLK_TCK returns number of clock ticks per second
  • _SC_ARG_MAX currently always returns 32768 due to Windows
  • _SC_PAGESIZE currently always returns 65536 due to Windows
  • _SC_NPROCESSORS_ONLN returns number of CPUs in the system
  • _SC_OPEN_MAX returns maximum number of open files
  • _SC_CHILD_MAX returns maximum number of processes
@param
int name
@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

syslog

Generates a log message which will be distributed by syslogd

Note: no errors are reported if an error occurred while logging

  the message.
@param
int priority
is a bitmask containing the facility value and the level value. If no facility value is ORed into priority, then the default value set by openlog() is used. it set to NULL, the program name is used. Level is one of LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG
const char* message
the message formatted using the same rules as printf()
...
@return
void
@asyncsignalsafe

system

Launches program with system command interpreter.

@param
const 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
const 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 x.

@param
double x
@return
double

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

tanh(x) = (exp(x) - exp(-x))/(exp(x) + exp(-x))
        = (exp(2*x) - 1)/(exp(2*x) - 1 + 2)
        = (1 - exp(-2*x))/(exp(-2*x) - 1 + 2)
@param
double x
@return
double

tanhf

Returns hyperbolic tangent of 𝑥.

tanh(x) = (exp(x) - exp(-x))/(exp(x) + exp(-x))
        = (exp(2*x) - 1)/(exp(2*x) - 1 + 2)
        = (1 - exp(-2*x))/(exp(-2*x) - 1 + 2)
@param
float x
@return
float

tanhl

Returns hyperbolic tangent of 𝑥.

tanh(x) = (exp(x) - exp(-x))/(exp(x) + exp(-x))
        = (exp(2*x) - 1)/(exp(2*x) - 1 + 2)
        = (1 - exp(-2*x))/(exp(-2*x) - 1 + 2)
@param
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
const 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|)

tcdrain

@param
int fd
@return
int

tcflow

Changes flow of teletypewriter data.

  • TCOOFF suspends output
  • TCOON resumes output
  • TCIOFF transmits a STOP character
  • TCION transmits a START character
@param
int fd
int action
@return
int

tcflush

Flushes teletypewriter data.

  • TCIFLUSH flushes data received but not read
  • TCOFLUSH flushes data written but not transmitted
  • TCIOFLUSH does both TCOFLUSH and TCIFLUSH
@param
int fd
int queue
@return
int

tcgetattr

Obtains the termios struct.

Here are the general defaults you can expect across platforms:

c_iflag        = ICRNL IXON
c_oflag        = OPOST ONLCR NL0 CR0 TAB0 BS0 VT0 FF0
c_cflag        = ISIG CREAD CS8
c_lflag        = ISIG ICANON ECHO ECHOE ECHOK IEXTEN ECHOCTL ECHOKE
c_ispeed       = 38400
c_ospeed       = 38400
c_cc[VINTR]    = CTRL-C
c_cc[VQUIT]    = CTRL-\   # ignore this comment
c_cc[VERASE]   = CTRL-?
c_cc[VKILL]    = CTRL-U
c_cc[VEOF]     = CTRL-D
c_cc[VTIME]    = CTRL-@
c_cc[VMIN]     = CTRL-A
c_cc[VSTART]   = CTRL-Q
c_cc[VSTOP]    = CTRL-S
c_cc[VSUSP]    = CTRL-Z
c_cc[VEOL]     = CTRL-@
c_cc[VSWTC]    = CTRL-@
c_cc[VREPRINT] = CTRL-R
c_cc[VDISCARD] = CTRL-O
c_cc[VWERASE]  = CTRL-W
c_cc[VLNEXT]   = CTRL-V
c_cc[VEOL2]    = CTRL-@
@param
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

tcgetsid

@param
int fd
@return
int

tcsendbreak

@param
int fd
int len
@return
int

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

TearDown

User-defined test cleanup function.

The test runner will call this function after each TEST() if it's defined by the linkage.

@return
void

telldir

Returns offset into directory data.

@param
struct dirstream* dir
@return
long

tempnam

Creates name for temporary file.

@param
const char* dir
const char* pfx
@return
char*

TerminateProcess

Terminates the specified process and all of its threads.

@param
long hProcess
unsigned int uExitCode
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

testlib_enable_tmp_setup_teardown

Enables setup and teardown of test directories.

If the linker says this symbol exists then, regardless of its value, a unique test directory will be created at the start of each test, the test will be run with that directory as its working directory, and if the test succeeds it'll be removed along with any contents.

@type
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

__tfork_thread

Creates thread on OpenBSD.

@param
rdi
is params
rsi
is size of params
rdx
is start function
rcx
is start parameter
@return
thread id or negative errno

tgamma

@param
double x
@return
double

tgammaf

@param
float x
@return
float

tgkill

Kills thread group.

@param
int tgid
int tid
int sig
@return
int
@raises ENOSYS on non-Linux
@see tkill()

__threaded

Contains TID of main thread or 0 if threading isn't enabled.

@type
int

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

times

Returns accounting data for process on time-sharing system.

@param
struct tms* out_times
@return
long

_timespec2timeval

Converts struct timespec to struct timeval.

This divides ts.tv_nsec by 1000 with upward rounding and overflow handling. Your ts.tv_nsec must be on the interval [0,1000000000) otherwise {-1, -1} is returned.

@param
struct ts ts
@return
ANONYMOUS-STRUCT
converted timeval whose tv_usec will be -1 on error

_timespec_add

Adds two nanosecond timestamps.

@param
struct x x
struct y y
@return
struct y

_timespec_eq

Checks if 𝑥 = 𝑦.

@param
struct x x
struct y y
@return
_Bool

_timespec_frommicros

Converts timespec interval from microseconds.

@param
long x
@return
struct ts

_timespec_frommillis

Converts timespec interval from milliseconds.

@param
long x
@return
struct ts

_timespec_gt

Returns true if timespec x is greater than y.

@param
struct x x
struct y y
@return
_Bool

_timespec_gte

Checks if 𝑥 ≥ 𝑦.

@param
struct x x
struct y y
@return
_Bool

_timespec_sub

Subtracts two nanosecond timestamps.

@param
struct x x
struct y y
@return
struct y

_timespec_tomicros

Converts timespec interval to microseconds.

@param
struct x x
@return
long

_timespec_tomillis

Converts timespec interval to milliseconds.

@param
struct x x
@return
long

TimeSpecToWindowsTime

@param
struct t t
@return
long

_timeval_add

Adds two microsecond timestamps.

@param
struct x x
struct y y
@return
struct y

TimeValToWindowsTime

@param
struct t t
@return
long

timezone

@type
long

timingsafe_memcmp

Lexicographically compares the first 𝑛 bytes in 𝑝 and 𝑞.

The following expression:

timingsafe_memcmp(p, q, n)
Is functionally equivalent to:

MAX(-1, MIN(1, memcmp(p, q, n)))
Running time is independent of the byte sequences compared, making this safe to use for comparing secret values such as cryptographic MACs. In contrast, memcmp() may short-circuit after finding the first differing byte.

timingsafe_memcmp n=0              661 picoseconds
timingsafe_memcmp n=1                1 ns/byte            590 mb/s
timingsafe_memcmp n=2                1 ns/byte            738 mb/s
timingsafe_memcmp n=3                1 ns/byte            805 mb/s
timingsafe_memcmp n=4                1 ns/byte            843 mb/s
timingsafe_memcmp n=5                1 ns/byte            922 mb/s
timingsafe_memcmp n=6                1 ns/byte            932 mb/s
timingsafe_memcmp n=7                1 ns/byte            939 mb/s
timingsafe_memcmp n=8              992 ps/byte            984 mb/s
timingsafe_memcmp n=9              992 ps/byte            984 mb/s
timingsafe_memcmp n=15             926 ps/byte          1,054 mb/s
timingsafe_memcmp n=16             950 ps/byte          1,026 mb/s
timingsafe_memcmp n=17             933 ps/byte          1,045 mb/s
timingsafe_memcmp n=31             896 ps/byte          1,089 mb/s
timingsafe_memcmp n=32             888 ps/byte          1,098 mb/s
timingsafe_memcmp n=33             972 ps/byte          1,004 mb/s
timingsafe_memcmp n=80             913 ps/byte          1,068 mb/s
timingsafe_memcmp n=128            891 ps/byte          1,095 mb/s
timingsafe_memcmp n=256            873 ps/byte          1,118 mb/s
timingsafe_memcmp n=16384          858 ps/byte          1,138 mb/s
timingsafe_memcmp n=32768          856 ps/byte          1,140 mb/s
timingsafe_memcmp n=131072         857 ps/byte          1,138 mb/s
bcmp ne n=256                        3 ps/byte            246 gb/s
bcmp eq n=256                       32 ps/byte         30,233 mb/s
memcmp ne n=256                      3 ps/byte            246 gb/s
memcmp eq n=256                     31 ps/byte         31,493 mb/s
timingsafe_bcmp ne n=256            27 ps/byte         35,992 mb/s
timingsafe_bcmp eq n=256            27 ps/byte         35,992 mb/s
timingsafe_memcmp ne n=256         877 ps/byte          1,113 mb/s
timingsafe_memcmp eq n=256         883 ps/byte          1,105 mb/s
@param
void* p
void* q
unsigned long n
@return
int
-1, 0, or 1 based on comparison
@note each byte is interpreted as unsigned char
@see timingsafe_bcmp() it's 100x faster
@asyncsignalsafe

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

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

tkill

Kills thread.

@param
int tid
is thread id
int sig
does nothing on xnu
@return
int
0 on success, or -1 w/ errno

tmpfile

Creates a temporary file.

@return
struct FILE*
@see mkostempsm(), kTmpPath

tolower

Converts character to ascii lower case.

@param
int c
@return
int

tolower_l

@param
int c
struct __locale_struct* l
@return
int

touch

Creates new file or changes modified time on existing one.

@param
const 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

toupper_l

@param
int c
struct __locale_struct* l
@return
int

towctrans

@param
unsigned int c
const int* t
@return
unsigned int

towlower

Converts wide character to lower case.

@param
unsigned int c
@return
unsigned int

towlower_l

@param
unsigned int c
struct __locale_struct* l
@return
unsigned int

towupper

Converts wide character to upper case.

@param
unsigned int c
@return
unsigned int

towupper_l

@param
unsigned int c
struct __locale_struct* l
@return
unsigned int

tpdecode

Thompson-Pike Varint Decoder.

@param
const 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.

This is a low-level function intended for the core runtime. Use utf16toutf8() for a much better API that uses malloc().

@param
char* dst
is output buffer
unsigned long dstsize
is bytes in dst
const 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.

This is a low-level function intended for the core runtime. Use utf8toutf16() for a much better API that uses malloc().

@param
unsigned short* dst
is output buffer
unsigned long dstsize
is shorts in dst
const 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

traceme

@type
int

TrackMemoryInterval

@param
struct _mmi* mm
int x
int y
long h
int prot
int flags
_Bool readonlyfile
_Bool iscow
long offset
long size
@return
int

trunc

Rounds to integer, towards zero.

@param
double x
@return
double

truncate

Reduces or extends underlying physical medium of file.

If file was originally larger, content >length is lost.

@param
const 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

Returns name of terminal.

@param
int fd
@return
char*

ttyname_r

Returns name of terminal, reentrantly.

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

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_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

uleb128

Encodes unsigned leb128 integer.

@param
char* p
unsigned __int128 x
@return
char*

uleb64

Encodes unsigned integer to array.

uleb64 INT64_MAX    l:        10𝑐         3𝑛𝑠
zleb64 INT64_MAX    l:        13𝑐         4𝑛𝑠
sleb64 INT64_MAX    l:        16𝑐         5𝑛𝑠
uleb128 INT64_MAX   l:        18𝑐         6𝑛𝑠
zleb128 INT64_MAX   l:        18𝑐         6𝑛𝑠
sleb128 INT64_MAX   l:        24𝑐         8𝑛𝑠
zleb64 INT64_MIN    l:        13𝑐         4𝑛𝑠
sleb64 INT64_MIN    l:        16𝑐         5𝑛𝑠
zleb128 INT64_MIN   l:        19𝑐         6𝑛𝑠
sleb128 INT64_MIN   l:        24𝑐         8𝑛𝑠
@param
char* p
is output array
unsigned long x
is number
@return
char*
p + i

umask

Sets file mode creation mask.

@param
int newmask
@return
int
previous mask
@note always succeeds

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
const 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
const unsigned short* s
@return
void*
@note no NUL terminator is added to end of buf
@see tunbing(), unbingbuf(), unbing()

Unchunk

Removes chunk transfer encoding from message body in place.

@param
struct HttpUnchunker* u
char* p
is modified in place
unsigned long n
unsigned long* l
receives content length if not null
@return
long
bytes processed, 0 if need more data, or -1 on failure

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

Underlong

Canonicalizes overlong Thompson-Pike encodings.

Please note that the IETF banned these numbers, so if you want to enforce their ban you can simply strcmp() the result to check for the existence of banned numbers.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

ungetc

Pushes byte back to stream.

@param
int c
struct FILE* f
@return
int
@threadsafe

ungetc_unlocked

Pushes byte back to stream.

@param
int c
struct FILE* f
@return
int

ungetwc

Pushes wide character back to stream.

@param
unsigned int c
struct FILE* f
@return
unsigned int
@threadsafe

ungetwc_unlocked

Pushes wide character back to stream.

@param
unsigned int c
struct FILE* f
@return
unsigned 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
const char* hexdigs
@return
void*

unhexstr

@param
const 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.

This may be used to delete files and directories and symlinks.

@param
int dirfd
is normally AT_FDCWD but if it's an open directory and path is relative, then path becomes relative to dirfd
const char* path
is 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

UnmapViewOfFile

Unmaps memory created by MapViewOfFileEx().

@param
void* lpBaseAddress
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

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()

unmount

Unmounts file system.

The following flags may be specified:

  • MNT_FORCE
The following flags may also be used, but could be set to zero at runtime if the underlying kernel doesn't support them.

  • MNT_DETACH
  • MNT_EXPIRE
  • UMOUNT_NOFOLLOW
  • MNT_BYFSID
@param
const char* target
int flags
@return
int

unsetenv

Removes environment variable.

@param
const 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

unuleb64

Decodes unsigned integer from array.

@param
char* p
is input array
unsigned long n
is capacity of p
unsigned long* x
receives number number
@return
int
bytes decoded or -1 on error

unveil

Restricts filesystem operations, e.g.

unveil(".", "r");     // current directory + children are visible
unveil("/etc", "r");  // make /etc readable too
unveil(0, 0);         // commit and lock policy
Unveiling restricts a view of the filesystem to a set of allowed paths with specific privileges.

Once you start using unveil(), the entire file system is considered hidden. You then specify, by repeatedly calling unveil(), which paths should become unhidden. When you're finished, you call unveil(0,0) which commits your policy.

There are some differences between unveil() on Linux versus OpenBSD.

  1. Build your policy and lock it in one go. On OpenBSD, policies take effect immediately and may evolve as you continue to call unveil() but only in a more restrictive direction. On Linux, nothing will happen until you call unveil(0,0) which commits and locks.
  2. Try not to overlap directory trees. On OpenBSD, if directory trees overlap, then the most restrictive policy will be used for a given file. On Linux overlapping may result in a less restrictive policy and possibly even undefined behavior.
  3. OpenBSD and Linux disagree on error codes. On OpenBSD, accessing paths outside of the allowed set raises ENOENT, and accessing ones with incorrect permissions raises EACCES. On Linux, both these cases raise EACCES.
  4. Unlike OpenBSD, Linux does nothing to conceal the existence of paths. Even with an unveil() policy in place, it's still possible to access the metadata of all files using functions like stat() and open(O_PATH), provided you know the path. A sandboxed process can always, for example, determine how many bytes of data are in /etc/passwd, even if the file isn't readable. But it's still not possible to use opendir() and go fishing for paths which weren't previously known.
  5. Use ftruncate() rather than truncate(). One of the backdoors with Landlock is it currently can't restrict truncate() and setxattr() which permits certain kinds of modifications to files outside the sandbox. When your policy is committed, we install a SECCOMP BPF filter to disable those calls, however similar trickery may be possible through other unaddressed calls like ioctl(). Using the pledge() function in addition to unveil() will solve this, since it installs a strong system call access policy.
  6. Set your process-wide policy at startup from the main thread. On OpenBSD unveil() will apply process-wide even when called from a child thread; whereas with Linux, calling unveil() from a thread will cause your ruleset to only apply to that thread in addition to any descendent threads it creates.
  7. Always specify at least one path. OpenBSD has unclear semantics when unveil(0,0) is used without any previous calls.
  8. On OpenBSD calling unveil(0,0) will prevent unveil() from being used again. On Linux this is allowed, because Landlock is able to do that securely, i.e. the second ruleset can only be a subset of the previous ones.
This system call is supported natively on OpenBSD and polyfilled on Linux using the Landlock LSM[1].
@param
const char* path
is the file or directory to unveil
const char* permissions
is a string consisting of zero or more of the following characters:

  • 'r' makes path available for read-only path operations, corresponding to the pledge promise "rpath".
  • w makes path available for write operations, corresponding to the pledge promise "wpath".
  • x makes path available for execute operations, corresponding to the pledge promises "exec" and "execnative".
  • c allows path to be created and removed, corresponding to the pledge promise "cpath".
@return
int
0 on success, or -1 w/ errno
@raise ENOSYS if host os isn't Linux or OpenBSD
@raise ENOSYS if Landlock isn't supported on this kernel
@raise EINVAL if one argument is set and the other is not
@raise EINVAL if an invalid character in permissions was found
@raise EPERM if unveil() is called after locking
@note on Linux this function requires Linux Kernel 5.13+
@see [1] https://docs.kernel.org/userspace-api/landlock.html
@threadsafe

unzleb64

Decodes array to signed integer w/ zig-zag encoding.

@param
const char* p
is array
unsigned long n
is byte length of array
long* o
optionally receives decoded integer
@return
int
bytes decoded or -1 on error
@see zleb64()

uselocale

@param
struct __locale_struct* l
@return
struct __locale_struct*

usleep

Sleeps for particular number of microseconds.

@param
unsigned int micros
@return
int
0 on success, or -1 w/ errno
@raise EINTR if a signal was delivered while sleeping
@see nanosleep(), sleep()
@norestart

utf16to32

Transcodes UTF-16 to UTF-32.

@param
const unsigned short* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
@return
int*

utf16toutf8

Transcodes UTF-16 to UTF-8.

@param
const unsigned short* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
@return
char*

utf8toutf32

Transcodes UTF-8 to UTF-32.

@param
const char* p
is input value
unsigned long n
if -1 implies strlen
unsigned long* z
if non-NULL receives output length
@return
int*

utime

Changes last accessed/modified times on file.

@param
const 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.

This is two functions in one. If path is null then this function becomes the same as futimens(dirfd, ts).

XNU and RHEL5 only have microsecond accuracy and there's no dirfd relative support.

@param
int dirfd
should AT_FDCWD
const char* path
struct st_birthtim* ts
is atime/mtime, or null for current time
int flags
can have AT_SYMLINK_NOFOLLOW
@return
int
@raise ENOSYS on RHEL5 if path is NULL
@raise EINVAL if flags had unrecognized bits
@raise EINVAL if path is NULL and flags has AT_SYMLINK_NOFOLLOW
@raise EBADF if dirfd isn't a valid fd or AT_FDCWD
@raise EFAULT if path or ts memory was invalid
@raise EROFS if file system is read-only
@raise ENAMETOOLONG
@raise EPERM
@see futimens()
@asyncsignalsafe

utimes

Changes last accessed/modified times on file.

@param
const char* path
struct ru_stime* tv
@return
int
0 on success or -1 w/ errno
@asyncsignalsafe
@see stat()

valloc

Equivalent to memalign(PAGESIZE, n).

@param
unsigned long n
number of bytes needed
@return
void*
memory address, or NULL w/ errno
@see pvalloc()
@threadsafe

vappendf

Appends formatted string to buffer.

@param
char** b
const char* f
struct __va_list* v
@return
long

vasprintf

Formats string w/ dynamic memory allocation.

@param
char** strp
const char* fmt
struct __va_list* va
@return
int
@see xasprintf() for a better API
@threadsafe

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
const 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
const char* fmt
struct __va_list* va
@return
int
@asyncsignalsafe
@vforksafe

__vdsosym

Returns address of vDSO function.

@param
const char* version
const char* name
@return
void*

verr

@param
int eval
const char* fmt
struct __va_list* va
@noreturn

verrx

@param
int eval
const 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:

INFOF("connecting to foo");
connect(...)
INFOF("connected to foo");
In that case, the second log entry will always display the amount of time that it took to connect. This is great in forking applications.
@param
unsigned int level
const char* file
int line
struct FILE* f
const char* fmt
struct __va_list* va
@return
void
@asyncsignalsafe
@threadsafe

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

Formats and writes text to stream.

@param
struct FILE* f
const char* fmt
struct __va_list* va
@return
int
@see printf() for further documentation

vfprintf_unlocked

Formats and writes text to stream.

@param
struct FILE* f
const char* fmt
struct __va_list* va
@return
int
@see printf() for further documentation

vfscanf

Stream decoder.

@param
struct FILE* stream
const char* fmt
struct __va_list* ap
@return
int
@see libc/fmt/vcscanf.h

vigna

Returns deterministic pseudorandom data, e.g.

uint64_t x = vigna();
You can generate different types of numbers as follows:

int64_t x = vigna() >> 1;    // make positive signed integer
double x = _real1(vigna());  // make float on [0,1]-interval
You can seed this random number generator using:

svigna(rdseed());
You may use the reentrant version of this function:

static uint64_t s = 0;
uint64_t x = svigna_r(&s);
If you want to fill a buffer with data then rngset() implements vigna's algorithm to do that extremely well:

char buf[4096];
rngset(buf, sizeof(buf), vigna, 0);
If you want a fast pseudorandom number generator that seeds itself automatically on startup and fork() then consider rand64(). If you want true random data then consider rdseed, rdrand, and getrandom.
@return
unsigned long
64 bits of pseudorandom data
@note this function is not intended for cryptography
@note this function passes bigcrush and practrand
@note this function takes at minimum 4 cycles

vigna_r

Returns pseudorandom data.

@param
unsigned long* state
@return
unsigned long
@see vigna() for easy api

VirtualProtect

Protects memory on the New Technology.

@param
void* lpAddress
unsigned long dwSize
unsigned int flNewProtect
unsigned int* lpflOldProtect
@return
int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

VisualizeControlCodes

Makes control codes and trojan source plainly viewable.

This is useful for logging data like HTTP messages, where we don't want full blown C string literal escaping, but we don't want things like raw ANSI control codes from untrusted devices in our terminals.

This function also canonicalizes overlong encodings. Therefore it isn't necessary to say VisualizeControlCodes(Underlong(𝑥))) since VisualizeControlCodes(𝑥) will do the same thing.

@param
const char* data
is input value
unsigned long size
if -1 implies strlen
unsigned long* out_size
if non-NULL receives output length
@return
char*
allocated NUL-terminated buffer, or NULL w/ errno

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

Formats and writes text to stdout.

@param
const char* fmt
struct __va_list* va
@return
int
@see printf() for further documentation

vscanf

String decoder.

@param
const 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
const 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 __fmt() and printf() for detailed documentation
@asyncsignalsafe
@vforksafe

vsprintf

Formats string to buffer hopefully large enough w/ vararg state.

@param
char* buf
const char* fmt
struct __va_list* va
@return
int
@see __fmt() and printf() for detailed documentation
@see vsnprintf() for modern alternative w/ buf size param

vsscanf

Decodes string.

@param
const char* str
const 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

vsyslog

Generates a log message which will be distributed by syslogd

Note: no errors are reported if an error occurred while logging

  the message.
@param
int priority
is a bitmask containing the facility value and the level value. If no facility value is ORed into priority, then the default value set by openlog() is used. it set to NULL, the program name is used. Level is one of LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG
const char* message
the format of the message to be processed by vprintf()
struct __va_list* ap
the va_list of arguments to be applied to the message
@return
void
@asyncsignalsafe

vwarn

@param
const char* fmt
struct __va_list* va
@return
void

vwarnx

@param
const 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
@restartable
@vforksafe

_wait0

Blocks until memory location becomes zero.

This is intended to be used on the child thread id, which is updated by the _spawn() system call when a thread terminates. The purpose of this operation is to know when it's safe to munmap() a threads stack

@param
const int* ctid
@return
void

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
@restartable

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
@restartable

WaitForMultipleObjects

Waits for handles to change status.

@param
unsigned int nCount
const long* lpHandles
int bWaitAll
unsigned int dwMilliseconds
@return
unsigned int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

WaitForSingleObject

Waits for handle to change status.

@param
long hHandle
unsigned int dwMilliseconds
@return
unsigned int
@note this wrapper takes care of ABI, STRACE(), and __winerr()

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
@restartable

warn

@param
const char* fmt
...
@return
void

warnx

@param
const char* fmt
...
@return
void

_wchomp

Mutates line to remove line-ending characters.

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

wcrtomb

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

wcscasecmp

Compares NUL-terminated wide strings case-insensitively.

@param
const int* a
is first non-null NUL-terminated string pointer
const 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
const 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
const int* a
is first non-null NUL-terminated string pointer
const int* b
is second non-null NUL-terminated string pointer
@return
int
is <0, 0, or >0 based on uint8_t comparison
@asyncsignalsafe

wcscoll_l

@param
const int* p
const int* q
struct __locale_struct* l
@return
int

wcscpy

Copies NUL-terminated wide character string.

𝑑 and 𝑠 must not overlap unless 𝑑 ≤ 𝑠.

@param
int* d
const 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
const int* s
const int* reject
is nul-terminated character set
@return
unsigned long
@see strspn(), strtok_r()
@asyncsignalsafe

wcsdup

Allocates copy of wide string.

@param
const int* s
@return
int*
@threadsafe

wcsendswith

Returns true if s has suffix.

@param
const int* s
is a NUL-terminated string
const 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
const int* a
is first non-null NUL-terminated string pointer
const 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

wcsncat

Appends at most 𝑛 wides from 𝑠 to 𝑑.

@param
int* d
const int* s
unsigned long n
@return
int*
𝑑
@note 𝑑 and 𝑠 can't overlap
@asyncsignaslenafe

wcsncmp

Compares NUL-terminated wide strings w/ limit.

@param
const int* a
is first non-null NUL-terminated string pointer
const 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
const 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

wcsnrtombs

@param
char* dst
const int** wcs
unsigned long wn
unsigned long n
unsigned int* st
@return
unsigned long

wcsnwidth

Returns monospace display width of wide character string.

@param
const int* pwcs
unsigned long n
unsigned long o
@return
int

wcspbrk

Returns pointer to first byte matching any in accept, or NULL.

@param
const int* s
const int* accept
@return
int*
@asyncsignalsafe

wcsrchr

Searches for last instance of wchar_t in string.

@param
const 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

wcsrtombs

@param
char* s
const int** ws
unsigned long n
unsigned int* st
@return
unsigned long

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
const int* s
const int* accept
is nul-terminated character set
@return
unsigned long
@see strcspn(), strtok_r()
@asyncsignalsafe

wcsstartswith

Returns true if s has prefix.

@param
const int* s
is a NUL-terminated string
const int* prefix
is also NUL-terminated
@return
_Bool

wcsstr

Searches for substring.

@param
const int* haystack
is the search area, as a NUL-terminated string
const int* needle
is the desired substring, also NUL-terminated
@return
int*
pointer to first substring within haystack, or NULL
@asyncsignalsafe
@see memmem()

wcstod

@param
const int* nptr
int** endptr
@return
double

wcstof

@param
const int* nptr
int** endptr
@return
float

wcstoi128

Decodes 128-bit signed integer from wide string.

@param
const int* s
is a non-null nul-terminated string
int** 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
decoded saturated integer
@see strtou128()

wcstoimax

Decodes intmax_t from wide string.

@param
const int* s
is a non-null nul-terminated string
int** 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
long
decoded saturated integer
@see strtoumax()

wcstok

Extracts non-empty tokens from string.

@param
int* s
is mutated and should be NULL on subsequent calls
const int* sep
is a NUL-terminated set of wchars to consider separators
int** state
tracks progress between calls
@return
int*
pointer to next token or NULL for end

wcstol

Decodes signed long integer from wide string.

@param
const int* s
is a non-null nul-terminated string
int** 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
long
the decoded signed saturated number

wcstold

@param
const int* nptr
int** endptr
@return
long double

wcstold_l

@param
const int* nptr
int** endptr
struct __locale_struct* l
@return
long double

wcstoll

Decodes signed long long integer from wide string.

@param
const int* s
is a non-null nul-terminated string
int** 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
long
the decoded signed saturated number

wcstoll_l

@param
const int* nptr
int** endptr
int base
struct __locale_struct* l
@return
long

wcstombs

@param
char* s
const int* ws
unsigned long n
@return
unsigned long

wcstou128

Decodes 128-bit unsigned integer from wide string.

@param
const int* s
is a non-null nul-terminated string
int** 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
unsigned __int128
decoded integer mod 2¹²⁸ negated if leading -
@see strtoi128()

wcstoul

Decodes unsigned integer from wide string.

@param
const int* s
is a non-null nul-terminated string
int** 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
unsigned long
decoded integer mod 2⁶⁴ negated if leading -

wcstoull

Decodes unsigned long long integer from wide string.

@param
const int* s
is a non-null nul-terminated string
int** 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
unsigned long
decoded integer mod 2⁶⁴ negated if leading -

wcstoull_l

@param
const int* nptr
int** endptr
int base
struct __locale_struct* l
@return
unsigned long

wcstoumax

Decodes uintmax_t from wide string.

@param
const int* s
is a non-null nul-terminated string
int** 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
unsigned long
decoded integer mod 2¹²⁸ negated if leading -
@see strtoimax()

wcswidth

Returns monospace display width of wide character string.

@param
const int* pwcs
unsigned long o
@return
int

wcsxfrm

@param
int* d
const int* s
unsigned long n
@return
unsigned long

wcsxfrm_l

@param
int* dest
const int* src
unsigned long count
struct __locale_struct* l
@return
unsigned long

wctob

@param
unsigned int c
@return
int

wctomb

@param
char* s
int wc
@return
int

wctrans

@param
const char* s
@return
const int*

wctype

Returns number representing character class name.

@param
const char* s
can be "alnum", "alpha", "blank", "cntrl", "digit", "graph", "lower", "print", "punct", "space", "upper", "xdigit"
@return
unsigned int
nonzero id or 0 if not found

wcwidth

Returns cell width of monospace character.

@param
int c
@return
int

_weakfree

Thunks free() if it's linked, otherwise do nothing.

@param
void* p
@return
void

WindowsDurationToTimeSpec

@param
long x
@return
ANONYMOUS-STRUCT

WindowsDurationToTimeVal

@param
long x
@return
ANONYMOUS-STRUCT

WindowsTimeToTimeSpec

Converts Windows COBOL timestamp to UNIX epoch in nanoseconds.

@param
long x
@return
ANONYMOUS-STRUCT

WindowsTimeToTimeVal

Converts Windows COBOL timestamp to UNIX epoch in microseconds.

@param
long x
@return
ANONYMOUS-STRUCT

__winerr

Return path for failed Win32 API calls.

@return
long
-1 w/ few exceptions
@note this is a code-size saving device

WinMain

Main function on Windows NT.

The Cosmopolitan Runtime provides the following services, which aim to bring Windows NT behavior closer in harmony with System Five:

  1. We configure CMD.EXE for UTF-8 and enable ANSI colors on Win10.
  2. Command line arguments are passed as a blob of UTF-16 text. We chop them up into an char *argv[] UTF-8 data structure, in accordance with the DOS conventions for argument quoting.
  3. Environment variables are passed to us as a sorted UTF-16 double NUL terminated list. We translate this to char ** using UTF-8.
  4. Allocates new stack at a high address. NT likes to choose a stack address that's beneath the program image. We want to be able to assume that stack addresses are located at higher addresses than heap and program memory.
  5. Reconfigure x87 FPU so long double is actually long (80 bits).
  6. Finally, we need fork. Since disagreeing with fork is axiomatic to Microsoft's engineering culture, we need to go to great lengths to have it anyway without breaking Microsoft's rules: using the WIN32 API (i.e. not NTDLL) to copy MAP_PRIVATE pages via a pipe. It'd go faster if the COW pages CreateFileMappingNuma claims to have turns out to be true. Until then we have a "PC Scale" and entirely legal workaround that they hopefully won't block using Windows Defender.
@param
long hInstance
call GetModuleHandle(NULL) from main if you need it
long hPrevInstance
const char* lpCmdLine
long nCmdShow
@return
long


__winsockerr

Error return path for winsock wrappers.

@return
long


WinThreadLaunch

Used by clone() on Windows to launch thread.

Windows owns the stack memory when we initially enter threads. This function switches us over, so that we can start using the runtime facilities.

@param
%rdi
is arg
%rsi
is tid
%rdx
is func
%rcx
is stack
@return
%rax is exit code
@see clone()

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

wmemcmp

Compares NUL-terminated wide strings w/ limit.

@param
const int* a
is first non-null NUL-terminated string pointer
const 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

wmemcpy

@param
int* dest
const int* src
unsigned long count
@return
int*

wmemmove

@param
int* dest
const int* src
unsigned long count
@return
int*

wmempcpy

@param
int* dest
const int* src
unsigned long count
@return
int*

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
@restartable

writev

Writes data from multiple buffers.

This is the same thing as write() except it has multiple buffers. This yields a performance boost in situations where it'd be expensive to stitch data together using memcpy() or issuing multiple syscalls. This wrapper is implemented so that writev() calls where iovlen<2 may be passed to the kernel as write() instead. This yields a 100 cycle performance boost in the case of a single small iovec.

Please note that it's not an error for a short write to happen. This can happen in the kernel if EINTR happens after some of the write has been committed. It can also happen if we need to polyfill this system call using write().

@param
int fd
struct iovec* iov
int iovlen
@return
long
number of bytes actually handed off, or -1 w/ errno
@restartable

WritevUninterruptible

@param
int fd
struct iovec* iov
int iovlen
@return
long

WSARecv

Receives data from Windows socket.

@param
unsigned long s
struct ProviderSpecific* inout_lpBuffers
unsigned int dwBufferCount
unsigned int* opt_out_lpNumberOfBytesRecvd
unsigned int* inout_lpFlags
struct NtOverlapped* opt_inout_lpOverlapped
void(*)() opt_lpCompletionRoutine
@return
int
0 on success, or -1 on failure
@note this wrapper takes care of ABI, STRACE(), and __winerr()

WSARecvFrom

Receives data from Windows socket.

@param
unsigned long s
struct ProviderSpecific* inout_lpBuffers
unsigned int dwBufferCount
unsigned int* opt_out_lpNumberOfBytesRecvd
unsigned int* inout_lpFlags
void* opt_out_fromsockaddr
unsigned int* opt_inout_fromsockaddrlen
struct NtOverlapped* opt_inout_lpOverlapped
void(*)() opt_lpCompletionRoutine
@return
int
0 on success, or -1 on failure
@note this wrapper takes care of ABI, STRACE(), and __winerr()

WSAStartup

Winsock2 prototypes.

@return
int
@note Some of the functions exported by WS2_32.DLL, e.g. bind(), overlap with the names used by System V. Prototypes for these functions are declared within their respective wrappers.

WSAWaitForMultipleEvents

Waits for events on Windows sockets.

@param
unsigned int cEvents
const long* lphEvents
int fWaitAll
unsigned int dwTimeout_ms
int fAlertable
@return
unsigned int
0 on success, or -1 on failure
@note this wrapper takes care of ABI, STRACE(), and __winerr()

xasprintf

Returns dynamically formatted string.

@param
const char* fmt
...
@return
char*
must be free()'d or gc()'d
@note greatest of all C functions

xbarf

Writes data to file.

@param
const char* path
void* data
unsigned long size
can be -1 to strlen(data)
@return
int
0 on success or -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
const 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

xed_decoded_inst_zero_set_mode

Clears instruction decoder state.

@param
struct XedDecodedInst* p
int mmode
@return
struct XedDecodedInst*

xed_get_chip_features

@param
struct XedChipFeatures* p
int chip
@return
void

xed_instruction_length_decode

Decodes machine instruction length.

This function also decodes other useful attributes, such as the offsets of displacement, immediates, etc. It works for all ISAs from 1977 to 2020.

@param
struct XedDecodedInst* xedd
void* itext
unsigned long bytes
@return
int
@note binary footprint increases ~4kb if this is used
@see biggest code in gdb/clang/tensorflow binaries

xed_isa_set_is_valid_for_chip

@param
int isa_set
int chip
@return
_Bool

xed_prefix_table_bit

Phash tables for instruction length decoding.

@return
@see build/rle.py for more context here

xed_test_chip_features

@param
struct XedChipFeatures* p
int isa_set
@return
_Bool

xfixpath

Fixes $PATH environment variable on Windows.

@return
void

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 getdelim() for a more difficult api
@see _chomp()

xhomedir

Returns home directory.

@return
char*

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 ru_stime* 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
const char* path
const char* other
@return
char*
newly allocated string of resulting path

xload

Inflates data once atomically, e.g.

void *GetData(void) {
  static char once;
  static void *ptr;
  static const unsigned char rodata[] = {...};
  if (once) return ptr;
  return xload(&once, &ptr, rodata, 112, 1024);
}
The above is an example of how this helper may be used to have lazy loading of big infrequently accessed image data.
@param
_Bool* o
points to your static init guard
void** t
points to your static pointer holder
void* p
is read-only data compressed using raw deflate
unsigned long n
is byte length of deflated data
unsigned long m
is byte length of inflated data
@return
void*
pointer to inflated data
@threadsafe

xloadzd

Loads δzd encoded data once atomically.

@param
_Bool* o
points to your static init guard
void** t
points to your static pointer holder
void* p
is read-only data compressed using raw deflate
unsigned long n
is byte length of deflated data
unsigned long m
is byte length of inflated data
unsigned long c
is number of items in array
unsigned long z
is byte length of items
unsigned int s
is crc32 checksum
@return
void*
pointer to decoded data
@threadsafe

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*


xreadlinkat

Reads symbolic link.

@param
int dirfd
const char* path
@return
char*
nul-terminated string, or null w/ errno
@see readlinkat()

xrealloc

Allocates/expands/shrinks/frees memory, or die.

This API enables you to do the following:

p = xrealloc(p, n)
The standard behaviors for realloc() still apply:

  • !p means xmalloc (returns non-NULL)
  • p && n means resize (returns non-NULL)
  • p && !n means free (returns NULL)
The complexity of resizing is guaranteed to be amortized.
@param
void* p
unsigned long n
@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
@vforksafe

xslurp

Reads entire file into memory.

@param
const char* path
unsigned long* opt_out_size
@return
void*
NUL-terminated malloc'd contents, or NULL w/ errno
@note this is uninterruptible

xspawn

Spawns process using fork().

@param
struct rusage* r
if provided gets accounting data
@return
int
wstatus, or -2 on child, or -1 w/ errno

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
const char* s
...
@return
char*
@see gc()

xstrdup

Allocates new copy of string, or dies.

@param
const char* s
@return
char*

xstripext

Removes file extension.

@param
const char* s
is mutated
@return
char*
s

xstripexts

Removes file extensions.

@param
const char* s
is mutated
@return
char*
s

xstrmul

Multiplies string.

@param
const char* s
unsigned long n
@return
char*

xstrndup

Allocates new copy of string, with byte limit.

@param
const 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
const unsigned short* binglyphs
@return
void*
@see xunbing(), unbingstr(), unbing()

xunbinga

Same as xunbing() w/ alignment guarantee.

@param
unsigned long a
const unsigned short* binglyphs
@return
void*

xvalloc

Allocates page-aligned memory, or dies.

@param
unsigned long size
@return
void*

xvasprintf

Returns dynamically formatted string.

@param
const char* fmt
struct __va_list* va
@return
char*
fully formatted string, which must be free()'d
@see xasprintf()

xvspawn

Spawns process using vfork().

@param
void(*)() f
is child callback
void* ctx
struct rusage* r
if provided gets accounting data
@return
int
wstatus, or -1 w/ errno

xwrite

Writes data uninterruptibly.

@param
int fd
void* p
unsigned long n
@return
int
0 on success, or -1 w/ errno

z_errmsg

@type
const char*[10]

zcalloc

@param
void* opaque
unsigned long items
unsigned long 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
const char*

__zipos_close

Closes compressed object.

@param
int fd
is vetted by close()
@return
int
@asyncsignalsafe
@threadsafe
@vforksafe

__zipos_free

Frees ZipOS handle.

@param
struct Zipos* z
struct ZiposHandle* h
@return
void
@asyncsignalsafe
@threadsafe

__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*
@asyncsignalsafe
@threadsafe

__zipos_lseek

Changes current position of zip file handle.

@param
struct ZiposHandle* h
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

__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
@asyncsignalsafe (todo)
@threadsafe

__zipos_parseuri

Extracts information about ZIP URI if it is one.

@param
const 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

zleb128

Encodes signed integer to array.

@param
char* p
__int128 x
@return
char*

zleb64

Encodes signed integer to array w/ zig-zag encoding.

uleb64 INT64_MAX    l:        10𝑐         3𝑛𝑠
zleb64 INT64_MAX    l:        13𝑐         4𝑛𝑠
sleb64 INT64_MAX    l:        16𝑐         5𝑛𝑠
uleb128 INT64_MAX   l:        18𝑐         6𝑛𝑠
zleb128 INT64_MAX   l:        18𝑐         6𝑛𝑠
sleb128 INT64_MAX   l:        24𝑐         8𝑛𝑠
@param
char* p
is output array which should have 10 items
long x
is number
@return
char*
p + i
@see unzleb64()

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
const char*