2022-04-24 16:59:22 +00:00
|
|
|
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
|
2023-12-08 03:11:56 +00:00
|
|
|
│ vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi │
|
2022-04-24 16:59:22 +00:00
|
|
|
╚──────────────────────────────────────────────────────────────────────────────╝
|
|
|
|
│ │
|
|
|
|
│ Lua │
|
|
|
|
│ Copyright © 2004-2021 Lua.org, PUC-Rio. │
|
|
|
|
│ │
|
|
|
|
│ Permission is hereby granted, free of charge, to any person obtaining │
|
|
|
|
│ a copy of this software and associated documentation files (the │
|
|
|
|
│ "Software"), to deal in the Software without restriction, including │
|
|
|
|
│ without limitation the rights to use, copy, modify, merge, publish, │
|
|
|
|
│ distribute, sublicense, and/or sell copies of the Software, and to │
|
|
|
|
│ permit persons to whom the Software is furnished to do so, subject to │
|
|
|
|
│ the following conditions: │
|
|
|
|
│ │
|
|
|
|
│ The above copyright notice and this permission notice shall be │
|
|
|
|
│ included in all copies or substantial portions of the Software. │
|
|
|
|
│ │
|
|
|
|
│ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │
|
|
|
|
│ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │
|
|
|
|
│ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │
|
|
|
|
│ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │
|
|
|
|
│ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │
|
|
|
|
│ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │
|
|
|
|
│ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │
|
|
|
|
│ │
|
|
|
|
╚─────────────────────────────────────────────────────────────────────────────*/
|
2021-03-02 13:51:10 +00:00
|
|
|
#define loslib_c
|
|
|
|
#define LUA_LIB
|
2021-03-07 21:26:57 +00:00
|
|
|
#include "libc/calls/calls.h"
|
|
|
|
#include "libc/calls/weirdtypes.h"
|
|
|
|
#include "libc/errno.h"
|
2021-03-08 05:07:16 +00:00
|
|
|
#include "libc/runtime/runtime.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/str/locale.h"
|
2022-08-11 07:15:29 +00:00
|
|
|
#include "libc/str/str.h"
|
2021-03-07 21:26:57 +00:00
|
|
|
#include "libc/sysv/consts/exit.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/temp.h"
|
2024-05-05 06:05:36 +00:00
|
|
|
#include "libc/time.h"
|
2021-03-07 21:26:57 +00:00
|
|
|
#include "third_party/lua/lauxlib.h"
|
|
|
|
#include "third_party/lua/lprefix.h"
|
|
|
|
#include "third_party/lua/lua.h"
|
|
|
|
#include "third_party/lua/lualib.h"
|
Release Cosmopolitan v3.3
This change upgrades to GCC 12.3 and GNU binutils 2.42. The GNU linker
appears to have changed things so that only a single de-duplicated str
table is present in the binary, and it gets placed wherever the linker
wants, regardless of what the linker script says. To cope with that we
need to stop using .ident to embed licenses. As such, this change does
significant work to revamp how third party licenses are defined in the
codebase, using `.section .notice,"aR",@progbits`.
This new GCC 12.3 toolchain has support for GNU indirect functions. It
lets us support __target_clones__ for the first time. This is used for
optimizing the performance of libc string functions such as strlen and
friends so far on x86, by ensuring AVX systems favor a second codepath
that uses VEX encoding. It shaves some latency off certain operations.
It's a useful feature to have for scientific computing for the reasons
explained by the test/libcxx/openmp_test.cc example which compiles for
fifteen different microarchitectures. Thanks to the upgrades, it's now
also possible to use newer instruction sets, such as AVX512FP16, VNNI.
Cosmo now uses the %gs register on x86 by default for TLS. Doing it is
helpful for any program that links `cosmo_dlopen()`. Such programs had
to recompile their binaries at startup to change the TLS instructions.
That's not great, since it means every page in the executable needs to
be faulted. The work of rewriting TLS-related x86 opcodes, is moved to
fixupobj.com instead. This is great news for MacOS x86 users, since we
previously needed to morph the binary every time for that platform but
now that's no longer necessary. The only platforms where we need fixup
of TLS x86 opcodes at runtime are now Windows, OpenBSD, and NetBSD. On
Windows we morph TLS to point deeper into the TIB, based on a TlsAlloc
assignment, and on OpenBSD/NetBSD we morph %gs back into %fs since the
kernels do not allow us to specify a value for the %gs register.
OpenBSD users are now required to use APE Loader to run Cosmo binaries
and assimilation is no longer possible. OpenBSD kernel needs to change
to allow programs to specify a value for the %gs register, or it needs
to stop marking executable pages loaded by the kernel as mimmutable().
This release fixes __constructor__, .ctor, .init_array, and lastly the
.preinit_array so they behave the exact same way as glibc.
We no longer use hex constants to define math.h symbols like M_PI.
2024-02-20 19:12:09 +00:00
|
|
|
__static_yoink("lua_notice");
|
2021-03-07 21:26:57 +00:00
|
|
|
|
2021-03-02 13:51:10 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
** {==================================================================
|
|
|
|
** List of valid conversion specifiers for the 'strftime' function;
|
|
|
|
** options are grouped by length; group of length 2 start with '||'.
|
|
|
|
** ===================================================================
|
|
|
|
*/
|
|
|
|
#if !defined(LUA_STRFTIMEOPTIONS) /* { */
|
|
|
|
|
|
|
|
/* options for ANSI C 89 (only 1-char options) */
|
|
|
|
#define L_STRFTIMEC89 "aAbBcdHIjmMpSUwWxXyYZ%"
|
|
|
|
|
|
|
|
/* options for ISO C 99 and POSIX */
|
|
|
|
#define L_STRFTIMEC99 "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%" \
|
|
|
|
"||" "EcECExEXEyEY" "OdOeOHOIOmOMOSOuOUOVOwOWOy" /* two-char options */
|
|
|
|
|
|
|
|
/* options for Windows */
|
|
|
|
#define L_STRFTIMEWIN "aAbBcdHIjmMpSUwWxXyYzZ%" \
|
|
|
|
"||" "#c#x#d#H#I#j#m#M#S#U#w#W#y#Y" /* two-char options */
|
|
|
|
|
|
|
|
#if defined(LUA_USE_WINDOWS)
|
|
|
|
#define LUA_STRFTIMEOPTIONS L_STRFTIMEWIN
|
|
|
|
#elif defined(LUA_USE_C89)
|
|
|
|
#define LUA_STRFTIMEOPTIONS L_STRFTIMEC89
|
|
|
|
#else /* C99 specification */
|
|
|
|
#define LUA_STRFTIMEOPTIONS L_STRFTIMEC99
|
|
|
|
#endif
|
|
|
|
|
|
|
|
#endif /* } */
|
|
|
|
/* }================================================================== */
|
|
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
** {==================================================================
|
|
|
|
** Configuration for time-related stuff
|
|
|
|
** ===================================================================
|
|
|
|
*/
|
|
|
|
|
|
|
|
/*
|
|
|
|
** type to represent time_t in Lua
|
|
|
|
*/
|
|
|
|
#if !defined(LUA_NUMTIME) /* { */
|
|
|
|
|
|
|
|
#define l_timet lua_Integer
|
|
|
|
#define l_pushtime(L,t) lua_pushinteger(L,(lua_Integer)(t))
|
|
|
|
#define l_gettime(L,arg) luaL_checkinteger(L, arg)
|
|
|
|
|
|
|
|
#else /* }{ */
|
|
|
|
|
|
|
|
#define l_timet lua_Number
|
|
|
|
#define l_pushtime(L,t) lua_pushnumber(L,(lua_Number)(t))
|
|
|
|
#define l_gettime(L,arg) luaL_checknumber(L, arg)
|
|
|
|
|
|
|
|
#endif /* } */
|
|
|
|
|
|
|
|
|
|
|
|
#if !defined(l_gmtime) /* { */
|
|
|
|
/*
|
|
|
|
** By default, Lua uses gmtime/localtime, except when POSIX is available,
|
|
|
|
** where it uses gmtime_r/localtime_r
|
|
|
|
*/
|
|
|
|
|
|
|
|
#if defined(LUA_USE_POSIX) /* { */
|
|
|
|
|
|
|
|
#define l_gmtime(t,r) gmtime_r(t,r)
|
|
|
|
#define l_localtime(t,r) localtime_r(t,r)
|
|
|
|
|
|
|
|
#else /* }{ */
|
|
|
|
|
|
|
|
/* ISO C definitions */
|
|
|
|
#define l_gmtime(t,r) ((void)(r)->tm_sec, gmtime(t))
|
|
|
|
#define l_localtime(t,r) ((void)(r)->tm_sec, localtime(t))
|
|
|
|
|
|
|
|
#endif /* } */
|
|
|
|
|
|
|
|
#endif /* } */
|
|
|
|
|
|
|
|
/* }================================================================== */
|
|
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
** {==================================================================
|
|
|
|
** Configuration for 'tmpnam':
|
|
|
|
** By default, Lua uses tmpnam except when POSIX is available, where
|
|
|
|
** it uses mkstemp.
|
|
|
|
** ===================================================================
|
|
|
|
*/
|
|
|
|
#if !defined(lua_tmpnam) /* { */
|
|
|
|
|
|
|
|
#if defined(LUA_USE_POSIX) /* { */
|
|
|
|
|
2024-05-20 07:46:27 +00:00
|
|
|
#define LUA_TMPNAMBUFSIZE 128
|
2021-03-02 13:51:10 +00:00
|
|
|
|
|
|
|
#define lua_tmpnam(b,e) { \
|
2024-05-20 07:46:27 +00:00
|
|
|
strlcpy(b, __get_tmpdir(), LUA_TMPNAMBUFSIZE); \
|
|
|
|
e = strlcat(b, "lua_XXXXXX", LUA_TMPNAMBUFSIZE) >= LUA_TMPNAMBUFSIZE; \
|
|
|
|
e = e ? -1 : mkstemp(b); \
|
2021-03-02 13:51:10 +00:00
|
|
|
if (e != -1) close(e); \
|
|
|
|
e = (e == -1); }
|
|
|
|
|
|
|
|
#else /* }{ */
|
|
|
|
|
|
|
|
/* ISO C definitions */
|
|
|
|
#define LUA_TMPNAMBUFSIZE L_tmpnam
|
|
|
|
#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); }
|
|
|
|
|
|
|
|
#endif /* } */
|
|
|
|
|
|
|
|
#endif /* } */
|
|
|
|
/* }================================================================== */
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
static int os_execute (lua_State *L) {
|
|
|
|
const char *cmd = luaL_optstring(L, 1, NULL);
|
|
|
|
int stat;
|
|
|
|
errno = 0;
|
|
|
|
stat = system(cmd);
|
|
|
|
if (cmd != NULL)
|
|
|
|
return luaL_execresult(L, stat);
|
|
|
|
else {
|
|
|
|
lua_pushboolean(L, stat); /* true if there is a shell */
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static int os_remove (lua_State *L) {
|
|
|
|
const char *filename = luaL_checkstring(L, 1);
|
|
|
|
return luaL_fileresult(L, remove(filename) == 0, filename);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static int os_rename (lua_State *L) {
|
|
|
|
const char *fromname = luaL_checkstring(L, 1);
|
|
|
|
const char *toname = luaL_checkstring(L, 2);
|
|
|
|
return luaL_fileresult(L, rename(fromname, toname) == 0, NULL);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static int os_tmpname (lua_State *L) {
|
|
|
|
char buff[LUA_TMPNAMBUFSIZE];
|
|
|
|
int err;
|
|
|
|
lua_tmpnam(buff, err);
|
2021-07-28 16:26:35 +00:00
|
|
|
if (l_unlikely(err))
|
2021-03-02 13:51:10 +00:00
|
|
|
return luaL_error(L, "unable to generate a unique filename");
|
|
|
|
lua_pushstring(L, buff);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static int os_getenv (lua_State *L) {
|
|
|
|
lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static int os_clock (lua_State *L) {
|
|
|
|
lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
** {======================================================
|
|
|
|
** Time/Date operations
|
|
|
|
** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
|
|
|
|
** wday=%w+1, yday=%j, isdst=? }
|
|
|
|
** =======================================================
|
|
|
|
*/
|
|
|
|
|
|
|
|
/*
|
|
|
|
** About the overflow check: an overflow cannot occur when time
|
|
|
|
** is represented by a lua_Integer, because either lua_Integer is
|
|
|
|
** large enough to represent all int fields or it is not large enough
|
|
|
|
** to represent a time that cause a field to overflow. However, if
|
|
|
|
** times are represented as doubles and lua_Integer is int, then the
|
|
|
|
** time 0x1.e1853b0d184f6p+55 would cause an overflow when adding 1900
|
|
|
|
** to compute the year.
|
|
|
|
*/
|
|
|
|
static void setfield (lua_State *L, const char *key, int value, int delta) {
|
|
|
|
#if (defined(LUA_NUMTIME) && LUA_MAXINTEGER <= INT_MAX)
|
2021-07-28 16:26:35 +00:00
|
|
|
if (l_unlikely(value > LUA_MAXINTEGER - delta))
|
2021-03-02 13:51:10 +00:00
|
|
|
luaL_error(L, "field '%s' is out-of-bound", key);
|
|
|
|
#endif
|
|
|
|
lua_pushinteger(L, (lua_Integer)value + delta);
|
|
|
|
lua_setfield(L, -2, key);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static void setboolfield (lua_State *L, const char *key, int value) {
|
|
|
|
if (value < 0) /* undefined? */
|
|
|
|
return; /* does not set field */
|
|
|
|
lua_pushboolean(L, value);
|
|
|
|
lua_setfield(L, -2, key);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
** Set all fields from structure 'tm' in the table on top of the stack
|
|
|
|
*/
|
|
|
|
static void setallfields (lua_State *L, struct tm *stm) {
|
|
|
|
setfield(L, "year", stm->tm_year, 1900);
|
|
|
|
setfield(L, "month", stm->tm_mon, 1);
|
|
|
|
setfield(L, "day", stm->tm_mday, 0);
|
|
|
|
setfield(L, "hour", stm->tm_hour, 0);
|
|
|
|
setfield(L, "min", stm->tm_min, 0);
|
|
|
|
setfield(L, "sec", stm->tm_sec, 0);
|
|
|
|
setfield(L, "yday", stm->tm_yday, 1);
|
|
|
|
setfield(L, "wday", stm->tm_wday, 1);
|
|
|
|
setboolfield(L, "isdst", stm->tm_isdst);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static int getboolfield (lua_State *L, const char *key) {
|
|
|
|
int res;
|
|
|
|
res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1);
|
|
|
|
lua_pop(L, 1);
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static int getfield (lua_State *L, const char *key, int d, int delta) {
|
|
|
|
int isnum;
|
|
|
|
int t = lua_getfield(L, -1, key); /* get field and its type */
|
|
|
|
lua_Integer res = lua_tointegerx(L, -1, &isnum);
|
|
|
|
if (!isnum) { /* field is not an integer? */
|
2021-07-28 16:26:35 +00:00
|
|
|
if (l_unlikely(t != LUA_TNIL)) /* some other value? */
|
2021-03-02 13:51:10 +00:00
|
|
|
return luaL_error(L, "field '%s' is not an integer", key);
|
2021-07-28 16:26:35 +00:00
|
|
|
else if (l_unlikely(d < 0)) /* absent field; no default? */
|
2021-03-02 13:51:10 +00:00
|
|
|
return luaL_error(L, "field '%s' missing in date table", key);
|
|
|
|
res = d;
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
/* unsigned avoids overflow when lua_Integer has 32 bits */
|
|
|
|
if (!(res >= 0 ? (lua_Unsigned)res <= (lua_Unsigned)INT_MAX + delta
|
|
|
|
: (lua_Integer)INT_MIN + delta <= res))
|
|
|
|
return luaL_error(L, "field '%s' is out-of-bound", key);
|
|
|
|
res -= delta;
|
|
|
|
}
|
|
|
|
lua_pop(L, 1);
|
|
|
|
return (int)res;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static const char *checkoption (lua_State *L, const char *conv,
|
|
|
|
ptrdiff_t convlen, char *buff) {
|
|
|
|
const char *option = LUA_STRFTIMEOPTIONS;
|
|
|
|
int oplen = 1; /* length of options being checked */
|
|
|
|
for (; *option != '\0' && oplen <= convlen; option += oplen) {
|
|
|
|
if (*option == '|') /* next block? */
|
|
|
|
oplen++; /* will check options with next length (+1) */
|
|
|
|
else if (memcmp(conv, option, oplen) == 0) { /* match? */
|
|
|
|
memcpy(buff, conv, oplen); /* copy valid option to buffer */
|
|
|
|
buff[oplen] = '\0';
|
|
|
|
return conv + oplen; /* return next item */
|
|
|
|
}
|
|
|
|
}
|
|
|
|
luaL_argerror(L, 1,
|
|
|
|
lua_pushfstring(L, "invalid conversion specifier '%%%s'", conv));
|
|
|
|
return conv; /* to avoid warnings */
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static time_t l_checktime (lua_State *L, int arg) {
|
|
|
|
l_timet t = l_gettime(L, arg);
|
|
|
|
luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds");
|
|
|
|
return (time_t)t;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* maximum size for an individual 'strftime' item */
|
|
|
|
#define SIZETIMEFMT 250
|
|
|
|
|
|
|
|
|
|
|
|
static int os_date (lua_State *L) {
|
|
|
|
size_t slen;
|
|
|
|
const char *s = luaL_optlstring(L, 1, "%c", &slen);
|
|
|
|
time_t t = luaL_opt(L, l_checktime, 2, time(NULL));
|
|
|
|
const char *se = s + slen; /* 's' end */
|
|
|
|
struct tm tmr, *stm;
|
|
|
|
if (*s == '!') { /* UTC? */
|
|
|
|
stm = l_gmtime(&t, &tmr);
|
|
|
|
s++; /* skip '!' */
|
|
|
|
}
|
|
|
|
else
|
|
|
|
stm = l_localtime(&t, &tmr);
|
|
|
|
if (stm == NULL) /* invalid date? */
|
|
|
|
return luaL_error(L,
|
|
|
|
"date result cannot be represented in this installation");
|
|
|
|
if (strcmp(s, "*t") == 0) {
|
|
|
|
lua_createtable(L, 0, 9); /* 9 = number of fields */
|
|
|
|
setallfields(L, stm);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
char cc[4]; /* buffer for individual conversion specifiers */
|
|
|
|
luaL_Buffer b;
|
|
|
|
cc[0] = '%';
|
|
|
|
luaL_buffinit(L, &b);
|
|
|
|
while (s < se) {
|
|
|
|
if (*s != '%') /* not a conversion specifier? */
|
|
|
|
luaL_addchar(&b, *s++);
|
|
|
|
else {
|
|
|
|
size_t reslen;
|
|
|
|
char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT);
|
|
|
|
s++; /* skip '%' */
|
|
|
|
s = checkoption(L, s, se - s, cc + 1); /* copy specifier to 'cc' */
|
|
|
|
reslen = strftime(buff, SIZETIMEFMT, cc, stm);
|
|
|
|
luaL_addsize(&b, reslen);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
luaL_pushresult(&b);
|
|
|
|
}
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static int os_time (lua_State *L) {
|
|
|
|
time_t t;
|
|
|
|
if (lua_isnoneornil(L, 1)) /* called without args? */
|
|
|
|
t = time(NULL); /* get current time */
|
|
|
|
else {
|
|
|
|
struct tm ts;
|
|
|
|
luaL_checktype(L, 1, LUA_TTABLE);
|
|
|
|
lua_settop(L, 1); /* make sure table is at the top */
|
|
|
|
ts.tm_year = getfield(L, "year", -1, 1900);
|
|
|
|
ts.tm_mon = getfield(L, "month", -1, 1);
|
|
|
|
ts.tm_mday = getfield(L, "day", -1, 0);
|
|
|
|
ts.tm_hour = getfield(L, "hour", 12, 0);
|
|
|
|
ts.tm_min = getfield(L, "min", 0, 0);
|
|
|
|
ts.tm_sec = getfield(L, "sec", 0, 0);
|
|
|
|
ts.tm_isdst = getboolfield(L, "isdst");
|
|
|
|
t = mktime(&ts);
|
|
|
|
setallfields(L, &ts); /* update fields with normalized values */
|
|
|
|
}
|
|
|
|
if (t != (time_t)(l_timet)t || t == (time_t)(-1))
|
|
|
|
return luaL_error(L,
|
|
|
|
"time result cannot be represented in this installation");
|
|
|
|
l_pushtime(L, t);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static int os_difftime (lua_State *L) {
|
|
|
|
time_t t1 = l_checktime(L, 1);
|
|
|
|
time_t t2 = l_checktime(L, 2);
|
|
|
|
lua_pushnumber(L, (lua_Number)difftime(t1, t2));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* }====================================================== */
|
|
|
|
|
|
|
|
|
|
|
|
static int os_setlocale (lua_State *L) {
|
|
|
|
static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
|
|
|
|
LC_NUMERIC, LC_TIME};
|
|
|
|
static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
|
|
|
|
"numeric", "time", NULL};
|
|
|
|
const char *l = luaL_optstring(L, 1, NULL);
|
|
|
|
int op = luaL_checkoption(L, 2, "all", catnames);
|
|
|
|
lua_pushstring(L, setlocale(cat[op], l));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static int os_exit (lua_State *L) {
|
|
|
|
int status;
|
|
|
|
if (lua_isboolean(L, 1))
|
|
|
|
status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE);
|
|
|
|
else
|
|
|
|
status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS);
|
|
|
|
if (lua_toboolean(L, 2))
|
|
|
|
lua_close(L);
|
|
|
|
if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static const luaL_Reg syslib[] = {
|
|
|
|
{"clock", os_clock},
|
|
|
|
{"date", os_date},
|
|
|
|
{"difftime", os_difftime},
|
|
|
|
{"execute", os_execute},
|
|
|
|
{"exit", os_exit},
|
|
|
|
{"getenv", os_getenv},
|
|
|
|
{"remove", os_remove},
|
|
|
|
{"rename", os_rename},
|
|
|
|
{"setlocale", os_setlocale},
|
|
|
|
{"time", os_time},
|
|
|
|
{"tmpname", os_tmpname},
|
|
|
|
{NULL, NULL}
|
|
|
|
};
|
|
|
|
|
|
|
|
/* }====================================================== */
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
LUAMOD_API int luaopen_os (lua_State *L) {
|
|
|
|
luaL_newlib(L, syslib);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|