2022-04-24 16:59:22 +00:00
|
|
|
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
|
|
|
|
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
|
|
|
|
╞══════════════════════════════════════════════════════════════════════════════╡
|
|
|
|
│ Copyright 2022 Justine Alexandra Roberts Tunney │
|
|
|
|
│ │
|
|
|
|
│ Permission to use, copy, modify, and/or distribute this software for │
|
|
|
|
│ any purpose with or without fee is hereby granted, provided that the │
|
|
|
|
│ above copyright notice and this permission notice appear in all copies. │
|
|
|
|
│ │
|
|
|
|
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
|
|
|
|
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
|
|
|
|
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
|
|
|
|
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
|
|
|
|
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
|
|
|
|
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
|
|
|
|
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
|
|
|
│ PERFORMANCE OF THIS SOFTWARE. │
|
|
|
|
╚─────────────────────────────────────────────────────────────────────────────*/
|
2023-04-27 03:45:01 +00:00
|
|
|
#include "tool/net/lfuncs.h"
|
2022-04-24 16:59:22 +00:00
|
|
|
#include "dsp/scale/cdecimate2xuint8x8.h"
|
2022-04-25 15:30:14 +00:00
|
|
|
#include "libc/calls/calls.h"
|
|
|
|
#include "libc/calls/struct/rusage.h"
|
2022-07-23 03:44:24 +00:00
|
|
|
#include "libc/calls/struct/stat.h"
|
Make improvements
- Every unit test now passes on Apple Silicon. The final piece of this
puzzle was porting our POSIX threads cancelation support, since that
works differently on ARM64 XNU vs. AMD64. Our semaphore support on
Apple Silicon is also superior now compared to AMD64, thanks to the
grand central dispatch library which lets *NSYNC locks go faster.
- The Cosmopolitan runtime is now more stable, particularly on Windows.
To do this, thread local storage is mandatory at all runtime levels,
and the innermost packages of the C library is no longer being built
using ASAN. TLS is being bootstrapped with a 128-byte TIB during the
process startup phase, and then later on the runtime re-allocates it
either statically or dynamically to support code using _Thread_local.
fork() and execve() now do a better job cooperating with threads. We
can now check how much stack memory is left in the process or thread
when functions like kprintf() / execve() etc. call alloca(), so that
ENOMEM can be raised, reduce a buffer size, or just print a warning.
- POSIX signal emulation is now implemented the same way kernels do it
with pthread_kill() and raise(). Any thread can interrupt any other
thread, regardless of what it's doing. If it's blocked on read/write
then the killer thread will cancel its i/o operation so that EINTR can
be returned in the mark thread immediately. If it's doing a tight CPU
bound operation, then that's also interrupted by the signal delivery.
Signal delivery works now by suspending a thread and pushing context
data structures onto its stack, and redirecting its execution to a
trampoline function, which calls SetThreadContext(GetCurrentThread())
when it's done.
- We're now doing a better job managing locks and handles. On NetBSD we
now close semaphore file descriptors in forked children. Semaphores on
Windows can now be canceled immediately, which means mutexes/condition
variables will now go faster. Apple Silicon semaphores can be canceled
too. We're now using Apple's pthread_yield() funciton. Apple _nocancel
syscalls are now used on XNU when appropriate to ensure pthread_cancel
requests aren't lost. The MbedTLS library has been updated to support
POSIX thread cancelations. See tool/build/runitd.c for an example of
how it can be used for production multi-threaded tls servers. Handles
on Windows now leak less often across processes. All i/o operations on
Windows are now overlapped, which means file pointers can no longer be
inherited across dup() and fork() for the time being.
- We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4()
which means, for example, that posix_spawn() now goes 3x faster. POSIX
spawn is also now more correct. Like Musl, it's now able to report the
failure code of execve() via a pipe although our approach favors using
shared memory to do that on systems that have a true vfork() function.
- We now spawn a thread to deliver SIGALRM to threads when setitimer()
is used. This enables the most precise wakeups the OS makes possible.
- The Cosmopolitan runtime now uses less memory. On NetBSD for example,
it turned out the kernel would actually commit the PT_GNU_STACK size
which caused RSS to be 6mb for every process. Now it's down to ~4kb.
On Apple Silicon, we reduce the mandatory upstream thread size to the
smallest possible size to reduce the memory overhead of Cosmo threads.
The examples directory has a program called greenbean which can spawn
a web server on Linux with 10,000 worker threads and have the memory
usage of the process be ~77mb. The 1024 byte overhead of POSIX-style
thread-local storage is now optional; it won't be allocated until the
pthread_setspecific/getspecific functions are called. On Windows, the
threads that get spawned which are internal to the libc implementation
use reserve rather than commit memory, which shaves a few hundred kb.
- sigaltstack() is now supported on Windows, however it's currently not
able to be used to handle stack overflows, since crash signals are
still generated by WIN32. However the crash handler will still switch
to the alt stack, which is helpful in environments with tiny threads.
- Test binaries are now smaller. Many of the mandatory dependencies of
the test runner have been removed. This ensures many programs can do a
better job only linking the the thing they're testing. This caused the
test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb
- long double is no longer used in the implementation details of libc,
except in the APIs that define it. The old code that used long double
for time (instead of struct timespec) has now been thoroughly removed.
- ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing
backtraces itself, it'll just print a command you can run on the shell
using our new `cosmoaddr2line` program to view the backtrace.
- Crash report signal handling now works in a much better way. Instead
of terminating the process, it now relies on SA_RESETHAND so that the
default SIG_IGN behavior can terminate the process if necessary.
- Our pledge() functionality has now been fully ported to AARCH64 Linux.
2023-09-19 03:44:45 +00:00
|
|
|
#include "libc/calls/struct/timespec.h"
|
2022-06-23 10:39:44 +00:00
|
|
|
#include "libc/dns/dns.h"
|
2022-07-23 03:44:24 +00:00
|
|
|
#include "libc/errno.h"
|
2022-04-29 13:06:23 +00:00
|
|
|
#include "libc/fmt/itoa.h"
|
2022-05-16 23:49:20 +00:00
|
|
|
#include "libc/fmt/leb128.h"
|
2022-08-20 19:32:51 +00:00
|
|
|
#include "libc/intrin/bits.h"
|
2022-09-13 06:10:38 +00:00
|
|
|
#include "libc/intrin/bsf.h"
|
|
|
|
#include "libc/intrin/bsr.h"
|
2022-08-20 19:32:51 +00:00
|
|
|
#include "libc/intrin/popcnt.h"
|
2022-04-24 16:59:22 +00:00
|
|
|
#include "libc/log/check.h"
|
|
|
|
#include "libc/log/log.h"
|
|
|
|
#include "libc/macros.internal.h"
|
2022-04-28 16:42:36 +00:00
|
|
|
#include "libc/math.h"
|
2022-09-13 06:10:38 +00:00
|
|
|
#include "libc/mem/gc.internal.h"
|
2022-04-24 16:59:22 +00:00
|
|
|
#include "libc/mem/mem.h"
|
2022-04-25 15:30:14 +00:00
|
|
|
#include "libc/nexgen32e/bench.h"
|
2022-04-24 16:59:22 +00:00
|
|
|
#include "libc/nexgen32e/crc32.h"
|
|
|
|
#include "libc/nexgen32e/rdtsc.h"
|
|
|
|
#include "libc/nexgen32e/rdtscp.h"
|
2022-04-28 16:42:36 +00:00
|
|
|
#include "libc/runtime/runtime.h"
|
2022-04-24 16:59:22 +00:00
|
|
|
#include "libc/sock/sock.h"
|
2022-08-20 19:32:51 +00:00
|
|
|
#include "libc/stdio/rand.h"
|
2023-07-06 22:38:08 +00:00
|
|
|
#include "libc/str/highwayhash64.h"
|
2022-08-11 07:15:29 +00:00
|
|
|
#include "libc/str/str.h"
|
2022-09-06 14:04:13 +00:00
|
|
|
#include "libc/str/strwidth.h"
|
2023-07-06 22:38:08 +00:00
|
|
|
#include "libc/str/tab.internal.h"
|
2022-04-24 16:59:22 +00:00
|
|
|
#include "libc/sysv/consts/af.h"
|
2022-06-23 10:39:44 +00:00
|
|
|
#include "libc/sysv/consts/ipproto.h"
|
2022-07-23 03:44:24 +00:00
|
|
|
#include "libc/sysv/consts/o.h"
|
2022-04-25 15:30:14 +00:00
|
|
|
#include "libc/sysv/consts/rusage.h"
|
2022-06-23 10:39:44 +00:00
|
|
|
#include "libc/sysv/consts/sock.h"
|
Make improvements
- Every unit test now passes on Apple Silicon. The final piece of this
puzzle was porting our POSIX threads cancelation support, since that
works differently on ARM64 XNU vs. AMD64. Our semaphore support on
Apple Silicon is also superior now compared to AMD64, thanks to the
grand central dispatch library which lets *NSYNC locks go faster.
- The Cosmopolitan runtime is now more stable, particularly on Windows.
To do this, thread local storage is mandatory at all runtime levels,
and the innermost packages of the C library is no longer being built
using ASAN. TLS is being bootstrapped with a 128-byte TIB during the
process startup phase, and then later on the runtime re-allocates it
either statically or dynamically to support code using _Thread_local.
fork() and execve() now do a better job cooperating with threads. We
can now check how much stack memory is left in the process or thread
when functions like kprintf() / execve() etc. call alloca(), so that
ENOMEM can be raised, reduce a buffer size, or just print a warning.
- POSIX signal emulation is now implemented the same way kernels do it
with pthread_kill() and raise(). Any thread can interrupt any other
thread, regardless of what it's doing. If it's blocked on read/write
then the killer thread will cancel its i/o operation so that EINTR can
be returned in the mark thread immediately. If it's doing a tight CPU
bound operation, then that's also interrupted by the signal delivery.
Signal delivery works now by suspending a thread and pushing context
data structures onto its stack, and redirecting its execution to a
trampoline function, which calls SetThreadContext(GetCurrentThread())
when it's done.
- We're now doing a better job managing locks and handles. On NetBSD we
now close semaphore file descriptors in forked children. Semaphores on
Windows can now be canceled immediately, which means mutexes/condition
variables will now go faster. Apple Silicon semaphores can be canceled
too. We're now using Apple's pthread_yield() funciton. Apple _nocancel
syscalls are now used on XNU when appropriate to ensure pthread_cancel
requests aren't lost. The MbedTLS library has been updated to support
POSIX thread cancelations. See tool/build/runitd.c for an example of
how it can be used for production multi-threaded tls servers. Handles
on Windows now leak less often across processes. All i/o operations on
Windows are now overlapped, which means file pointers can no longer be
inherited across dup() and fork() for the time being.
- We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4()
which means, for example, that posix_spawn() now goes 3x faster. POSIX
spawn is also now more correct. Like Musl, it's now able to report the
failure code of execve() via a pipe although our approach favors using
shared memory to do that on systems that have a true vfork() function.
- We now spawn a thread to deliver SIGALRM to threads when setitimer()
is used. This enables the most precise wakeups the OS makes possible.
- The Cosmopolitan runtime now uses less memory. On NetBSD for example,
it turned out the kernel would actually commit the PT_GNU_STACK size
which caused RSS to be 6mb for every process. Now it's down to ~4kb.
On Apple Silicon, we reduce the mandatory upstream thread size to the
smallest possible size to reduce the memory overhead of Cosmo threads.
The examples directory has a program called greenbean which can spawn
a web server on Linux with 10,000 worker threads and have the memory
usage of the process be ~77mb. The 1024 byte overhead of POSIX-style
thread-local storage is now optional; it won't be allocated until the
pthread_setspecific/getspecific functions are called. On Windows, the
threads that get spawned which are internal to the libc implementation
use reserve rather than commit memory, which shaves a few hundred kb.
- sigaltstack() is now supported on Windows, however it's currently not
able to be used to handle stack overflows, since crash signals are
still generated by WIN32. However the crash handler will still switch
to the alt stack, which is helpful in environments with tiny threads.
- Test binaries are now smaller. Many of the mandatory dependencies of
the test runner have been removed. This ensures many programs can do a
better job only linking the the thing they're testing. This caused the
test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb
- long double is no longer used in the implementation details of libc,
except in the APIs that define it. The old code that used long double
for time (instead of struct timespec) has now been thoroughly removed.
- ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing
backtraces itself, it'll just print a command you can run on the shell
using our new `cosmoaddr2line` program to view the backtrace.
- Crash report signal handling now works in a much better way. Instead
of terminating the process, it now relies on SA_RESETHAND so that the
default SIG_IGN behavior can terminate the process if necessary.
- Our pledge() functionality has now been fully ported to AARCH64 Linux.
2023-09-19 03:44:45 +00:00
|
|
|
#include "libc/thread/thread.h"
|
2022-04-24 16:59:22 +00:00
|
|
|
#include "libc/time/time.h"
|
|
|
|
#include "libc/x/x.h"
|
|
|
|
#include "net/http/escape.h"
|
|
|
|
#include "net/http/http.h"
|
|
|
|
#include "net/http/ip.h"
|
|
|
|
#include "net/http/url.h"
|
|
|
|
#include "third_party/lua/cosmo.h"
|
|
|
|
#include "third_party/lua/lauxlib.h"
|
|
|
|
#include "third_party/lua/lua.h"
|
2022-07-23 03:44:24 +00:00
|
|
|
#include "third_party/lua/luaconf.h"
|
|
|
|
#include "third_party/lua/lunix.h"
|
2022-04-24 16:59:22 +00:00
|
|
|
#include "third_party/mbedtls/md.h"
|
|
|
|
#include "third_party/mbedtls/md5.h"
|
|
|
|
#include "third_party/mbedtls/platform.h"
|
|
|
|
#include "third_party/mbedtls/sha1.h"
|
|
|
|
#include "third_party/mbedtls/sha256.h"
|
|
|
|
#include "third_party/mbedtls/sha512.h"
|
2022-05-16 23:49:20 +00:00
|
|
|
#include "third_party/zlib/zlib.h"
|
2022-04-24 16:59:22 +00:00
|
|
|
|
2022-04-25 15:30:14 +00:00
|
|
|
static int Rdpid(void) {
|
2023-05-13 05:42:57 +00:00
|
|
|
#ifdef __x86_64__
|
2022-04-25 15:30:14 +00:00
|
|
|
return rdpid();
|
2023-05-13 05:42:57 +00:00
|
|
|
#else
|
|
|
|
return -1;
|
|
|
|
#endif
|
2022-04-25 15:30:14 +00:00
|
|
|
}
|
|
|
|
|
2022-04-29 13:06:23 +00:00
|
|
|
int LuaHex(lua_State *L) {
|
|
|
|
char b[19];
|
|
|
|
uint64_t x;
|
|
|
|
x = luaL_checkinteger(L, 1);
|
|
|
|
FormatHex64(b, x, true);
|
|
|
|
lua_pushstring(L, b);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaOct(lua_State *L) {
|
|
|
|
char b[24];
|
|
|
|
uint64_t x;
|
|
|
|
x = luaL_checkinteger(L, 1);
|
|
|
|
FormatOctal64(b, x, true);
|
|
|
|
lua_pushstring(L, b);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaBin(lua_State *L) {
|
|
|
|
char b[67];
|
|
|
|
uint64_t x;
|
|
|
|
x = luaL_checkinteger(L, 1);
|
|
|
|
FormatBinary64(b, x, 2);
|
|
|
|
lua_pushstring(L, b);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2022-04-24 16:59:22 +00:00
|
|
|
int LuaGetTime(lua_State *L) {
|
Make improvements
- Every unit test now passes on Apple Silicon. The final piece of this
puzzle was porting our POSIX threads cancelation support, since that
works differently on ARM64 XNU vs. AMD64. Our semaphore support on
Apple Silicon is also superior now compared to AMD64, thanks to the
grand central dispatch library which lets *NSYNC locks go faster.
- The Cosmopolitan runtime is now more stable, particularly on Windows.
To do this, thread local storage is mandatory at all runtime levels,
and the innermost packages of the C library is no longer being built
using ASAN. TLS is being bootstrapped with a 128-byte TIB during the
process startup phase, and then later on the runtime re-allocates it
either statically or dynamically to support code using _Thread_local.
fork() and execve() now do a better job cooperating with threads. We
can now check how much stack memory is left in the process or thread
when functions like kprintf() / execve() etc. call alloca(), so that
ENOMEM can be raised, reduce a buffer size, or just print a warning.
- POSIX signal emulation is now implemented the same way kernels do it
with pthread_kill() and raise(). Any thread can interrupt any other
thread, regardless of what it's doing. If it's blocked on read/write
then the killer thread will cancel its i/o operation so that EINTR can
be returned in the mark thread immediately. If it's doing a tight CPU
bound operation, then that's also interrupted by the signal delivery.
Signal delivery works now by suspending a thread and pushing context
data structures onto its stack, and redirecting its execution to a
trampoline function, which calls SetThreadContext(GetCurrentThread())
when it's done.
- We're now doing a better job managing locks and handles. On NetBSD we
now close semaphore file descriptors in forked children. Semaphores on
Windows can now be canceled immediately, which means mutexes/condition
variables will now go faster. Apple Silicon semaphores can be canceled
too. We're now using Apple's pthread_yield() funciton. Apple _nocancel
syscalls are now used on XNU when appropriate to ensure pthread_cancel
requests aren't lost. The MbedTLS library has been updated to support
POSIX thread cancelations. See tool/build/runitd.c for an example of
how it can be used for production multi-threaded tls servers. Handles
on Windows now leak less often across processes. All i/o operations on
Windows are now overlapped, which means file pointers can no longer be
inherited across dup() and fork() for the time being.
- We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4()
which means, for example, that posix_spawn() now goes 3x faster. POSIX
spawn is also now more correct. Like Musl, it's now able to report the
failure code of execve() via a pipe although our approach favors using
shared memory to do that on systems that have a true vfork() function.
- We now spawn a thread to deliver SIGALRM to threads when setitimer()
is used. This enables the most precise wakeups the OS makes possible.
- The Cosmopolitan runtime now uses less memory. On NetBSD for example,
it turned out the kernel would actually commit the PT_GNU_STACK size
which caused RSS to be 6mb for every process. Now it's down to ~4kb.
On Apple Silicon, we reduce the mandatory upstream thread size to the
smallest possible size to reduce the memory overhead of Cosmo threads.
The examples directory has a program called greenbean which can spawn
a web server on Linux with 10,000 worker threads and have the memory
usage of the process be ~77mb. The 1024 byte overhead of POSIX-style
thread-local storage is now optional; it won't be allocated until the
pthread_setspecific/getspecific functions are called. On Windows, the
threads that get spawned which are internal to the libc implementation
use reserve rather than commit memory, which shaves a few hundred kb.
- sigaltstack() is now supported on Windows, however it's currently not
able to be used to handle stack overflows, since crash signals are
still generated by WIN32. However the crash handler will still switch
to the alt stack, which is helpful in environments with tiny threads.
- Test binaries are now smaller. Many of the mandatory dependencies of
the test runner have been removed. This ensures many programs can do a
better job only linking the the thing they're testing. This caused the
test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb
- long double is no longer used in the implementation details of libc,
except in the APIs that define it. The old code that used long double
for time (instead of struct timespec) has now been thoroughly removed.
- ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing
backtraces itself, it'll just print a command you can run on the shell
using our new `cosmoaddr2line` program to view the backtrace.
- Crash report signal handling now works in a much better way. Instead
of terminating the process, it now relies on SA_RESETHAND so that the
default SIG_IGN behavior can terminate the process if necessary.
- Our pledge() functionality has now been fully ported to AARCH64 Linux.
2023-09-19 03:44:45 +00:00
|
|
|
struct timespec now = timespec_real();
|
|
|
|
lua_pushnumber(L, now.tv_sec + now.tv_nsec * 1e-9);
|
2022-04-24 16:59:22 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaSleep(lua_State *L) {
|
|
|
|
usleep(1e6 * luaL_checknumber(L, 1));
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaRdtsc(lua_State *L) {
|
|
|
|
lua_pushinteger(L, rdtsc());
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaGetCpuNode(lua_State *L) {
|
2022-04-25 15:30:14 +00:00
|
|
|
lua_pushinteger(L, TSC_AUX_NODE(Rdpid()));
|
2022-04-24 16:59:22 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaGetCpuCore(lua_State *L) {
|
2022-04-25 15:30:14 +00:00
|
|
|
lua_pushinteger(L, TSC_AUX_CORE(Rdpid()));
|
2022-04-24 16:59:22 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2022-04-26 04:16:05 +00:00
|
|
|
int LuaGetCpuCount(lua_State *L) {
|
2023-08-17 07:25:01 +00:00
|
|
|
lua_pushinteger(L, __get_cpu_count());
|
2022-04-26 04:16:05 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2022-04-24 16:59:22 +00:00
|
|
|
int LuaGetLogLevel(lua_State *L) {
|
|
|
|
lua_pushinteger(L, __log_level);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaSetLogLevel(lua_State *L) {
|
|
|
|
__log_level = luaL_checkinteger(L, 1);
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
static int LuaRand(lua_State *L, uint64_t impl(void)) {
|
|
|
|
lua_pushinteger(L, impl());
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaLemur64(lua_State *L) {
|
|
|
|
return LuaRand(L, lemur64);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaRand64(lua_State *L) {
|
2022-10-10 11:12:06 +00:00
|
|
|
return LuaRand(L, _rand64);
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
int LuaRdrand(lua_State *L) {
|
|
|
|
return LuaRand(L, rdrand);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaRdseed(lua_State *L) {
|
|
|
|
return LuaRand(L, rdseed);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaDecimate(lua_State *L) {
|
2022-05-29 21:47:14 +00:00
|
|
|
char *p;
|
2022-04-24 16:59:22 +00:00
|
|
|
size_t n, m;
|
|
|
|
const char *s;
|
2022-05-29 21:47:14 +00:00
|
|
|
luaL_Buffer buf;
|
2022-04-24 16:59:22 +00:00
|
|
|
s = luaL_checklstring(L, 1, &n);
|
|
|
|
m = ROUNDUP(n, 16);
|
2022-05-29 21:47:14 +00:00
|
|
|
p = luaL_buffinitsize(L, &buf, m);
|
2022-07-08 16:47:04 +00:00
|
|
|
memcpy(p, s, n);
|
2022-04-24 16:59:22 +00:00
|
|
|
bzero(p + n, m - n);
|
2022-05-29 21:47:14 +00:00
|
|
|
cDecimate2xUint8x8(m, (unsigned char *)p,
|
|
|
|
(signed char[8]){-1, -3, 3, 17, 17, 3, -3, -1});
|
2022-06-15 00:50:25 +00:00
|
|
|
luaL_pushresultsize(&buf, (n + 1) >> 1);
|
2022-04-24 16:59:22 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaMeasureEntropy(lua_State *L) {
|
|
|
|
size_t n;
|
|
|
|
const char *s;
|
|
|
|
s = luaL_checklstring(L, 1, &n);
|
|
|
|
lua_pushnumber(L, MeasureEntropy(s, n));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaGetHostOs(lua_State *L) {
|
|
|
|
const char *s = NULL;
|
|
|
|
if (IsLinux()) {
|
|
|
|
s = "LINUX";
|
|
|
|
} else if (IsMetal()) {
|
|
|
|
s = "METAL";
|
|
|
|
} else if (IsWindows()) {
|
|
|
|
s = "WINDOWS";
|
|
|
|
} else if (IsXnu()) {
|
|
|
|
s = "XNU";
|
|
|
|
} else if (IsOpenbsd()) {
|
|
|
|
s = "OPENBSD";
|
|
|
|
} else if (IsFreebsd()) {
|
|
|
|
s = "FREEBSD";
|
|
|
|
} else if (IsNetbsd()) {
|
|
|
|
s = "NETBSD";
|
|
|
|
}
|
|
|
|
if (s) {
|
|
|
|
lua_pushstring(L, s);
|
|
|
|
} else {
|
|
|
|
lua_pushnil(L);
|
|
|
|
}
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2023-06-03 15:12:13 +00:00
|
|
|
int LuaGetHostIsa(lua_State *L) {
|
|
|
|
const char *s;
|
|
|
|
#ifdef __x86_64__
|
|
|
|
s = "X86_64";
|
|
|
|
#elif defined(__aarch64__)
|
|
|
|
s = "AARCH64";
|
|
|
|
#elif defined(__powerpc64__)
|
|
|
|
s = "POWERPC64";
|
|
|
|
#elif defined(__s390x__)
|
|
|
|
s = "S390X";
|
|
|
|
#else
|
|
|
|
#error "unsupported architecture"
|
|
|
|
#endif
|
|
|
|
lua_pushstring(L, s);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2022-04-24 16:59:22 +00:00
|
|
|
int LuaFormatIp(lua_State *L) {
|
|
|
|
char b[16];
|
|
|
|
uint32_t ip;
|
|
|
|
ip = htonl(luaL_checkinteger(L, 1));
|
|
|
|
inet_ntop(AF_INET, &ip, b, sizeof(b));
|
|
|
|
lua_pushstring(L, b);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaParseIp(lua_State *L) {
|
|
|
|
size_t n;
|
|
|
|
const char *s;
|
|
|
|
s = luaL_checklstring(L, 1, &n);
|
|
|
|
lua_pushinteger(L, ParseIp(s, n));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
static int LuaIsIp(lua_State *L, bool IsIp(uint32_t)) {
|
|
|
|
lua_pushboolean(L, IsIp(luaL_checkinteger(L, 1)));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaIsPublicIp(lua_State *L) {
|
|
|
|
return LuaIsIp(L, IsPublicIp);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaIsPrivateIp(lua_State *L) {
|
|
|
|
return LuaIsIp(L, IsPrivateIp);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaIsLoopbackIp(lua_State *L) {
|
|
|
|
return LuaIsIp(L, IsLoopbackIp);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaCategorizeIp(lua_State *L) {
|
|
|
|
lua_pushstring(L, GetIpCategoryName(CategorizeIp(luaL_checkinteger(L, 1))));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaFormatHttpDateTime(lua_State *L) {
|
|
|
|
char buf[30];
|
|
|
|
lua_pushstring(L, FormatUnixHttpDateTime(buf, luaL_checkinteger(L, 1)));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaParseHttpDateTime(lua_State *L) {
|
|
|
|
size_t n;
|
|
|
|
const char *s;
|
|
|
|
s = luaL_checklstring(L, 1, &n);
|
|
|
|
lua_pushinteger(L, ParseHttpDateTime(s, n));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaParseParams(lua_State *L) {
|
|
|
|
void *m;
|
|
|
|
size_t size;
|
|
|
|
const char *data;
|
|
|
|
struct UrlParams h;
|
2022-08-06 00:34:13 +00:00
|
|
|
if (!lua_isnoneornil(L, 1)) {
|
|
|
|
data = luaL_checklstring(L, 1, &size);
|
|
|
|
bzero(&h, sizeof(h));
|
|
|
|
if ((m = ParseParams(data, size, &h))) {
|
|
|
|
LuaPushUrlParams(L, &h);
|
|
|
|
free(h.p);
|
|
|
|
free(m);
|
|
|
|
return 1;
|
|
|
|
} else {
|
|
|
|
luaL_error(L, "out of memory");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-08-06 00:34:13 +00:00
|
|
|
}
|
2022-05-29 21:47:14 +00:00
|
|
|
} else {
|
2022-08-06 00:34:13 +00:00
|
|
|
return lua_gettop(L);
|
2022-05-29 21:47:14 +00:00
|
|
|
}
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
int LuaParseHost(lua_State *L) {
|
|
|
|
void *m;
|
|
|
|
size_t n;
|
|
|
|
struct Url h;
|
|
|
|
const char *p;
|
2022-08-06 00:34:13 +00:00
|
|
|
if (!lua_isnoneornil(L, 1)) {
|
|
|
|
bzero(&h, sizeof(h));
|
|
|
|
p = luaL_checklstring(L, 1, &n);
|
|
|
|
if ((m = ParseHost(p, n, &h))) {
|
|
|
|
lua_newtable(L);
|
|
|
|
LuaPushUrlView(L, &h.host);
|
|
|
|
LuaPushUrlView(L, &h.port);
|
|
|
|
free(m);
|
|
|
|
return 1;
|
|
|
|
} else {
|
|
|
|
luaL_error(L, "out of memory");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-08-06 00:34:13 +00:00
|
|
|
}
|
2022-05-29 21:47:14 +00:00
|
|
|
} else {
|
2022-08-06 00:34:13 +00:00
|
|
|
return lua_gettop(L);
|
2022-05-29 21:47:14 +00:00
|
|
|
}
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
int LuaPopcnt(lua_State *L) {
|
|
|
|
lua_pushinteger(L, popcnt(luaL_checkinteger(L, 1)));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaBsr(lua_State *L) {
|
|
|
|
long x;
|
|
|
|
if ((x = luaL_checkinteger(L, 1))) {
|
2022-09-13 06:10:38 +00:00
|
|
|
lua_pushinteger(L, _bsrl(x));
|
2022-04-24 16:59:22 +00:00
|
|
|
return 1;
|
|
|
|
} else {
|
|
|
|
luaL_argerror(L, 1, "zero");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaBsf(lua_State *L) {
|
|
|
|
long x;
|
|
|
|
if ((x = luaL_checkinteger(L, 1))) {
|
2022-09-13 06:10:38 +00:00
|
|
|
lua_pushinteger(L, _bsfl(x));
|
2022-04-24 16:59:22 +00:00
|
|
|
return 1;
|
|
|
|
} else {
|
|
|
|
luaL_argerror(L, 1, "zero");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-06 22:38:08 +00:00
|
|
|
int LuaHighwayHash64(lua_State *L) {
|
|
|
|
size_t n;
|
|
|
|
uint64_t k[4];
|
|
|
|
const char *p;
|
|
|
|
p = luaL_checklstring(L, 1, &n);
|
|
|
|
k[0] = luaL_optinteger(L, 2, 0);
|
|
|
|
k[1] = luaL_optinteger(L, 3, 0);
|
|
|
|
k[2] = luaL_optinteger(L, 4, 0);
|
|
|
|
k[3] = luaL_optinteger(L, 5, 0);
|
|
|
|
lua_pushinteger(L, HighwayHash64(p, n, k));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2022-04-24 16:59:22 +00:00
|
|
|
static int LuaHash(lua_State *L, uint32_t H(uint32_t, const void *, size_t)) {
|
|
|
|
long i;
|
|
|
|
size_t n;
|
|
|
|
const char *p;
|
|
|
|
i = luaL_checkinteger(L, 1);
|
|
|
|
p = luaL_checklstring(L, 2, &n);
|
|
|
|
lua_pushinteger(L, H(i, p, n));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaCrc32(lua_State *L) {
|
|
|
|
return LuaHash(L, crc32_z);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaCrc32c(lua_State *L) {
|
|
|
|
return LuaHash(L, crc32c);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaIndentLines(lua_State *L) {
|
|
|
|
size_t n, j;
|
2023-09-02 03:49:13 +00:00
|
|
|
const void *p;
|
2022-08-06 00:34:13 +00:00
|
|
|
if (!lua_isnoneornil(L, 1)) {
|
|
|
|
p = luaL_checklstring(L, 1, &n);
|
|
|
|
j = luaL_optinteger(L, 2, 1);
|
|
|
|
if (!(0 <= j && j <= 65535)) {
|
|
|
|
luaL_argerror(L, 2, "not in range 0..65535");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-08-06 00:34:13 +00:00
|
|
|
}
|
2023-09-02 03:49:13 +00:00
|
|
|
char *q = IndentLines(p, n, &n, j);
|
|
|
|
lua_pushlstring(L, q, n);
|
|
|
|
free(q);
|
2022-08-06 00:34:13 +00:00
|
|
|
return 1;
|
|
|
|
} else {
|
|
|
|
return lua_gettop(L);
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaGetMonospaceWidth(lua_State *L) {
|
|
|
|
int w;
|
2022-07-08 16:47:04 +00:00
|
|
|
if (lua_isnumber(L, 1)) {
|
2022-04-24 16:59:22 +00:00
|
|
|
w = wcwidth(lua_tointeger(L, 1));
|
|
|
|
} else if (lua_isstring(L, 1)) {
|
|
|
|
w = strwidth(luaL_checkstring(L, 1), luaL_optinteger(L, 2, 0) & 7);
|
|
|
|
} else {
|
|
|
|
luaL_argerror(L, 1, "not integer or string");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
lua_pushinteger(L, w);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2022-07-23 03:44:24 +00:00
|
|
|
// Slurp(path:str[, i:int[, j:int]])
|
|
|
|
// ├─→ data:str
|
|
|
|
// └─→ nil, unix.Errno
|
2022-04-24 16:59:22 +00:00
|
|
|
int LuaSlurp(lua_State *L) {
|
2022-07-23 03:44:24 +00:00
|
|
|
ssize_t rc;
|
|
|
|
char tb[2048];
|
|
|
|
luaL_Buffer b;
|
|
|
|
struct stat st;
|
|
|
|
int fd, olderr;
|
|
|
|
bool shouldpread;
|
|
|
|
lua_Integer i, j, got;
|
|
|
|
olderr = errno;
|
|
|
|
if (lua_isnoneornil(L, 2)) {
|
|
|
|
i = 1;
|
2022-04-24 16:59:22 +00:00
|
|
|
} else {
|
2022-07-23 03:44:24 +00:00
|
|
|
i = luaL_checkinteger(L, 2);
|
|
|
|
}
|
|
|
|
if (lua_isnoneornil(L, 3)) {
|
|
|
|
j = LUA_MAXINTEGER;
|
|
|
|
} else {
|
|
|
|
j = luaL_checkinteger(L, 3);
|
|
|
|
}
|
|
|
|
luaL_buffinit(L, &b);
|
|
|
|
if ((fd = open(luaL_checkstring(L, 1), O_RDONLY | O_SEQUENTIAL)) == -1) {
|
|
|
|
return LuaUnixSysretErrno(L, "open", olderr);
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
2022-07-23 03:44:24 +00:00
|
|
|
if (i < 0 || j < 0) {
|
|
|
|
if (fstat(fd, &st) == -1) {
|
|
|
|
close(fd);
|
|
|
|
return LuaUnixSysretErrno(L, "fstat", olderr);
|
|
|
|
}
|
|
|
|
if (i < 0) {
|
|
|
|
i = st.st_size + (i + 1);
|
|
|
|
}
|
|
|
|
if (j < 0) {
|
|
|
|
j = st.st_size + (j + 1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (i < 1) {
|
|
|
|
i = 1;
|
|
|
|
}
|
|
|
|
shouldpread = i > 1;
|
|
|
|
for (; i <= j; i += got) {
|
|
|
|
if (shouldpread) {
|
|
|
|
rc = pread(fd, tb, MIN(j - i + 1, sizeof(tb)), i - 1);
|
|
|
|
} else {
|
|
|
|
rc = read(fd, tb, MIN(j - i + 1, sizeof(tb)));
|
|
|
|
}
|
|
|
|
if (rc != -1) {
|
|
|
|
got = rc;
|
|
|
|
if (!got) break;
|
|
|
|
luaL_addlstring(&b, tb, got);
|
|
|
|
} else if (errno == EINTR) {
|
|
|
|
errno = olderr;
|
|
|
|
got = 0;
|
|
|
|
} else {
|
|
|
|
close(fd);
|
|
|
|
return LuaUnixSysretErrno(L, "read", olderr);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (close(fd) == -1) {
|
|
|
|
return LuaUnixSysretErrno(L, "close", olderr);
|
|
|
|
}
|
|
|
|
luaL_pushresult(&b);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Barf(path:str, data:str[, mode:int[, flags:int[, offset:int]]])
|
|
|
|
// ├─→ true
|
|
|
|
// └─→ nil, unix.Errno
|
|
|
|
int LuaBarf(lua_State *L) {
|
|
|
|
ssize_t rc;
|
2023-09-02 03:49:13 +00:00
|
|
|
const char *data;
|
2022-07-23 03:44:24 +00:00
|
|
|
lua_Number offset;
|
|
|
|
size_t i, n, wrote;
|
|
|
|
int fd, mode, flags, olderr;
|
|
|
|
olderr = errno;
|
|
|
|
data = luaL_checklstring(L, 2, &n);
|
|
|
|
if (lua_isnoneornil(L, 5)) {
|
|
|
|
offset = 0;
|
|
|
|
} else {
|
|
|
|
offset = luaL_checkinteger(L, 5);
|
|
|
|
if (offset < 1) {
|
|
|
|
luaL_error(L, "offset must be >= 1");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-07-23 03:44:24 +00:00
|
|
|
}
|
|
|
|
--offset;
|
|
|
|
}
|
|
|
|
mode = luaL_optinteger(L, 3, 0644);
|
|
|
|
flags = O_WRONLY | O_SEQUENTIAL | luaL_optinteger(L, 4, O_TRUNC | O_CREAT);
|
|
|
|
if (flags & O_NONBLOCK) {
|
|
|
|
luaL_error(L, "O_NONBLOCK not allowed");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-07-23 03:44:24 +00:00
|
|
|
}
|
|
|
|
if ((flags & O_APPEND) && offset) {
|
|
|
|
luaL_error(L, "O_APPEND with offset not possible");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-07-23 03:44:24 +00:00
|
|
|
}
|
|
|
|
if ((fd = open(luaL_checkstring(L, 1), flags, mode)) == -1) {
|
|
|
|
return LuaUnixSysretErrno(L, "open", olderr);
|
|
|
|
}
|
|
|
|
for (i = 0; i < n; i += wrote) {
|
|
|
|
if (offset) {
|
|
|
|
rc = pwrite(fd, data + i, n - i, offset + i);
|
|
|
|
} else {
|
|
|
|
rc = write(fd, data + i, n - i);
|
|
|
|
}
|
|
|
|
if (rc != -1) {
|
|
|
|
wrote = rc;
|
|
|
|
} else if (errno == EINTR) {
|
|
|
|
errno = olderr;
|
|
|
|
wrote = 0;
|
|
|
|
} else {
|
|
|
|
close(fd);
|
|
|
|
return LuaUnixSysretErrno(L, "write", olderr);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (close(fd) == -1) {
|
|
|
|
return LuaUnixSysretErrno(L, "close", olderr);
|
|
|
|
}
|
|
|
|
lua_pushboolean(L, true);
|
|
|
|
return 1;
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
|
2022-06-23 10:39:44 +00:00
|
|
|
int LuaResolveIp(lua_State *L) {
|
|
|
|
ssize_t rc;
|
|
|
|
int64_t ip;
|
|
|
|
const char *host;
|
|
|
|
struct addrinfo *ai = NULL;
|
|
|
|
struct addrinfo hint = {AI_NUMERICSERV, AF_INET, SOCK_STREAM, IPPROTO_TCP};
|
|
|
|
host = luaL_checkstring(L, 1);
|
|
|
|
if ((ip = ParseIp(host, -1)) != -1) {
|
2022-06-24 00:59:35 +00:00
|
|
|
lua_pushinteger(L, ip);
|
2022-06-23 10:39:44 +00:00
|
|
|
return 1;
|
|
|
|
} else if ((rc = getaddrinfo(host, "0", &hint, &ai)) == EAI_SUCCESS) {
|
|
|
|
lua_pushinteger(L, ntohl(ai->ai_addr4->sin_addr.s_addr));
|
|
|
|
freeaddrinfo(ai);
|
|
|
|
return 1;
|
|
|
|
} else {
|
|
|
|
lua_pushnil(L);
|
|
|
|
lua_pushfstring(L, "%s: DNS lookup failed: EAI_%s", host, gai_strerror(rc));
|
|
|
|
return 2;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-24 16:59:22 +00:00
|
|
|
static int LuaCheckControlFlags(lua_State *L, int idx) {
|
2022-07-09 06:06:46 +00:00
|
|
|
int f = luaL_optinteger(L, idx, 0);
|
2022-04-24 16:59:22 +00:00
|
|
|
if (f & ~(kControlWs | kControlC0 | kControlC1)) {
|
|
|
|
luaL_argerror(L, idx, "invalid control flags");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
return f;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaHasControlCodes(lua_State *L) {
|
|
|
|
int f;
|
|
|
|
size_t n;
|
|
|
|
const char *p;
|
|
|
|
p = luaL_checklstring(L, 1, &n);
|
|
|
|
f = LuaCheckControlFlags(L, 2);
|
|
|
|
lua_pushboolean(L, HasControlCodes(p, n, f) != -1);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaEncodeLatin1(lua_State *L) {
|
|
|
|
int f;
|
2023-09-02 03:49:13 +00:00
|
|
|
char *q;
|
2022-04-24 16:59:22 +00:00
|
|
|
size_t n;
|
2023-09-02 03:49:13 +00:00
|
|
|
const char *p;
|
2022-04-24 16:59:22 +00:00
|
|
|
p = luaL_checklstring(L, 1, &n);
|
|
|
|
f = LuaCheckControlFlags(L, 2);
|
2023-09-02 03:49:13 +00:00
|
|
|
if ((q = EncodeLatin1(p, n, &n, f))) {
|
|
|
|
lua_pushlstring(L, q, n);
|
|
|
|
free(q);
|
2022-05-29 21:47:14 +00:00
|
|
|
return 1;
|
|
|
|
} else {
|
|
|
|
luaL_error(L, "out of memory");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-05-29 21:47:14 +00:00
|
|
|
}
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
|
2023-10-12 03:06:20 +00:00
|
|
|
dontinline int LuaBase32Impl(lua_State *L,
|
|
|
|
char *B32(const char *, size_t, const char *, size_t, size_t *)) {
|
|
|
|
char *p;
|
|
|
|
size_t sl, al; // source/output and alphabet lengths
|
|
|
|
const char *s = luaL_checklstring(L, 1, &sl);
|
|
|
|
// use an empty string, as EncodeBase32 provides a default value
|
|
|
|
const char *a = luaL_optlstring(L, 2, "", &al);
|
|
|
|
if (!IS2POW(al) || al > 128 || al == 1)
|
|
|
|
return luaL_error(L, "alphabet length is not a power of 2 in range 2..128");
|
|
|
|
if (!(p = B32(s, sl, a, al, &sl)))
|
|
|
|
return luaL_error(L, "out of memory");
|
|
|
|
lua_pushlstring(L, p, sl);
|
|
|
|
free(p);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaEncodeBase32(lua_State *L) {
|
|
|
|
return LuaBase32Impl(L, EncodeBase32);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaDecodeBase32(lua_State *L) {
|
|
|
|
return LuaBase32Impl(L, DecodeBase32);
|
|
|
|
}
|
|
|
|
|
2023-07-06 22:38:08 +00:00
|
|
|
int LuaEncodeHex(lua_State *L) {
|
|
|
|
char *p;
|
|
|
|
size_t n;
|
|
|
|
const char *s;
|
|
|
|
luaL_Buffer buf;
|
|
|
|
s = luaL_checklstring(L, 1, &n);
|
|
|
|
p = luaL_buffinitsize(L, &buf, n * 2 + 1);
|
|
|
|
hexpcpy(p, s, n);
|
|
|
|
luaL_pushresultsize(&buf, n * 2);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaDecodeHex(lua_State *L) {
|
|
|
|
char *p;
|
|
|
|
int x, y;
|
|
|
|
size_t i, n;
|
|
|
|
const char *s;
|
|
|
|
luaL_Buffer buf;
|
|
|
|
s = luaL_checklstring(L, 1, &n);
|
|
|
|
if (n & 1) {
|
|
|
|
luaL_argerror(L, 1, "hex string length uneven");
|
|
|
|
__builtin_unreachable();
|
|
|
|
}
|
|
|
|
p = luaL_buffinitsize(L, &buf, n >> 1);
|
|
|
|
for (i = 0; i < n; i += 2) {
|
|
|
|
if ((x = kHexToInt[s[i + 0] & 255]) == -1 ||
|
|
|
|
(y = kHexToInt[s[i + 1] & 255]) == -1) {
|
|
|
|
luaL_argerror(L, 1, "hex string has non-hex character");
|
|
|
|
__builtin_unreachable();
|
|
|
|
}
|
|
|
|
p[i >> 1] = x << 4 | y;
|
|
|
|
}
|
|
|
|
luaL_pushresultsize(&buf, n >> 1);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2022-04-24 16:59:22 +00:00
|
|
|
int LuaGetRandomBytes(lua_State *L) {
|
2022-05-29 21:47:14 +00:00
|
|
|
size_t n;
|
|
|
|
luaL_Buffer buf;
|
|
|
|
n = luaL_optinteger(L, 1, 16);
|
2022-04-24 16:59:22 +00:00
|
|
|
if (!(n > 0 && n <= 256)) {
|
|
|
|
luaL_argerror(L, 1, "not in range 1..256");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
2022-05-29 21:47:14 +00:00
|
|
|
CHECK_EQ(n, getrandom(luaL_buffinitsize(L, &buf, n), n, 0));
|
2022-06-15 00:50:25 +00:00
|
|
|
luaL_pushresultsize(&buf, n);
|
2022-04-24 16:59:22 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaGetHttpReason(lua_State *L) {
|
|
|
|
lua_pushstring(L, GetHttpReason(luaL_checkinteger(L, 1)));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaGetCryptoHash(lua_State *L) {
|
|
|
|
size_t hl, pl, kl;
|
|
|
|
uint8_t d[64];
|
|
|
|
// get hash name, payload, and key
|
2023-09-02 03:49:13 +00:00
|
|
|
const void *h = luaL_checklstring(L, 1, &hl);
|
|
|
|
const void *p = luaL_checklstring(L, 2, &pl);
|
|
|
|
const void *k = luaL_optlstring(L, 3, "", &kl);
|
2022-04-24 16:59:22 +00:00
|
|
|
const mbedtls_md_info_t *digest = mbedtls_md_info_from_string(h);
|
|
|
|
if (!digest) return luaL_argerror(L, 1, "unknown hash type");
|
|
|
|
if (kl == 0) {
|
|
|
|
// no key provided, run generic hash function
|
|
|
|
if ((digest->f_md)(p, pl, d)) return luaL_error(L, "bad input data");
|
|
|
|
} else if (mbedtls_md_hmac(digest, k, kl, p, pl, d)) {
|
|
|
|
return luaL_error(L, "bad input data");
|
|
|
|
}
|
|
|
|
lua_pushlstring(L, (void *)d, digest->size);
|
|
|
|
mbedtls_platform_zeroize(d, sizeof(d));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
static dontinline int LuaIsValid(lua_State *L, bool V(const char *, size_t)) {
|
|
|
|
size_t size;
|
|
|
|
const char *data;
|
|
|
|
data = luaL_checklstring(L, 1, &size);
|
|
|
|
lua_pushboolean(L, V(data, size));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaIsValidHttpToken(lua_State *L) {
|
|
|
|
return LuaIsValid(L, IsValidHttpToken);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaIsAcceptablePath(lua_State *L) {
|
|
|
|
return LuaIsValid(L, IsAcceptablePath);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaIsReasonablePath(lua_State *L) {
|
|
|
|
return LuaIsValid(L, IsReasonablePath);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaIsAcceptableHost(lua_State *L) {
|
|
|
|
return LuaIsValid(L, IsAcceptableHost);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaIsAcceptablePort(lua_State *L) {
|
|
|
|
return LuaIsValid(L, IsAcceptablePort);
|
|
|
|
}
|
|
|
|
|
|
|
|
static dontinline int LuaCoderImpl(lua_State *L,
|
|
|
|
char *C(const char *, size_t, size_t *)) {
|
2023-09-02 03:49:13 +00:00
|
|
|
void *q;
|
2022-04-24 16:59:22 +00:00
|
|
|
size_t n;
|
2023-09-02 03:49:13 +00:00
|
|
|
const void *p;
|
2022-08-06 00:34:13 +00:00
|
|
|
if (!lua_isnoneornil(L, 1)) {
|
|
|
|
p = luaL_checklstring(L, 1, &n);
|
2023-09-02 03:49:13 +00:00
|
|
|
if ((q = C(p, n, &n))) {
|
|
|
|
lua_pushlstring(L, q, n);
|
|
|
|
free(q);
|
2022-08-06 00:34:13 +00:00
|
|
|
} else {
|
|
|
|
luaL_error(L, "out of memory");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-08-06 00:34:13 +00:00
|
|
|
}
|
|
|
|
return 1;
|
2022-07-13 06:31:06 +00:00
|
|
|
} else {
|
2022-08-06 00:34:13 +00:00
|
|
|
return lua_gettop(L);
|
2022-07-13 06:31:06 +00:00
|
|
|
}
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
static dontinline int LuaCoder(lua_State *L,
|
|
|
|
char *C(const char *, size_t, size_t *)) {
|
|
|
|
return LuaCoderImpl(L, C);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaUnderlong(lua_State *L) {
|
|
|
|
return LuaCoder(L, Underlong);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaEncodeBase64(lua_State *L) {
|
|
|
|
return LuaCoder(L, EncodeBase64);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaDecodeBase64(lua_State *L) {
|
|
|
|
return LuaCoder(L, DecodeBase64);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaDecodeLatin1(lua_State *L) {
|
|
|
|
return LuaCoder(L, DecodeLatin1);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaEscapeHtml(lua_State *L) {
|
|
|
|
return LuaCoder(L, EscapeHtml);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaEscapeParam(lua_State *L) {
|
|
|
|
return LuaCoder(L, EscapeParam);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaEscapePath(lua_State *L) {
|
|
|
|
return LuaCoder(L, EscapePath);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaEscapeHost(lua_State *L) {
|
|
|
|
return LuaCoder(L, EscapeHost);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaEscapeIp(lua_State *L) {
|
|
|
|
return LuaCoder(L, EscapeIp);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaEscapeUser(lua_State *L) {
|
|
|
|
return LuaCoder(L, EscapeUser);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaEscapePass(lua_State *L) {
|
|
|
|
return LuaCoder(L, EscapePass);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaEscapeSegment(lua_State *L) {
|
|
|
|
return LuaCoder(L, EscapeSegment);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaEscapeFragment(lua_State *L) {
|
|
|
|
return LuaCoder(L, EscapeFragment);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaEscapeLiteral(lua_State *L) {
|
2023-09-02 03:49:13 +00:00
|
|
|
const char *p;
|
|
|
|
char *z, *q = 0;
|
2022-07-13 06:31:06 +00:00
|
|
|
size_t n, y = 0;
|
|
|
|
p = luaL_checklstring(L, 1, &n);
|
2023-09-02 03:49:13 +00:00
|
|
|
if ((z = EscapeJsStringLiteral(&q, &y, p, n, &n))) {
|
|
|
|
lua_pushlstring(L, z, n);
|
|
|
|
free(z);
|
2022-07-13 06:31:06 +00:00
|
|
|
return 1;
|
|
|
|
} else {
|
|
|
|
luaL_error(L, "out of memory");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-07-13 06:31:06 +00:00
|
|
|
}
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
int LuaVisualizeControlCodes(lua_State *L) {
|
|
|
|
return LuaCoder(L, VisualizeControlCodes);
|
|
|
|
}
|
|
|
|
|
|
|
|
static dontinline int LuaHasherImpl(lua_State *L, size_t k,
|
|
|
|
int H(const void *, size_t, uint8_t *)) {
|
|
|
|
size_t n;
|
|
|
|
uint8_t d[64];
|
2023-09-02 03:49:13 +00:00
|
|
|
const void *p;
|
2022-08-06 00:34:13 +00:00
|
|
|
if (!lua_isnoneornil(L, 1)) {
|
|
|
|
p = luaL_checklstring(L, 1, &n);
|
|
|
|
H(p, n, d);
|
|
|
|
lua_pushlstring(L, (void *)d, k);
|
|
|
|
mbedtls_platform_zeroize(d, sizeof(d));
|
|
|
|
return 1;
|
|
|
|
} else {
|
|
|
|
return lua_gettop(L);
|
|
|
|
}
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
static dontinline int LuaHasher(lua_State *L, size_t k,
|
|
|
|
int H(const void *, size_t, uint8_t *)) {
|
|
|
|
return LuaHasherImpl(L, k, H);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaMd5(lua_State *L) {
|
|
|
|
return LuaHasher(L, 16, mbedtls_md5_ret);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaSha1(lua_State *L) {
|
|
|
|
return LuaHasher(L, 20, mbedtls_sha1_ret);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaSha224(lua_State *L) {
|
|
|
|
return LuaHasher(L, 28, mbedtls_sha256_ret_224);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaSha256(lua_State *L) {
|
|
|
|
return LuaHasher(L, 32, mbedtls_sha256_ret_256);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaSha384(lua_State *L) {
|
|
|
|
return LuaHasher(L, 48, mbedtls_sha512_ret_384);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaSha512(lua_State *L) {
|
|
|
|
return LuaHasher(L, 64, mbedtls_sha512_ret_512);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LuaIsHeaderRepeatable(lua_State *L) {
|
|
|
|
int h;
|
|
|
|
bool r;
|
|
|
|
size_t n;
|
|
|
|
const char *s;
|
|
|
|
s = luaL_checklstring(L, 1, &n);
|
|
|
|
if ((h = GetHttpHeader(s, n)) != -1) {
|
|
|
|
r = kHttpRepeatable[h];
|
|
|
|
} else {
|
|
|
|
r = false;
|
|
|
|
}
|
|
|
|
lua_pushboolean(L, r);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
void LuaPushUrlView(lua_State *L, struct UrlView *v) {
|
|
|
|
if (v->p) {
|
|
|
|
lua_pushlstring(L, v->p, v->n);
|
|
|
|
} else {
|
|
|
|
lua_pushnil(L);
|
|
|
|
}
|
|
|
|
}
|
2022-04-25 15:30:14 +00:00
|
|
|
|
|
|
|
static int64_t GetInterrupts(void) {
|
|
|
|
struct rusage ru;
|
|
|
|
if (!getrusage(RUSAGE_SELF, &ru)) {
|
|
|
|
return ru.ru_nivcsw;
|
|
|
|
} else {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-28 16:42:36 +00:00
|
|
|
static int DoNothing(lua_State *L) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2022-04-25 15:30:14 +00:00
|
|
|
int LuaBenchmark(lua_State *L) {
|
|
|
|
uint64_t t1, t2;
|
|
|
|
int64_t interrupts;
|
2022-04-28 16:42:36 +00:00
|
|
|
double avgticks, overhead;
|
2023-09-02 03:49:13 +00:00
|
|
|
int core, iter, count, attempts, maxattempts;
|
2022-04-25 15:30:14 +00:00
|
|
|
luaL_checktype(L, 1, LUA_TFUNCTION);
|
|
|
|
count = luaL_optinteger(L, 2, 100);
|
|
|
|
maxattempts = luaL_optinteger(L, 3, 10);
|
2022-06-11 03:51:36 +00:00
|
|
|
__warn_if_powersave();
|
2022-04-28 16:42:36 +00:00
|
|
|
lua_gc(L, LUA_GCSTOP);
|
|
|
|
|
2022-04-25 15:30:14 +00:00
|
|
|
for (attempts = 0;;) {
|
2022-04-28 16:42:36 +00:00
|
|
|
lua_gc(L, LUA_GCCOLLECT);
|
Make improvements
- Every unit test now passes on Apple Silicon. The final piece of this
puzzle was porting our POSIX threads cancelation support, since that
works differently on ARM64 XNU vs. AMD64. Our semaphore support on
Apple Silicon is also superior now compared to AMD64, thanks to the
grand central dispatch library which lets *NSYNC locks go faster.
- The Cosmopolitan runtime is now more stable, particularly on Windows.
To do this, thread local storage is mandatory at all runtime levels,
and the innermost packages of the C library is no longer being built
using ASAN. TLS is being bootstrapped with a 128-byte TIB during the
process startup phase, and then later on the runtime re-allocates it
either statically or dynamically to support code using _Thread_local.
fork() and execve() now do a better job cooperating with threads. We
can now check how much stack memory is left in the process or thread
when functions like kprintf() / execve() etc. call alloca(), so that
ENOMEM can be raised, reduce a buffer size, or just print a warning.
- POSIX signal emulation is now implemented the same way kernels do it
with pthread_kill() and raise(). Any thread can interrupt any other
thread, regardless of what it's doing. If it's blocked on read/write
then the killer thread will cancel its i/o operation so that EINTR can
be returned in the mark thread immediately. If it's doing a tight CPU
bound operation, then that's also interrupted by the signal delivery.
Signal delivery works now by suspending a thread and pushing context
data structures onto its stack, and redirecting its execution to a
trampoline function, which calls SetThreadContext(GetCurrentThread())
when it's done.
- We're now doing a better job managing locks and handles. On NetBSD we
now close semaphore file descriptors in forked children. Semaphores on
Windows can now be canceled immediately, which means mutexes/condition
variables will now go faster. Apple Silicon semaphores can be canceled
too. We're now using Apple's pthread_yield() funciton. Apple _nocancel
syscalls are now used on XNU when appropriate to ensure pthread_cancel
requests aren't lost. The MbedTLS library has been updated to support
POSIX thread cancelations. See tool/build/runitd.c for an example of
how it can be used for production multi-threaded tls servers. Handles
on Windows now leak less often across processes. All i/o operations on
Windows are now overlapped, which means file pointers can no longer be
inherited across dup() and fork() for the time being.
- We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4()
which means, for example, that posix_spawn() now goes 3x faster. POSIX
spawn is also now more correct. Like Musl, it's now able to report the
failure code of execve() via a pipe although our approach favors using
shared memory to do that on systems that have a true vfork() function.
- We now spawn a thread to deliver SIGALRM to threads when setitimer()
is used. This enables the most precise wakeups the OS makes possible.
- The Cosmopolitan runtime now uses less memory. On NetBSD for example,
it turned out the kernel would actually commit the PT_GNU_STACK size
which caused RSS to be 6mb for every process. Now it's down to ~4kb.
On Apple Silicon, we reduce the mandatory upstream thread size to the
smallest possible size to reduce the memory overhead of Cosmo threads.
The examples directory has a program called greenbean which can spawn
a web server on Linux with 10,000 worker threads and have the memory
usage of the process be ~77mb. The 1024 byte overhead of POSIX-style
thread-local storage is now optional; it won't be allocated until the
pthread_setspecific/getspecific functions are called. On Windows, the
threads that get spawned which are internal to the libc implementation
use reserve rather than commit memory, which shaves a few hundred kb.
- sigaltstack() is now supported on Windows, however it's currently not
able to be used to handle stack overflows, since crash signals are
still generated by WIN32. However the crash handler will still switch
to the alt stack, which is helpful in environments with tiny threads.
- Test binaries are now smaller. Many of the mandatory dependencies of
the test runner have been removed. This ensures many programs can do a
better job only linking the the thing they're testing. This caused the
test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb
- long double is no longer used in the implementation details of libc,
except in the APIs that define it. The old code that used long double
for time (instead of struct timespec) has now been thoroughly removed.
- ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing
backtraces itself, it'll just print a command you can run on the shell
using our new `cosmoaddr2line` program to view the backtrace.
- Crash report signal handling now works in a much better way. Instead
of terminating the process, it now relies on SA_RESETHAND so that the
default SIG_IGN behavior can terminate the process if necessary.
- Our pledge() functionality has now been fully ported to AARCH64 Linux.
2023-09-19 03:44:45 +00:00
|
|
|
pthread_yield();
|
2022-04-28 16:42:36 +00:00
|
|
|
core = TSC_AUX_CORE(Rdpid());
|
|
|
|
interrupts = GetInterrupts();
|
|
|
|
for (avgticks = iter = 1; iter < count; ++iter) {
|
|
|
|
lua_pushcfunction(L, DoNothing);
|
|
|
|
t1 = __startbench_m();
|
|
|
|
lua_call(L, 0, 0);
|
|
|
|
t2 = __endbench_m();
|
|
|
|
avgticks += 1. / iter * ((int)(t2 - t1) - avgticks);
|
|
|
|
}
|
|
|
|
++attempts;
|
|
|
|
if (TSC_AUX_CORE(Rdpid()) == core && GetInterrupts() == interrupts) {
|
|
|
|
break;
|
|
|
|
} else if (attempts >= maxattempts) {
|
2022-05-29 15:14:55 +00:00
|
|
|
luaL_error(L, "system is under too much load to run benchmark");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-04-28 16:42:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
overhead = avgticks;
|
|
|
|
|
|
|
|
for (attempts = 0;;) {
|
|
|
|
lua_gc(L, LUA_GCCOLLECT);
|
Make improvements
- Every unit test now passes on Apple Silicon. The final piece of this
puzzle was porting our POSIX threads cancelation support, since that
works differently on ARM64 XNU vs. AMD64. Our semaphore support on
Apple Silicon is also superior now compared to AMD64, thanks to the
grand central dispatch library which lets *NSYNC locks go faster.
- The Cosmopolitan runtime is now more stable, particularly on Windows.
To do this, thread local storage is mandatory at all runtime levels,
and the innermost packages of the C library is no longer being built
using ASAN. TLS is being bootstrapped with a 128-byte TIB during the
process startup phase, and then later on the runtime re-allocates it
either statically or dynamically to support code using _Thread_local.
fork() and execve() now do a better job cooperating with threads. We
can now check how much stack memory is left in the process or thread
when functions like kprintf() / execve() etc. call alloca(), so that
ENOMEM can be raised, reduce a buffer size, or just print a warning.
- POSIX signal emulation is now implemented the same way kernels do it
with pthread_kill() and raise(). Any thread can interrupt any other
thread, regardless of what it's doing. If it's blocked on read/write
then the killer thread will cancel its i/o operation so that EINTR can
be returned in the mark thread immediately. If it's doing a tight CPU
bound operation, then that's also interrupted by the signal delivery.
Signal delivery works now by suspending a thread and pushing context
data structures onto its stack, and redirecting its execution to a
trampoline function, which calls SetThreadContext(GetCurrentThread())
when it's done.
- We're now doing a better job managing locks and handles. On NetBSD we
now close semaphore file descriptors in forked children. Semaphores on
Windows can now be canceled immediately, which means mutexes/condition
variables will now go faster. Apple Silicon semaphores can be canceled
too. We're now using Apple's pthread_yield() funciton. Apple _nocancel
syscalls are now used on XNU when appropriate to ensure pthread_cancel
requests aren't lost. The MbedTLS library has been updated to support
POSIX thread cancelations. See tool/build/runitd.c for an example of
how it can be used for production multi-threaded tls servers. Handles
on Windows now leak less often across processes. All i/o operations on
Windows are now overlapped, which means file pointers can no longer be
inherited across dup() and fork() for the time being.
- We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4()
which means, for example, that posix_spawn() now goes 3x faster. POSIX
spawn is also now more correct. Like Musl, it's now able to report the
failure code of execve() via a pipe although our approach favors using
shared memory to do that on systems that have a true vfork() function.
- We now spawn a thread to deliver SIGALRM to threads when setitimer()
is used. This enables the most precise wakeups the OS makes possible.
- The Cosmopolitan runtime now uses less memory. On NetBSD for example,
it turned out the kernel would actually commit the PT_GNU_STACK size
which caused RSS to be 6mb for every process. Now it's down to ~4kb.
On Apple Silicon, we reduce the mandatory upstream thread size to the
smallest possible size to reduce the memory overhead of Cosmo threads.
The examples directory has a program called greenbean which can spawn
a web server on Linux with 10,000 worker threads and have the memory
usage of the process be ~77mb. The 1024 byte overhead of POSIX-style
thread-local storage is now optional; it won't be allocated until the
pthread_setspecific/getspecific functions are called. On Windows, the
threads that get spawned which are internal to the libc implementation
use reserve rather than commit memory, which shaves a few hundred kb.
- sigaltstack() is now supported on Windows, however it's currently not
able to be used to handle stack overflows, since crash signals are
still generated by WIN32. However the crash handler will still switch
to the alt stack, which is helpful in environments with tiny threads.
- Test binaries are now smaller. Many of the mandatory dependencies of
the test runner have been removed. This ensures many programs can do a
better job only linking the the thing they're testing. This caused the
test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb
- long double is no longer used in the implementation details of libc,
except in the APIs that define it. The old code that used long double
for time (instead of struct timespec) has now been thoroughly removed.
- ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing
backtraces itself, it'll just print a command you can run on the shell
using our new `cosmoaddr2line` program to view the backtrace.
- Crash report signal handling now works in a much better way. Instead
of terminating the process, it now relies on SA_RESETHAND so that the
default SIG_IGN behavior can terminate the process if necessary.
- Our pledge() functionality has now been fully ported to AARCH64 Linux.
2023-09-19 03:44:45 +00:00
|
|
|
pthread_yield();
|
2022-04-25 15:30:14 +00:00
|
|
|
core = TSC_AUX_CORE(Rdpid());
|
|
|
|
interrupts = GetInterrupts();
|
|
|
|
for (avgticks = iter = 1; iter < count; ++iter) {
|
|
|
|
lua_pushvalue(L, 1);
|
2022-04-28 16:42:36 +00:00
|
|
|
t1 = __startbench_m();
|
2022-04-25 15:30:14 +00:00
|
|
|
lua_call(L, 0, 0);
|
2022-04-28 16:42:36 +00:00
|
|
|
t2 = __endbench_m();
|
2022-04-25 15:30:14 +00:00
|
|
|
avgticks += 1. / iter * ((int)(t2 - t1) - avgticks);
|
|
|
|
}
|
|
|
|
++attempts;
|
|
|
|
if (TSC_AUX_CORE(Rdpid()) == core && GetInterrupts() == interrupts) {
|
|
|
|
break;
|
|
|
|
} else if (attempts >= maxattempts) {
|
2022-05-29 15:14:55 +00:00
|
|
|
luaL_error(L, "system is under too much load to run benchmark");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-04-25 15:30:14 +00:00
|
|
|
}
|
|
|
|
}
|
2022-04-28 16:42:36 +00:00
|
|
|
avgticks = MAX(avgticks - overhead, 0);
|
|
|
|
|
|
|
|
lua_gc(L, LUA_GCRESTART);
|
Make improvements
- Every unit test now passes on Apple Silicon. The final piece of this
puzzle was porting our POSIX threads cancelation support, since that
works differently on ARM64 XNU vs. AMD64. Our semaphore support on
Apple Silicon is also superior now compared to AMD64, thanks to the
grand central dispatch library which lets *NSYNC locks go faster.
- The Cosmopolitan runtime is now more stable, particularly on Windows.
To do this, thread local storage is mandatory at all runtime levels,
and the innermost packages of the C library is no longer being built
using ASAN. TLS is being bootstrapped with a 128-byte TIB during the
process startup phase, and then later on the runtime re-allocates it
either statically or dynamically to support code using _Thread_local.
fork() and execve() now do a better job cooperating with threads. We
can now check how much stack memory is left in the process or thread
when functions like kprintf() / execve() etc. call alloca(), so that
ENOMEM can be raised, reduce a buffer size, or just print a warning.
- POSIX signal emulation is now implemented the same way kernels do it
with pthread_kill() and raise(). Any thread can interrupt any other
thread, regardless of what it's doing. If it's blocked on read/write
then the killer thread will cancel its i/o operation so that EINTR can
be returned in the mark thread immediately. If it's doing a tight CPU
bound operation, then that's also interrupted by the signal delivery.
Signal delivery works now by suspending a thread and pushing context
data structures onto its stack, and redirecting its execution to a
trampoline function, which calls SetThreadContext(GetCurrentThread())
when it's done.
- We're now doing a better job managing locks and handles. On NetBSD we
now close semaphore file descriptors in forked children. Semaphores on
Windows can now be canceled immediately, which means mutexes/condition
variables will now go faster. Apple Silicon semaphores can be canceled
too. We're now using Apple's pthread_yield() funciton. Apple _nocancel
syscalls are now used on XNU when appropriate to ensure pthread_cancel
requests aren't lost. The MbedTLS library has been updated to support
POSIX thread cancelations. See tool/build/runitd.c for an example of
how it can be used for production multi-threaded tls servers. Handles
on Windows now leak less often across processes. All i/o operations on
Windows are now overlapped, which means file pointers can no longer be
inherited across dup() and fork() for the time being.
- We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4()
which means, for example, that posix_spawn() now goes 3x faster. POSIX
spawn is also now more correct. Like Musl, it's now able to report the
failure code of execve() via a pipe although our approach favors using
shared memory to do that on systems that have a true vfork() function.
- We now spawn a thread to deliver SIGALRM to threads when setitimer()
is used. This enables the most precise wakeups the OS makes possible.
- The Cosmopolitan runtime now uses less memory. On NetBSD for example,
it turned out the kernel would actually commit the PT_GNU_STACK size
which caused RSS to be 6mb for every process. Now it's down to ~4kb.
On Apple Silicon, we reduce the mandatory upstream thread size to the
smallest possible size to reduce the memory overhead of Cosmo threads.
The examples directory has a program called greenbean which can spawn
a web server on Linux with 10,000 worker threads and have the memory
usage of the process be ~77mb. The 1024 byte overhead of POSIX-style
thread-local storage is now optional; it won't be allocated until the
pthread_setspecific/getspecific functions are called. On Windows, the
threads that get spawned which are internal to the libc implementation
use reserve rather than commit memory, which shaves a few hundred kb.
- sigaltstack() is now supported on Windows, however it's currently not
able to be used to handle stack overflows, since crash signals are
still generated by WIN32. However the crash handler will still switch
to the alt stack, which is helpful in environments with tiny threads.
- Test binaries are now smaller. Many of the mandatory dependencies of
the test runner have been removed. This ensures many programs can do a
better job only linking the the thing they're testing. This caused the
test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb
- long double is no longer used in the implementation details of libc,
except in the APIs that define it. The old code that used long double
for time (instead of struct timespec) has now been thoroughly removed.
- ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing
backtraces itself, it'll just print a command you can run on the shell
using our new `cosmoaddr2line` program to view the backtrace.
- Crash report signal handling now works in a much better way. Instead
of terminating the process, it now relies on SA_RESETHAND so that the
default SIG_IGN behavior can terminate the process if necessary.
- Our pledge() functionality has now been fully ported to AARCH64 Linux.
2023-09-19 03:44:45 +00:00
|
|
|
lua_pushinteger(L, avgticks / 3);
|
2022-04-28 16:42:36 +00:00
|
|
|
lua_pushinteger(L, round(avgticks));
|
|
|
|
lua_pushinteger(L, round(overhead));
|
2022-04-25 15:30:14 +00:00
|
|
|
lua_pushinteger(L, attempts);
|
2022-04-28 16:42:36 +00:00
|
|
|
return 4;
|
2022-04-25 15:30:14 +00:00
|
|
|
}
|
2022-05-16 23:49:20 +00:00
|
|
|
|
2022-05-29 15:14:55 +00:00
|
|
|
static void LuaCompress2(lua_State *L, void *dest, size_t *destLen,
|
|
|
|
const void *source, size_t sourceLen, int level) {
|
|
|
|
switch (compress2(dest, destLen, source, sourceLen, level)) {
|
|
|
|
case Z_OK:
|
|
|
|
break;
|
|
|
|
case Z_BUF_ERROR:
|
|
|
|
luaL_error(L, "out of memory");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-05-29 15:14:55 +00:00
|
|
|
case Z_STREAM_ERROR:
|
|
|
|
luaL_error(L, "invalid level");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-05-29 15:14:55 +00:00
|
|
|
default:
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-05-29 15:14:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-09 12:49:19 +00:00
|
|
|
// VERY DEPRECATED - PLEASE DO NOT USE
|
2022-05-16 23:49:20 +00:00
|
|
|
int LuaCompress(lua_State *L) {
|
|
|
|
size_t n, m;
|
|
|
|
char *q, *e;
|
|
|
|
uint32_t crc;
|
|
|
|
const char *p;
|
2022-05-29 21:47:14 +00:00
|
|
|
luaL_Buffer buf;
|
2022-05-16 23:49:20 +00:00
|
|
|
int level, hdrlen;
|
|
|
|
p = luaL_checklstring(L, 1, &n);
|
|
|
|
level = luaL_optinteger(L, 2, Z_DEFAULT_COMPRESSION);
|
|
|
|
m = compressBound(n);
|
2022-05-17 17:41:23 +00:00
|
|
|
if (lua_toboolean(L, 3)) {
|
|
|
|
// raw mode
|
2022-05-29 21:47:14 +00:00
|
|
|
q = luaL_buffinitsize(L, &buf, m);
|
2022-05-29 15:14:55 +00:00
|
|
|
LuaCompress2(L, q, &m, p, n, level);
|
2022-05-17 17:41:23 +00:00
|
|
|
} else {
|
|
|
|
// easy mode
|
2022-05-29 21:47:14 +00:00
|
|
|
q = luaL_buffinitsize(L, &buf, 10 + 4 + m);
|
2022-05-17 17:41:23 +00:00
|
|
|
crc = crc32_z(0, p, n);
|
|
|
|
e = uleb64(q, n);
|
|
|
|
e = WRITE32LE(e, crc);
|
|
|
|
hdrlen = e - q;
|
2022-05-29 15:14:55 +00:00
|
|
|
LuaCompress2(L, q + hdrlen, &m, p, n, level);
|
2022-05-29 21:47:14 +00:00
|
|
|
m += hdrlen;
|
2022-05-17 17:41:23 +00:00
|
|
|
}
|
2022-05-29 21:47:14 +00:00
|
|
|
luaL_pushresultsize(&buf, m);
|
2022-05-16 23:49:20 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2022-07-09 12:49:19 +00:00
|
|
|
// VERY DEPRECATED - PLEASE DO NOT USE
|
2022-05-16 23:49:20 +00:00
|
|
|
int LuaUncompress(lua_State *L) {
|
2022-07-08 16:47:04 +00:00
|
|
|
int rc;
|
2022-05-16 23:49:20 +00:00
|
|
|
char *q;
|
|
|
|
uint32_t crc;
|
|
|
|
const char *p;
|
2022-05-29 21:47:14 +00:00
|
|
|
luaL_Buffer buf;
|
2022-05-16 23:49:20 +00:00
|
|
|
size_t n, m, len;
|
|
|
|
p = luaL_checklstring(L, 1, &n);
|
2022-05-17 17:41:23 +00:00
|
|
|
if (lua_isnoneornil(L, 2)) {
|
|
|
|
if ((rc = unuleb64(p, n, &m)) == -1 || n < rc + 4) {
|
|
|
|
luaL_error(L, "compressed value too short to be valid");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-05-17 17:41:23 +00:00
|
|
|
}
|
|
|
|
len = m;
|
|
|
|
crc = READ32LE(p + rc);
|
2022-05-29 21:47:14 +00:00
|
|
|
q = luaL_buffinitsize(L, &buf, m);
|
2022-05-17 17:41:23 +00:00
|
|
|
if (uncompress((void *)q, &m, (unsigned char *)p + rc + 4, n) != Z_OK ||
|
|
|
|
m != len || crc32_z(0, q, m) != crc) {
|
|
|
|
luaL_error(L, "compressed value is corrupted");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-05-17 17:41:23 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
len = m = luaL_checkinteger(L, 2);
|
2022-05-29 21:47:14 +00:00
|
|
|
q = luaL_buffinitsize(L, &buf, m);
|
2022-05-17 17:41:23 +00:00
|
|
|
if (uncompress((void *)q, &m, (void *)p, n) != Z_OK || m != len) {
|
|
|
|
luaL_error(L, "compressed value is corrupted");
|
2023-06-09 06:44:03 +00:00
|
|
|
__builtin_unreachable();
|
2022-05-17 17:41:23 +00:00
|
|
|
}
|
2022-05-16 23:49:20 +00:00
|
|
|
}
|
2022-05-29 21:47:14 +00:00
|
|
|
luaL_pushresultsize(&buf, m);
|
2022-05-16 23:49:20 +00:00
|
|
|
return 1;
|
|
|
|
}
|
2022-07-08 16:47:04 +00:00
|
|
|
|
|
|
|
// unix.deflate(uncompressed:str[, level:int])
|
|
|
|
// ├─→ compressed:str
|
|
|
|
// └─→ nil, error:str
|
|
|
|
int LuaDeflate(lua_State *L) {
|
|
|
|
char *out;
|
|
|
|
z_stream zs;
|
|
|
|
int rc, level;
|
|
|
|
const char *in;
|
|
|
|
luaL_Buffer buf;
|
|
|
|
size_t insize, outsize, actualoutsize;
|
|
|
|
in = luaL_checklstring(L, 1, &insize);
|
|
|
|
level = luaL_optinteger(L, 2, Z_DEFAULT_COMPRESSION);
|
|
|
|
outsize = compressBound(insize);
|
|
|
|
out = luaL_buffinitsize(L, &buf, outsize);
|
|
|
|
|
|
|
|
zs.next_in = (const uint8_t *)in;
|
|
|
|
zs.avail_in = insize;
|
|
|
|
zs.next_out = (uint8_t *)out;
|
|
|
|
zs.avail_out = outsize;
|
|
|
|
zs.zalloc = Z_NULL;
|
|
|
|
zs.zfree = Z_NULL;
|
|
|
|
|
|
|
|
if ((rc = deflateInit2(&zs, level, Z_DEFLATED, -MAX_WBITS, MAX_MEM_LEVEL,
|
|
|
|
Z_DEFAULT_STRATEGY)) != Z_OK) {
|
|
|
|
lua_pushnil(L);
|
|
|
|
lua_pushfstring(L, "%s() failed: %d", "deflateInit2", rc);
|
|
|
|
return 2;
|
|
|
|
}
|
|
|
|
|
|
|
|
rc = deflate(&zs, Z_FINISH);
|
|
|
|
actualoutsize = outsize - zs.avail_out;
|
|
|
|
deflateEnd(&zs);
|
|
|
|
|
|
|
|
if (rc != Z_STREAM_END) {
|
|
|
|
lua_pushnil(L);
|
|
|
|
lua_pushfstring(L, "%s() failed: %d", "deflate", rc);
|
|
|
|
return 2;
|
|
|
|
}
|
|
|
|
|
|
|
|
luaL_pushresultsize(&buf, actualoutsize);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
// unix.inflate(compressed:str, maxoutsize:int)
|
|
|
|
// ├─→ uncompressed:str
|
|
|
|
// └─→ nil, error:str
|
|
|
|
int LuaInflate(lua_State *L) {
|
|
|
|
int rc;
|
|
|
|
char *out;
|
|
|
|
z_stream zs;
|
|
|
|
const char *in;
|
|
|
|
luaL_Buffer buf;
|
|
|
|
size_t insize, outsize, actualoutsize;
|
|
|
|
in = luaL_checklstring(L, 1, &insize);
|
|
|
|
outsize = luaL_checkinteger(L, 2);
|
|
|
|
out = luaL_buffinitsize(L, &buf, outsize);
|
|
|
|
|
|
|
|
zs.next_in = (const uint8_t *)in;
|
|
|
|
zs.avail_in = insize;
|
|
|
|
zs.total_in = insize;
|
|
|
|
zs.next_out = (uint8_t *)out;
|
|
|
|
zs.avail_out = outsize;
|
|
|
|
zs.total_out = outsize;
|
|
|
|
zs.zalloc = Z_NULL;
|
|
|
|
zs.zfree = Z_NULL;
|
|
|
|
|
|
|
|
if ((rc = inflateInit2(&zs, -MAX_WBITS)) != Z_OK) {
|
|
|
|
lua_pushnil(L);
|
|
|
|
lua_pushfstring(L, "%s() failed: %d", "inflateInit2", rc);
|
|
|
|
return 2;
|
|
|
|
}
|
|
|
|
|
|
|
|
rc = inflate(&zs, Z_FINISH);
|
|
|
|
actualoutsize = outsize - zs.avail_out;
|
|
|
|
inflateEnd(&zs);
|
|
|
|
|
|
|
|
if (rc != Z_STREAM_END) {
|
|
|
|
lua_pushnil(L);
|
|
|
|
lua_pushfstring(L, "%s() failed: %d", "inflate", rc);
|
|
|
|
return 2;
|
|
|
|
}
|
|
|
|
|
|
|
|
luaL_pushresultsize(&buf, actualoutsize);
|
|
|
|
return 1;
|
|
|
|
}
|