mirror of
https://github.com/jart/cosmopolitan.git
synced 2026-11-08 17:19:47 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
38df0a4186 | ||
|
|
1c0adb556d | ||
|
|
8aca94f951 | ||
|
|
38e3ab57a6 | ||
|
|
672ccda37c | ||
|
|
9849b4c7ba | ||
|
|
3421b9a580 | ||
|
|
29d695f4c9 | ||
|
|
7d6835c0dd | ||
|
|
05197afca2 | ||
|
|
bc353f454b | ||
|
|
7bc24888fe | ||
|
|
59ac141e49 | ||
|
|
60b68d7152 | ||
|
|
a5b483f2d4 | ||
|
|
d3efa47f81 | ||
|
|
7822917fc2 | ||
|
|
81ee11a16e | ||
|
|
f155205eb0 | ||
|
|
e46ef487a8 | ||
|
|
afc07b9339 | ||
|
|
edb8fef06c | ||
|
|
b75a4654cf | ||
|
|
fe3216e961 | ||
|
|
174d288e66 | ||
|
|
9f9b240f3d | ||
|
|
726f04e8aa | ||
|
|
556697cbd8 | ||
|
|
3ee3736a01 | ||
|
|
01bd7d1008 | ||
|
|
32321ab1e9 | ||
|
|
3b4fcd8575 | ||
|
|
6ba3b448f3 | ||
|
|
91e167caaf | ||
|
|
ccbae7799e | ||
|
|
af24c19db3 | ||
|
|
950a1b310b | ||
|
|
daca5499b9 | ||
|
|
2526a9b8c7 | ||
|
|
7549a5755e | ||
|
|
795d295590 | ||
|
|
3f3cb0650b | ||
|
|
acd8900071 | ||
|
|
6c60793f3a | ||
|
|
ad97775370 | ||
|
|
0b5f84dd20 | ||
|
|
27b5deefb1 | ||
|
|
ecb2ef7c39 | ||
|
|
304cf8869c | ||
|
|
3e0ddf70e9 | ||
|
|
5005f2e446 | ||
|
|
bc8532688b | ||
|
|
09811e739f | ||
|
|
24988f2351 | ||
|
|
b46f763ee7 | ||
|
|
87708c5d6e |
No files matched your search
@@ -21,8 +21,11 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: support ape bins
|
||||
run: sudo sh -c "echo ':APE:M::MZqFpD::/bin/sh:' >/proc/sys/fs/binfmt_misc/register"
|
||||
- name: support ape bins 1
|
||||
run: sudo cp build/bootstrap/ape.elf /usr/bin/ape
|
||||
|
||||
- name: support ape bins 2
|
||||
run: sudo sh -c "echo ':APE:M::MZqFpD::/usr/bin/ape:' >/proc/sys/fs/binfmt_misc/register"
|
||||
|
||||
- name: make matrix
|
||||
run: V=0 make -j2 MODE=${{ matrix.mode }}
|
||||
@@ -160,6 +160,7 @@ include net/https/https.mk # │
|
||||
include third_party/regex/regex.mk #─┘
|
||||
include third_party/tidy/tidy.mk
|
||||
include third_party/third_party.mk
|
||||
include third_party/nsync/testing/testing.mk
|
||||
include libc/testlib/testlib.mk
|
||||
include tool/viz/lib/vizlib.mk
|
||||
include tool/args/args.mk
|
||||
@@ -202,6 +203,7 @@ include tool/hash/hash.mk
|
||||
include tool/net/net.mk
|
||||
include tool/viz/viz.mk
|
||||
include tool/tool.mk
|
||||
include net/turfwar/turfwar.mk
|
||||
include test/libc/tinymath/test.mk
|
||||
include test/libc/intrin/test.mk
|
||||
include test/libc/mem/test.mk
|
||||
|
||||
@@ -23,8 +23,8 @@ If you're doing your development work on Linux or BSD then you need just
|
||||
five files to get started. Here's what you do on Linux:
|
||||
|
||||
```sh
|
||||
wget https://justine.lol/cosmopolitan/cosmopolitan-amalgamation-2.1.zip
|
||||
unzip cosmopolitan-amalgamation-2.1.zip
|
||||
wget https://justine.lol/cosmopolitan/cosmopolitan-amalgamation-2.1.1.zip
|
||||
unzip cosmopolitan-amalgamation-2.1.1.zip
|
||||
printf 'main() { printf("hello world\\n"); }\n' >hello.c
|
||||
gcc -g -Os -static -nostdlib -nostdinc -fno-pie -no-pie -mno-red-zone \
|
||||
-fno-omit-frame-pointer -pg -mnop-mcount -mno-tls-direct-seg-refs -gdwarf-4 \
|
||||
@@ -258,8 +258,10 @@ Funding for this project is crowdsourced using
|
||||
[GitHub Sponsors](https://github.com/sponsors/jart) and
|
||||
[Patreon](https://www.patreon.com/jart). Your support is what makes this
|
||||
project possible. Thank you! We'd also like to give special thanks to
|
||||
the following individuals:
|
||||
the following groups and individuals:
|
||||
|
||||
- [Joe Drumgoole](https://github.com/jdrumgoole)
|
||||
- [Rob Figueiredo](https://github.com/robfig)
|
||||
- [Wasmer](https://wasmer.io/)
|
||||
|
||||
For publicly sponsoring our work at the highest tier.
|
||||
@@ -125,6 +125,7 @@ ape_mz: .asciz "MZqFpD='\n" # Mark 'Zibo' Joseph Zbikowski
|
||||
.org 0x24 # MZ: bytes reserved for you
|
||||
.ascii "JT" # MZ: OEM identifier
|
||||
.short 0 # MZ: OEM information
|
||||
.ascii "' <<'@'\n"
|
||||
.org 0x40-4 # MZ: bytes reserved for you
|
||||
#if SupportsWindows() || SupportsMetal()
|
||||
.long RVA(ape_pe) # PE: the new technology
|
||||
@@ -250,7 +251,6 @@ pc: cld
|
||||
xor %cx,%cx # current cylinder
|
||||
xor %dh,%dh # current head
|
||||
mov $v_ape_realsectors,%di # total sectors
|
||||
sub $v_ape_realslacksectors,%di
|
||||
3: call pcread
|
||||
dec %di
|
||||
jnz 3b
|
||||
@@ -549,7 +549,7 @@ ape_disk:
|
||||
the bourne executable & linkable format */
|
||||
|
||||
#if SupportsWindows() || SupportsMetal() || SupportsXnu()
|
||||
apesh: .ascii "'\n#'\"\n" # sixth edition shebang
|
||||
apesh: .ascii "\n@\n#'\"\n" # sixth edition shebang
|
||||
// Until all operating systems can be updated to support APE,
|
||||
// we have a beautiful, yet imperfect workaround, which is to
|
||||
// modify the binary to follow the local system's convention.
|
||||
@@ -1137,12 +1137,17 @@ sconf: .short 1843200/*hz*/ / 16/*wut*/ / 9600/*baud*/
|
||||
.endobj sconf,global,hidden
|
||||
|
||||
// Global Descriptor Table
|
||||
//
|
||||
// @note address portion only concern legacy modes
|
||||
.align 8
|
||||
gdt: .short 2f-1f # table byte length
|
||||
.long REAL(1f),0 # table address
|
||||
.zero 2
|
||||
_gdtrphy:
|
||||
.short 2f-1f-1 # table byte length
|
||||
.long REAL(1f) # table address (physical space)
|
||||
.endobj _gdtrphy,global,hidden
|
||||
_gdtr:
|
||||
.short 2f-1f-1 # table byte length
|
||||
.quad 1f # table address (final virtual space)
|
||||
.endobj _gdtr,global,hidden
|
||||
.align 8
|
||||
_gdt:
|
||||
1:
|
||||
// ┌G:granularity (1 → limit *= 0x1000)
|
||||
// │┌D/B:default operation size (0 = 16|64bit, 1 = 32-bit)
|
||||
@@ -1172,7 +1177,9 @@ gdt: .short 2f-1f # table byte length
|
||||
.quad 0b0000000011001111100100100000000000000000000000001111111111111111 #32
|
||||
.quad 0b0000000010101111100110110000000000000000000000001111111111111111 #40
|
||||
.quad 0b0000000010101111100100110000000000000000000000001111111111111111 #48
|
||||
2: .endobj gdt,global,hidden
|
||||
.tssdescstub _tss #56,64
|
||||
2:
|
||||
.endobj _gdt,global,hidden
|
||||
|
||||
/*─────────────────────────────────────────────────────────────────────────────╗
|
||||
│ αcτµαlly pδrταblε εxεcµταblε § real mode │
|
||||
@@ -1433,7 +1440,7 @@ golong: cli
|
||||
rdmsr
|
||||
or $EFER_LME|EFER_SCE,%eax
|
||||
wrmsr
|
||||
lgdt REAL(gdt)
|
||||
lgdt REAL(_gdtrphy)
|
||||
mov %cr0,%eax
|
||||
or $CR0_PE|CR0_PG|CR0_MP,%eax
|
||||
and $~CR0_EM,%eax
|
||||
@@ -1451,6 +1458,8 @@ long: xor %eax,%eax
|
||||
mov %eax,%fs
|
||||
mov %eax,%gs
|
||||
mov $0x80000,%esp
|
||||
mov $GDT_LONG_TSS,%al
|
||||
ltr %ax
|
||||
xor %r12d,%r12d
|
||||
xor %r13d,%r13d
|
||||
xor %r14d,%r14d
|
||||
@@ -1464,6 +1473,8 @@ long: xor %eax,%eax
|
||||
call __map_phdrs
|
||||
push $0x037f
|
||||
fldcw (%rsp)
|
||||
lgdt _gdtr # reload GDTR for
|
||||
# virtual memory space
|
||||
movabs $kernel,%rax
|
||||
jmp *%rax
|
||||
.endfn long
|
||||
@@ -1586,7 +1597,6 @@ kernel: movabs $ape_stack_vaddr,%rsp
|
||||
.ldsvar _end
|
||||
.ldsvar _etext
|
||||
.ldsvar v_ape_realsectors
|
||||
.ldsvar v_ape_realslacksectors
|
||||
.ldsvar v_ape_highsectors
|
||||
.ldsvar ape_idata_ro
|
||||
.ldsvar ape_pad_rodata
|
||||
|
||||
+5
-5
@@ -427,7 +427,7 @@ SECTIONS {
|
||||
|
||||
KEEP(*(.bssepilogue))
|
||||
/*END: NT FORK COPYING */
|
||||
. = ALIGN(FRAMESIZE); /* for brk()/sbrk() allocation */
|
||||
. = ALIGN(PAGESIZE);
|
||||
HIDDEN(_end = .);
|
||||
PROVIDE_HIDDEN(end = .);
|
||||
} :Bss
|
||||
@@ -565,13 +565,13 @@ SHSTUB2(ape_loader_dd_count,
|
||||
#if SupportsMetal()
|
||||
HIDDEN(v_ape_realsectors =
|
||||
MIN(0x70000 - IMAGE_BASE_REAL,
|
||||
ROUNDUP(RVA(_edata), 4096)) / 512);
|
||||
HIDDEN(v_ape_realslacksectors =
|
||||
v_ape_realsectors - MIN(0x70000 - IMAGE_BASE_REAL,
|
||||
ROUNDUP(RVA(_edata), 512)) / 512);
|
||||
ROUNDUP(RVA(_edata), 512)) / 512);
|
||||
HIDDEN(v_ape_realpages = v_ape_realsectors / (4096 / 512));
|
||||
HIDDEN(v_ape_highsectors =
|
||||
(ROUNDUP(RVA(_edata), 512) / 512) - v_ape_realsectors);
|
||||
PROVIDE_HIDDEN(_tss = 0);
|
||||
PROVIDE_HIDDEN(_tss_end = 0);
|
||||
TSSDESCSTUB2(_tss, _tss, _tss_end ? _tss_end - _tss - 1 : 0);
|
||||
#endif
|
||||
|
||||
/* ZIP End of Central Directory header */
|
||||
|
||||
@@ -180,6 +180,12 @@
|
||||
.stub \name\()_bcs\n,long
|
||||
.endm
|
||||
|
||||
// Task State Segment Descriptor Entries.
|
||||
.macro .tssdescstub name:req
|
||||
.stub \name\()_desc_ent0,quad
|
||||
.stub \name\()_desc_ent1,quad
|
||||
.endm
|
||||
|
||||
/* clang-format on */
|
||||
#elif defined(__LINKER__)
|
||||
|
||||
@@ -257,5 +263,22 @@
|
||||
(X) % 10 * 0x1000000 \
|
||||
: 0xffffffffffffffff)
|
||||
|
||||
/**
|
||||
* Laying out the GDT entries for a TSS for bare metal operation.
|
||||
*/
|
||||
#define TSSDESCSTUB2(SYM, BASE, LIM) \
|
||||
HIDDEN(SYM##_desc_ent0 = TSSDESC_ENT0(BASE, LIM)); \
|
||||
HIDDEN(SYM##_desc_ent1 = TSSDESC_ENT1(BASE)); \
|
||||
ASSERT((LIM) >= 0 && (LIM) <= 0xffff, "bare metal TSS is suspiciously fat")
|
||||
#define TSSDESC_ENT0(BASE, LIM) \
|
||||
(((LIM) << 0 & 0x000000000000ffff) | \
|
||||
((BASE) << 16 & 0x000000ffffff0000) | \
|
||||
0x89 << 40 | \
|
||||
((LIM) >> 16 << 48 & 0x000f000000000000) | \
|
||||
0x2 << 52 | \
|
||||
((BASE) >> 24 << 56 & 0xff00000000000000))
|
||||
#define TSSDESC_ENT1(BASE) \
|
||||
((BASE) >> 32 << 0 & 0x00000000ffffffff)
|
||||
|
||||
#endif /* __ASSEMBLER__ */
|
||||
#endif /* APE_MACROS_H_ */
|
||||
+15
-23
@@ -73,33 +73,25 @@ IMAGE_BASE_VIRTUAL ?= 0x400000
|
||||
IGNORE := $(shell $(ECHO) -2 ♥cosmo)
|
||||
IGNORE := $(shell $(MKDIR) o/tmp)
|
||||
|
||||
ifneq ("$(wildcard o/third_party/gcc/bin/x86_64-pc-linux-gnu-as.exe)","")
|
||||
AS = o/third_party/gcc/bin/x86_64-pc-linux-gnu-as.exe
|
||||
CC = o/third_party/gcc/bin/x86_64-pc-linux-gnu-gcc.exe
|
||||
CXX = o/third_party/gcc/bin/x86_64-pc-linux-gnu-g++.exe
|
||||
CXXFILT = o/third_party/gcc/bin/x86_64-pc-linux-gnu-c++filt.exe
|
||||
LD = o/third_party/gcc/bin/x86_64-pc-linux-gnu-ld.bfd.exe
|
||||
NM = o/third_party/gcc/bin/x86_64-pc-linux-gnu-nm.exe
|
||||
GCC = o/third_party/gcc/bin/x86_64-pc-linux-gnu-gcc.exe
|
||||
STRIP = o/third_party/gcc/bin/x86_64-pc-linux-gnu-strip.exe
|
||||
OBJCOPY = o/third_party/gcc/bin/x86_64-pc-linux-gnu-objcopy.exe
|
||||
OBJDUMP = o/third_party/gcc/bin/x86_64-pc-linux-gnu-objdump.exe
|
||||
ADDR2LINE = $(PWD)/o/third_party/gcc/bin/x86_64-pc-linux-gnu-addr2line.exe
|
||||
ifneq ("$(wildcard o/third_party/gcc/bin/x86_64-pc-linux-gnu-*)","")
|
||||
PREFIX = o/third_party/gcc/bin/x86_64-pc-linux-gnu-
|
||||
else
|
||||
IGNORE := $(shell build/bootstrap/unbundle.com)
|
||||
AS = o/third_party/gcc/bin/x86_64-linux-musl-as
|
||||
CC = o/third_party/gcc/bin/x86_64-linux-musl-gcc
|
||||
CXX = o/third_party/gcc/bin/x86_64-linux-musl-g++
|
||||
CXXFILT = o/third_party/gcc/bin/x86_64-linux-musl-c++filt
|
||||
LD = o/third_party/gcc/bin/x86_64-linux-musl-ld.bfd
|
||||
NM = o/third_party/gcc/bin/x86_64-linux-musl-nm
|
||||
GCC = o/third_party/gcc/bin/x86_64-linux-musl-gcc
|
||||
STRIP = o/third_party/gcc/bin/x86_64-linux-musl-strip
|
||||
OBJCOPY = o/third_party/gcc/bin/x86_64-linux-musl-objcopy
|
||||
OBJDUMP = o/third_party/gcc/bin/x86_64-linux-musl-objdump
|
||||
ADDR2LINE = $(PWD)/o/third_party/gcc/bin/x86_64-linux-musl-addr2line
|
||||
PREFIX = o/third_party/gcc/bin/x86_64-linux-musl-
|
||||
endif
|
||||
|
||||
AS = $(PREFIX)as
|
||||
CC = $(PREFIX)gcc
|
||||
CXX = $(PREFIX)g++
|
||||
CXXFILT = $(PREFIX)c++filt
|
||||
LD = $(PREFIX)ld.bfd
|
||||
NM = $(PREFIX)nm
|
||||
GCC = $(PREFIX)gcc
|
||||
STRIP = $(PREFIX)strip
|
||||
OBJCOPY = $(PREFIX)objcopy
|
||||
OBJDUMP = $(PREFIX)objdump
|
||||
ADDR2LINE = $(PWD)/$(PREFIX)addr2line
|
||||
|
||||
export ADDR2LINE
|
||||
export LC_ALL
|
||||
export MKDIR
|
||||
|
||||
@@ -167,7 +167,7 @@ void *Worker(void *id) {
|
||||
|
||||
// wait for client connection
|
||||
clientaddrsize = sizeof(clientaddr);
|
||||
client = accept(server, &clientaddr, &clientaddrsize);
|
||||
client = accept(server, (struct sockaddr *)&clientaddr, &clientaddrsize);
|
||||
|
||||
// accept() can raise a very diverse number of errors but none of
|
||||
// them are really true showstoppers that would necessitate us to
|
||||
|
||||
+2
-2
@@ -49,12 +49,12 @@ int main(int argc, char *argv[]) {
|
||||
printf("res = %d?\n", res);
|
||||
return -1;
|
||||
}
|
||||
printf("Hello World! %.19Lg\n", atan2l(x, y));
|
||||
printf("\e[92;44mHello World!\e[0m %.19Lg\n", atan2l(x, y));
|
||||
|
||||
// read/print loop so machine doesn't reset on metal
|
||||
for (;;) {
|
||||
if ((res = readansi(0, buf, 16)) > 0) {
|
||||
printf("got %`'.*s\r\n", res, buf);
|
||||
printf("got \e[97m%`'.*s\e[0m\r\n", res, buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#if 0
|
||||
/*─────────────────────────────────────────────────────────────────╗
|
||||
│ To the extent possible under law, Justine Tunney has waived │
|
||||
│ all copyright and related or neighboring rights to this file, │
|
||||
│ as it is written in the following disclaimers: │
|
||||
│ • http://unlicense.org/ │
|
||||
│ • http://creativecommons.org/publicdomain/zero/1.0/ │
|
||||
╚─────────────────────────────────────────────────────────────────*/
|
||||
#endif
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/termios.h"
|
||||
#include "libc/isystem/unistd.h"
|
||||
#include "libc/math.h"
|
||||
#include "libc/stdio/stdio.h"
|
||||
#include "libc/str/str.h"
|
||||
#include "libc/sysv/consts/termios.h"
|
||||
|
||||
/**
|
||||
* @fileoverview Demo of program crash reporting with Bare Metal VGA TTY.
|
||||
*
|
||||
* make -j8 o//examples/vga2.com
|
||||
* qemu-system-x86_64 -hda o//examples/vga2.com -serial stdio
|
||||
*/
|
||||
|
||||
STATIC_YOINK("vga_console");
|
||||
STATIC_YOINK("_idt");
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
volatile int x = 1;
|
||||
volatile int y = 2;
|
||||
printf("\e[92;44mHello World!\e[0m %d\n", 1 / (x + y - 3));
|
||||
for (;;);
|
||||
}
|
||||
@@ -19,7 +19,7 @@
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
|
||||
/**
|
||||
* Compares two nanosecond timestamps.
|
||||
* Compares nanosecond timestamps.
|
||||
*/
|
||||
int _timespec_cmp(struct timespec a, struct timespec b) {
|
||||
int cmp;
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
* @param ts receives `CLOCK_REALTIME` timestamp
|
||||
* @param base must be `TIME_UTC`
|
||||
* @return `base` on success, or `0` on failure
|
||||
* @see _timespec_real()
|
||||
*/
|
||||
int timespec_get(struct timespec *ts, int base) {
|
||||
if (base == TIME_UTC && !clock_gettime(CLOCK_REALTIME, ts)) {
|
||||
|
||||
@@ -20,6 +20,13 @@
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
|
||||
/**
|
||||
* Returns current monotonic time.
|
||||
*
|
||||
* This function uses a `CLOCK_MONOTONIC` clock and never fails.
|
||||
*
|
||||
* @see _timespec_real()
|
||||
*/
|
||||
struct timespec _timespec_mono(void) {
|
||||
struct timespec ts;
|
||||
_npassert(!clock_gettime(CLOCK_MONOTONIC_FAST, &ts));
|
||||
|
||||
@@ -20,6 +20,15 @@
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
|
||||
/**
|
||||
* Returns current time.
|
||||
*
|
||||
* This function uses a `CLOCK_REALTIME` clock and never fails. Unlike
|
||||
* clock_gettime() or timespec_real() this interface avoids the use of
|
||||
* pointers which lets time handling code become more elegant.
|
||||
*
|
||||
* @see _timespec_mono()
|
||||
*/
|
||||
struct timespec _timespec_real(void) {
|
||||
struct timespec ts;
|
||||
_npassert(!clock_gettime(CLOCK_REALTIME_FAST, &ts));
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*-*- 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 2021 Justine Alexandra Roberts Tunney │
|
||||
│ 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 │
|
||||
@@ -16,21 +16,23 @@
|
||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/assert.h"
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/calls/struct/timespec.internal.h"
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
#include "libc/calls/struct/timeval.internal.h"
|
||||
#include "libc/sysv/consts/at.h"
|
||||
#include "libc/errno.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
|
||||
textwindows int sys_utimes_nt(const char *path, const struct timeval tv[2]) {
|
||||
struct timespec ts[2];
|
||||
if (tv) {
|
||||
ts[0].tv_sec = tv[0].tv_sec;
|
||||
ts[0].tv_nsec = tv[0].tv_usec * 1000;
|
||||
ts[1].tv_sec = tv[1].tv_sec;
|
||||
ts[1].tv_nsec = tv[1].tv_usec * 1000;
|
||||
return sys_utimensat_nt(AT_FDCWD, path, ts, 0);
|
||||
/**
|
||||
* Sleeps for specified delay.
|
||||
*
|
||||
* @return unslept time which may be non-zero if the call was interrupted
|
||||
*/
|
||||
struct timespec _timespec_sleep(struct timespec delay) {
|
||||
int rc;
|
||||
struct timespec remain;
|
||||
if (!(rc = clock_nanosleep(CLOCK_REALTIME, 0, &delay, &remain))) {
|
||||
return (struct timespec){0};
|
||||
} else {
|
||||
return sys_utimensat_nt(AT_FDCWD, path, NULL, 0);
|
||||
_npassert(rc == EINTR);
|
||||
return remain;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/*-*- 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 2020 Justine Alexandra Roberts Tunney │
|
||||
│ 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 │
|
||||
@@ -17,20 +17,19 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/assert.h"
|
||||
#include "libc/intrin/weaken.h"
|
||||
#include "libc/limits.h"
|
||||
#include "libc/mem/mem.h"
|
||||
#include "third_party/zlib/zutil.internal.h"
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/errno.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
#include "libc/sysv/consts/timer.h"
|
||||
|
||||
void *zcalloc(void *opaque, uInt items, uInt size) {
|
||||
size_t res;
|
||||
if (__builtin_mul_overflow(items, size, &res)) return 0;
|
||||
if (res > INT_MAX) return 0;
|
||||
_npassert(_weaken(malloc));
|
||||
return _weaken(malloc)(res);
|
||||
}
|
||||
|
||||
void zcfree(void *opaque, void *ptr) {
|
||||
_npassert(_weaken(free));
|
||||
_weaken(free)(ptr);
|
||||
/**
|
||||
* Sleeps until the specified time.
|
||||
*
|
||||
* @return 0 on success, or EINTR if interrupted
|
||||
*/
|
||||
int _timespec_sleep_until(struct timespec abs_deadline) {
|
||||
int rc;
|
||||
rc = clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &abs_deadline, 0);
|
||||
_npassert(!rc || rc == EINTR);
|
||||
return rc;
|
||||
}
|
||||
@@ -20,14 +20,35 @@
|
||||
#include "libc/limits.h"
|
||||
|
||||
/**
|
||||
* Converts timespec interval to microseconds.
|
||||
* Reduces `ts` from 1e-9 to 1e-6 granularity w/ ceil rounding.
|
||||
*
|
||||
* This function uses ceiling rounding. For example, if `ts` is one
|
||||
* nanosecond, then one microsecond will be returned. Ceil rounding
|
||||
* is needed by many interfaces, e.g. setitimer(), because the zero
|
||||
* timestamp has a special meaning.
|
||||
*
|
||||
* This function also detects overflow in which case `INT64_MAX` or
|
||||
* `INT64_MIN` may be returned. The `errno` variable isn't changed.
|
||||
*
|
||||
* @return 64-bit scalar holding microseconds since epoch
|
||||
* @see _timespec_totimeval()
|
||||
*/
|
||||
int64_t _timespec_tomicros(struct timespec x) {
|
||||
int64_t _timespec_tomicros(struct timespec ts) {
|
||||
int64_t us;
|
||||
if (!__builtin_mul_overflow(x.tv_sec, 1000000ul, &us) &&
|
||||
!__builtin_add_overflow(us, x.tv_nsec / 1000, &us)) {
|
||||
// reduce precision from nanos to micros
|
||||
if (ts.tv_nsec <= 999999000) {
|
||||
ts.tv_nsec = (ts.tv_nsec + 999) / 1000;
|
||||
} else {
|
||||
ts.tv_nsec = 0;
|
||||
if (ts.tv_sec < INT64_MAX) {
|
||||
ts.tv_sec += 1;
|
||||
}
|
||||
}
|
||||
// convert to scalar result
|
||||
if (!__builtin_mul_overflow(ts.tv_sec, 1000000ul, &us) &&
|
||||
!__builtin_add_overflow(us, ts.tv_nsec, &us)) {
|
||||
return us;
|
||||
} else if (x.tv_sec < 0) {
|
||||
} else if (ts.tv_sec < 0) {
|
||||
return INT64_MIN;
|
||||
} else {
|
||||
return INT64_MAX;
|
||||
|
||||
@@ -20,14 +20,34 @@
|
||||
#include "libc/limits.h"
|
||||
|
||||
/**
|
||||
* Converts timespec interval to milliseconds.
|
||||
* Reduces `ts` from 1e-9 to 1e-3 granularity w/ ceil rounding.
|
||||
*
|
||||
* This function uses ceiling rounding. For example, if `ts` is one
|
||||
* nanosecond, then one millisecond will be returned. Ceil rounding
|
||||
* is needed by many interfaces, e.g. setitimer(), because the zero
|
||||
* timestamp has a special meaning.
|
||||
*
|
||||
* This function also detects overflow in which case `INT64_MAX` or
|
||||
* `INT64_MIN` may be returned. The `errno` variable isn't changed.
|
||||
*
|
||||
* @return 64-bit scalar milliseconds since epoch
|
||||
*/
|
||||
int64_t _timespec_tomillis(struct timespec x) {
|
||||
int64_t _timespec_tomillis(struct timespec ts) {
|
||||
int64_t ms;
|
||||
if (!__builtin_mul_overflow(x.tv_sec, 1000ul, &ms) &&
|
||||
!__builtin_add_overflow(ms, x.tv_nsec / 1000000, &ms)) {
|
||||
// reduce precision from nanos to millis
|
||||
if (ts.tv_nsec <= 999000000) {
|
||||
ts.tv_nsec = (ts.tv_nsec + 999999) / 1000000;
|
||||
} else {
|
||||
ts.tv_nsec = 0;
|
||||
if (ts.tv_sec < INT64_MAX) {
|
||||
ts.tv_sec += 1;
|
||||
}
|
||||
}
|
||||
// convert to scalar result
|
||||
if (!__builtin_mul_overflow(ts.tv_sec, 1000ul, &ms) &&
|
||||
!__builtin_add_overflow(ms, ts.tv_nsec, &ms)) {
|
||||
return ms;
|
||||
} else if (x.tv_sec < 0) {
|
||||
} else if (ts.tv_sec < 0) {
|
||||
return INT64_MIN;
|
||||
} else {
|
||||
return INT64_MAX;
|
||||
|
||||
@@ -20,7 +20,12 @@
|
||||
#include "libc/limits.h"
|
||||
|
||||
/**
|
||||
* Converts timespec interval to nanoseconds.
|
||||
* Converts timespec to scalar.
|
||||
*
|
||||
* This function will detect overflow in which case `INT64_MAX` or
|
||||
* `INT64_MIN` may be returned. The `errno` variable isn't changed.
|
||||
*
|
||||
* @return 64-bit integer holding nanoseconds since epoch
|
||||
*/
|
||||
int64_t _timespec_tonanos(struct timespec x) {
|
||||
int64_t ns;
|
||||
|
||||
@@ -18,6 +18,21 @@
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
|
||||
/**
|
||||
* Reduces `ts` from 1e-9 to 1e-6 granularity w/ ceil rounding.
|
||||
*
|
||||
* This function uses ceiling rounding. For example, if `ts` is one
|
||||
* nanosecond, then one microsecond will be returned. Ceil rounding
|
||||
* is needed by many interfaces, e.g. setitimer(), because the zero
|
||||
* timestamp has a special meaning.
|
||||
*
|
||||
* @return microseconds since epoch
|
||||
* @see _timespec_tomicros()
|
||||
*/
|
||||
struct timeval _timespec_totimeval(struct timespec ts) {
|
||||
return (struct timeval){ts.tv_sec, ts.tv_nsec / 1000};
|
||||
if (ts.tv_nsec < 1000000000 - 999) {
|
||||
return (struct timeval){ts.tv_sec, (ts.tv_nsec + 999) / 1000};
|
||||
} else {
|
||||
return (struct timeval){ts.tv_sec + 1, 0};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/*-*- 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. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
|
||||
/**
|
||||
* Compares microseconds timestamps.
|
||||
*/
|
||||
int _timeval_cmp(struct timeval a, struct timeval b) {
|
||||
int cmp;
|
||||
if (!(cmp = (a.tv_sec > b.tv_sec) - (a.tv_sec < b.tv_sec))) {
|
||||
cmp = (a.tv_usec > b.tv_usec) - (a.tv_usec < b.tv_usec);
|
||||
}
|
||||
return cmp;
|
||||
}
|
||||
@@ -16,5 +16,11 @@
|
||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
|
||||
bool __time_critical;
|
||||
/**
|
||||
* Checks if 𝑥 = 𝑦.
|
||||
*/
|
||||
bool _timeval_eq(struct timeval x, struct timeval y) {
|
||||
return x.tv_sec == y.tv_sec && x.tv_usec == y.tv_usec;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/*-*- 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. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
|
||||
/**
|
||||
* Returns true if timeval `x` is greater than `y`.
|
||||
*/
|
||||
bool _timeval_gt(struct timeval x, struct timeval y) {
|
||||
if (x.tv_sec > y.tv_sec) {
|
||||
return true;
|
||||
}
|
||||
if (x.tv_sec == y.tv_sec) {
|
||||
if (x.tv_usec > y.tv_usec) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*-*- 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. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
|
||||
/**
|
||||
* Checks if 𝑥 ≥ 𝑦.
|
||||
*/
|
||||
bool _timeval_gte(struct timeval x, struct timeval y) {
|
||||
if (x.tv_sec > y.tv_sec) return true;
|
||||
if (x.tv_sec < y.tv_sec) return false;
|
||||
return x.tv_usec >= y.tv_usec;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/*-*- 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. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
|
||||
/**
|
||||
* Subtracts two nanosecond timestamps.
|
||||
*/
|
||||
struct timeval _timeval_sub(struct timeval a, struct timeval b) {
|
||||
a.tv_sec -= b.tv_sec;
|
||||
if (a.tv_usec < b.tv_usec) {
|
||||
a.tv_usec += 1000000;
|
||||
a.tv_sec--;
|
||||
}
|
||||
a.tv_usec -= b.tv_usec;
|
||||
return a;
|
||||
}
|
||||
@@ -18,6 +18,9 @@
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
|
||||
/**
|
||||
* Coerces `tv` from 1e-6 to 1e-9 granularity.
|
||||
*/
|
||||
struct timespec _timeval_totimespec(struct timeval tv) {
|
||||
return (struct timespec){tv.tv_sec, tv.tv_usec * 1000};
|
||||
}
|
||||
+6
-1
@@ -22,9 +22,14 @@
|
||||
/**
|
||||
* Checks if effective user can access path in particular ways.
|
||||
*
|
||||
* This is equivalent to saying:
|
||||
*
|
||||
* faccessat(AT_FDCWD, path, mode, 0);
|
||||
*
|
||||
* @param path is a filename or directory
|
||||
* @param mode can be R_OK, W_OK, X_OK, F_OK
|
||||
* @return 0 if ok, or -1 and sets errno
|
||||
* @return 0 if ok, or -1 w/ errno
|
||||
* @see faccessat() for further documentation
|
||||
* @asyncsignalsafe
|
||||
*/
|
||||
int access(const char *path, int mode) {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#ifndef COSMOPOLITAN_LIBC_CALLS_ASAN_INTERNAL_H_
|
||||
#define COSMOPOLITAN_LIBC_CALLS_ASAN_INTERNAL_H_
|
||||
#include "libc/intrin/asmflag.h"
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
#include "libc/intrin/asmflag.h"
|
||||
#if !(__ASSEMBLER__ + __LINKER__ + 0)
|
||||
COSMOPOLITAN_C_START_
|
||||
|
||||
@@ -14,6 +15,10 @@ forceinline bool __asan_is_valid_timespec(const struct timespec *ts) {
|
||||
return zf;
|
||||
}
|
||||
|
||||
forceinline bool __asan_is_valid_timeval(const struct timeval *tv) {
|
||||
return __asan_is_valid_timespec((const struct timespec *)tv);
|
||||
}
|
||||
|
||||
COSMOPOLITAN_C_END_
|
||||
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
|
||||
#endif /* COSMOPOLITAN_LIBC_CALLS_ASAN_INTERNAL_H_ */
|
||||
@@ -84,6 +84,7 @@ int execv(const char *, char *const[]);
|
||||
int execve(const char *, char *const[], char *const[]);
|
||||
int execvp(const char *, char *const[]);
|
||||
int execvpe(const char *, char *const[], char *const[]);
|
||||
int fexecve(int, char *const[], char *const[]);
|
||||
int faccessat(int, const char *, int, uint32_t);
|
||||
int fadvise(int, uint64_t, uint64_t, int);
|
||||
int fchdir(int);
|
||||
|
||||
+3
-1
@@ -16,11 +16,12 @@
|
||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/syscall-nt.internal.h"
|
||||
#include "libc/calls/syscall-sysv.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/asan.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/runtime/runtime.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
/**
|
||||
@@ -34,6 +35,7 @@
|
||||
*/
|
||||
int chdir(const char *path) {
|
||||
int rc;
|
||||
GetProgramExecutableName(); // XXX: ugly workaround
|
||||
if (!path || (IsAsan() && !__asan_is_valid(path, 1))) {
|
||||
rc = efault();
|
||||
} else if (!IsWindows()) {
|
||||
|
||||
+28
-2
@@ -17,17 +17,43 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/syscall-sysv.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/asan.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
/**
|
||||
* Changes root directory.
|
||||
*
|
||||
* Please consider using unveil() instead of chroot(). If you use this
|
||||
* system call then consider using both chdir() and closefrom() before
|
||||
* calling this function. Otherwise there's a small risk that fchdir()
|
||||
* could be used to escape the chroot() environment. Cosmopolitan Libc
|
||||
* focuses on static binaries which make chroot() infinitely easier to
|
||||
* use since you don't need to construct an entire userspace each time
|
||||
* however unveil() is still better to use on modern Linux and OpenBSD
|
||||
* because it doesn't require root privileges.
|
||||
*
|
||||
* @param path shall become the new root directory
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @raise EACCES if we don't have permission to search a component of `path`
|
||||
* @raise ENOTDIR if a directory component in `path` exists as non-directory
|
||||
* @raise ENAMETOOLONG if symlink-resolved `path` length exceeds `PATH_MAX`
|
||||
* @raise ENAMETOOLONG if component in `path` exists longer than `NAME_MAX`
|
||||
* @raise EPERM if not root or pledge() is in play
|
||||
* @raise EIO if a low-level i/o error occurred
|
||||
* @raise EFAULT if `path` is bad memory
|
||||
* @raise ENOENT if `path` doesn't exist
|
||||
* @raise ENOSYS on Windows
|
||||
*/
|
||||
int chroot(const char *path) {
|
||||
int rc;
|
||||
rc = sys_chroot(path);
|
||||
if (!path || (IsAsan() && !__asan_is_valid(path, 1))) {
|
||||
rc = efault();
|
||||
} else {
|
||||
rc = sys_chroot(path);
|
||||
}
|
||||
STRACE("chroot(%s) → %d% m", path, rc);
|
||||
return rc;
|
||||
}
|
||||
@@ -17,10 +17,10 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/asan.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/struct/timespec.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/describeflags.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
#include "libc/time/time.h"
|
||||
@@ -49,6 +49,12 @@ static int sys_clock_getres_xnu(int clock, struct timespec *ts) {
|
||||
|
||||
/**
|
||||
* Returns granularity of clock.
|
||||
*
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @error EPERM if pledge() is in play without stdio promise
|
||||
* @error EINVAL if `clock` isn't supported on this system
|
||||
* @error EFAULT if `ts` points to bad memory
|
||||
* @threadsafe
|
||||
*/
|
||||
int clock_getres(int clock, struct timespec *ts) {
|
||||
int rc;
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
#include "libc/calls/asan.internal.h"
|
||||
#include "libc/calls/clock_gettime.internal.h"
|
||||
#include "libc/calls/state.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/struct/timespec.internal.h"
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
#include "libc/calls/syscall_support-sysv.internal.h"
|
||||
@@ -30,9 +29,11 @@
|
||||
#include "libc/intrin/asmflag.h"
|
||||
#include "libc/intrin/bits.h"
|
||||
#include "libc/intrin/describeflags.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/mem/alloca.h"
|
||||
#include "libc/nt/synchronization.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
#include "libc/thread/tls.h"
|
||||
|
||||
/**
|
||||
* Returns nanosecond time.
|
||||
@@ -48,12 +49,30 @@
|
||||
* __clock_gettime l: 35𝑐 11𝑛𝑠
|
||||
* sys_clock_gettime l: 220𝑐 71𝑛𝑠
|
||||
*
|
||||
* @param clock can be CLOCK_REALTIME, CLOCK_MONOTONIC, etc.
|
||||
* @param clock can be one of:
|
||||
* - `CLOCK_REALTIME`: universally supported
|
||||
* - `CLOCK_REALTIME_FAST`: ditto but faster on freebsd
|
||||
* - `CLOCK_MONOTONIC`: universally supported
|
||||
* - `CLOCK_MONOTONIC_FAST`: ditto but faster on freebsd
|
||||
* - `CLOCK_MONOTONIC_RAW`: nearly universally supported
|
||||
* - `CLOCK_PROCESS_CPUTIME_ID`: linux and bsd
|
||||
* - `CLOCK_THREAD_CPUTIME_ID`: linux and bsd
|
||||
* - `CLOCK_REALTIME_COARSE`: : linux and openbsd
|
||||
* - `CLOCK_MONOTONIC_COARSE`: linux
|
||||
* - `CLOCK_PROF`: linux and netbsd
|
||||
* - `CLOCK_BOOTTIME`: linux and openbsd
|
||||
* - `CLOCK_REALTIME_ALARM`: linux-only
|
||||
* - `CLOCK_BOOTTIME_ALARM`: linux-only
|
||||
* - `CLOCK_TAI`: linux-only
|
||||
* @param ts is where the result is stored
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @error EINVAL if clock isn't supported on this system
|
||||
* @error EPERM if pledge() is in play without stdio promise
|
||||
* @error EINVAL if `clock` isn't supported on this system
|
||||
* @error EFAULT if `ts` points to bad memory
|
||||
* @see strftime(), gettimeofday()
|
||||
* @asyncsignalsafe
|
||||
* @threadsafe
|
||||
* @vforksafe
|
||||
*/
|
||||
int clock_gettime(int clock, struct timespec *ts) {
|
||||
int rc;
|
||||
@@ -65,7 +84,7 @@ int clock_gettime(int clock, struct timespec *ts) {
|
||||
rc = __clock_gettime(clock, ts);
|
||||
}
|
||||
#if SYSDEBUG
|
||||
if (!__time_critical) {
|
||||
if (!(__get_tls()->tib_flags & TIB_FLAG_TIME_CRITICAL)) {
|
||||
STRACE("clock_gettime(%s, [%s]) → %d% m", DescribeClockName(clock),
|
||||
DescribeTimespec(rc, ts), rc);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/*-*- 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 2021 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. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/internal.h"
|
||||
#include "libc/calls/sig.internal.h"
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/calls/struct/timespec.internal.h"
|
||||
#include "libc/macros.internal.h"
|
||||
#include "libc/nt/synchronization.h"
|
||||
#include "libc/sysv/consts/timer.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
textwindows int sys_clock_nanosleep_nt(int clock, int flags,
|
||||
const struct timespec *req,
|
||||
struct timespec *rem) {
|
||||
struct timespec now, abs;
|
||||
if (flags & TIMER_ABSTIME) {
|
||||
abs = *req;
|
||||
for (;;) {
|
||||
if (sys_clock_gettime_nt(clock, &now)) return -1;
|
||||
if (_timespec_gte(now, abs)) return 0;
|
||||
if (_check_interrupts(false, g_fds.p)) return eintr();
|
||||
SleepEx(MIN(__SIG_POLLING_INTERVAL_MS,
|
||||
_timespec_tomillis(_timespec_sub(abs, now))),
|
||||
false);
|
||||
}
|
||||
} else {
|
||||
if (sys_clock_gettime_nt(clock, &now)) return -1;
|
||||
abs = _timespec_add(now, *req);
|
||||
for (;;) {
|
||||
sys_clock_gettime_nt(clock, &now);
|
||||
if (_timespec_gte(now, abs)) return 0;
|
||||
if (_check_interrupts(false, g_fds.p)) {
|
||||
if (rem) *rem = _timespec_sub(abs, now);
|
||||
return eintr();
|
||||
}
|
||||
SleepEx(MIN(__SIG_POLLING_INTERVAL_MS,
|
||||
_timespec_tomillis(_timespec_sub(abs, now))),
|
||||
false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*-*- 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. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/calls/struct/timespec.internal.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
int sys_clock_nanosleep_openbsd(int clock, int flags,
|
||||
const struct timespec *req,
|
||||
struct timespec *rem) {
|
||||
int res;
|
||||
struct timespec now, rel;
|
||||
if (clock == CLOCK_REALTIME) {
|
||||
if (!flags) {
|
||||
res = sys_nanosleep(req, rem);
|
||||
} else {
|
||||
sys_clock_gettime(clock, &now);
|
||||
if (_timespec_gt(*req, now)) {
|
||||
rel = _timespec_sub(*req, now);
|
||||
res = sys_nanosleep(&rel, 0);
|
||||
} else {
|
||||
res = 0;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
res = enotsup();
|
||||
}
|
||||
return res;
|
||||
}
|
||||
@@ -16,30 +16,34 @@
|
||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/calls/struct/timespec.internal.h"
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
#include "libc/calls/struct/timeval.internal.h"
|
||||
#include "libc/fmt/conv.h"
|
||||
#include "libc/sock/internal.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
#include "libc/sysv/consts/timer.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
// we don't want instrumentation because:
|
||||
// - nanosleep() depends on this and ftrace can take microsecs
|
||||
|
||||
/**
|
||||
* Converts `struct timespec` to `struct timeval`.
|
||||
*
|
||||
* This divides ts.tv_nsec by 1000 with upward rounding and overflow
|
||||
* handling. Your ts.tv_nsec must be on the interval `[0,1000000000)`
|
||||
* otherwise `{-1, -1}` is returned.
|
||||
*
|
||||
* @return converted timeval whose tv_usec will be -1 on error
|
||||
*/
|
||||
noinstrument struct timeval _timespec2timeval(struct timespec ts) {
|
||||
if (0 <= ts.tv_nsec && ts.tv_nsec < 1000000000) {
|
||||
if (0 <= ts.tv_nsec && ts.tv_nsec < 1000000000 - 999) {
|
||||
return (struct timeval){ts.tv_sec, (ts.tv_nsec + 999) / 1000};
|
||||
int sys_clock_nanosleep_xnu(int clock, int flags, const struct timespec *req,
|
||||
struct timespec *rem) {
|
||||
int res;
|
||||
struct timeval now, abs, rel;
|
||||
if (clock == CLOCK_REALTIME) {
|
||||
if (flags & TIMER_ABSTIME) {
|
||||
abs = _timespec_totimeval(*req);
|
||||
sys_gettimeofday_xnu(&now, 0, 0);
|
||||
if (_timeval_gt(abs, now)) {
|
||||
rel = _timeval_sub(abs, now);
|
||||
res = sys_select(0, 0, 0, 0, &rel);
|
||||
} else {
|
||||
res = 0;
|
||||
}
|
||||
} else {
|
||||
return (struct timeval){ts.tv_sec + 1, 0};
|
||||
res = sys_nanosleep_xnu(req, rem);
|
||||
}
|
||||
} else {
|
||||
return (struct timeval){-1, -1};
|
||||
res = enotsup();
|
||||
}
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
/*-*- 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. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/asan.internal.h"
|
||||
#include "libc/calls/state.internal.h"
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/calls/struct/timespec.internal.h"
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
#include "libc/calls/struct/timeval.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/errno.h"
|
||||
#include "libc/intrin/describeflags.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
#include "libc/sysv/consts/timer.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
#include "libc/thread/tls.h"
|
||||
|
||||
/**
|
||||
* Sleeps for particular amount of time.
|
||||
*
|
||||
* Here's how you could sleep for one second:
|
||||
*
|
||||
* clock_nanosleep(0, 0, &(struct timespec){1}, 0);
|
||||
*
|
||||
* Your sleep will be interrupted automatically if you do something like
|
||||
* press ctrl-c during the wait. That's an `EINTR` error and it lets you
|
||||
* immediately react to status changes. This is always the case, even if
|
||||
* you're using `SA_RESTART` since this is a `@norestart` system call.
|
||||
*
|
||||
* void OnCtrlC(int sig) {} // EINTR only happens after delivery
|
||||
* signal(SIGINT, OnCtrlC); // do delivery rather than kill proc
|
||||
* printf("save me from sleeping forever by pressing ctrl-c\n");
|
||||
* clock_nanosleep(0, 0, &(struct timespec){INT_MAX}, 0);
|
||||
* printf("you're my hero\n");
|
||||
*
|
||||
* If you want to perform an uninterruptible sleep without having to use
|
||||
* sigprocmask() to block all signals then this function provides a good
|
||||
* solution to that problem. For example:
|
||||
*
|
||||
* struct timespec rel, now, abs;
|
||||
* clock_gettime(CLOCK_REALTIME, &now);
|
||||
* rel = _timespec_frommillis(100);
|
||||
* abs = _timespec_add(now, rel);
|
||||
* while (clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &abs, 0));
|
||||
*
|
||||
* will accurately spin on `EINTR` errors. That way you're not impeding
|
||||
* signal delivery and you're not losing precision on your wait timeout.
|
||||
* This function has first-class support on Linux, FreeBSD, and NetBSD;
|
||||
* on OpenBSD it's good; on XNU it's bad; and on Windows it's ugly.
|
||||
*
|
||||
* @param clock should be `CLOCK_REALTIME` and you may consult the docs
|
||||
* of your preferred platforms to see what other clocks might work
|
||||
* @param flags can be 0 for relative and `TIMER_ABSTIME` for absolute
|
||||
* @param req can be a relative or absolute time, depending on `flags`
|
||||
* @param rem shall be updated with the remainder of unslept time when
|
||||
* (1) it's non-null; (2) `flags` is 0; and (3) -1 w/ `EINTR` is
|
||||
* returned; if this function returns 0 then `rem` is undefined;
|
||||
* if flags is `TIMER_ABSTIME` then `rem` is ignored
|
||||
* @return 0 on success, or errno on error
|
||||
* @raise EINTR when a signal got delivered while we were waiting
|
||||
* @raise ENOTSUP if `clock` is known but we can't use it here
|
||||
* @raise EINVAL if `clock` is unknown to current platform
|
||||
* @raise EINVAL if `flags` has an unrecognized value
|
||||
* @raise EINVAL if `req->tv_nsec ∉ [0,1000000000)`
|
||||
* @raise EFAULT if bad memory was passed
|
||||
* @raise ENOSYS on bare metal
|
||||
* @returnserrno
|
||||
* @norestart
|
||||
*/
|
||||
errno_t clock_nanosleep(int clock, int flags, const struct timespec *req,
|
||||
struct timespec *rem) {
|
||||
int rc, e = errno;
|
||||
|
||||
if (!req || (IsAsan() && (!__asan_is_valid_timespec(req) ||
|
||||
(rem && !__asan_is_valid_timespec(rem))))) {
|
||||
rc = efault();
|
||||
} else if (clock == 127 || //
|
||||
(flags & ~TIMER_ABSTIME) || //
|
||||
req->tv_sec < 0 || //
|
||||
!(0 <= req->tv_nsec && req->tv_nsec <= 999999999)) {
|
||||
rc = einval();
|
||||
} else if (IsLinux() || IsFreebsd() || IsNetbsd()) {
|
||||
rc = sys_clock_nanosleep(clock, flags, req, rem);
|
||||
} else if (IsXnu()) {
|
||||
rc = sys_clock_nanosleep_xnu(clock, flags, req, rem);
|
||||
} else if (IsOpenbsd()) {
|
||||
rc = sys_clock_nanosleep_openbsd(clock, flags, req, rem);
|
||||
} else if (IsMetal()) {
|
||||
rc = enosys();
|
||||
} else {
|
||||
rc = sys_clock_nanosleep_nt(clock, flags, req, rem);
|
||||
}
|
||||
|
||||
if (rc == -1) {
|
||||
rc = errno;
|
||||
errno = e;
|
||||
}
|
||||
|
||||
#if SYSDEBUG
|
||||
if (!(__get_tls()->tib_flags & TIB_FLAG_TIME_CRITICAL)) {
|
||||
STRACE("clock_nanosleep(%s, %s, %s, [%s]) → %s", DescribeClockName(clock),
|
||||
DescribeSleepFlags(flags), DescribeTimespec(0, req),
|
||||
DescribeTimespec(rc, rem), DescribeErrnoResult(rc));
|
||||
}
|
||||
#endif
|
||||
|
||||
return rc;
|
||||
}
|
||||
+17
-9
@@ -32,17 +32,25 @@
|
||||
/**
|
||||
* Closes file descriptor.
|
||||
*
|
||||
* This function may be used for file descriptors returned by functions
|
||||
* like open, socket, accept, epoll_create, and landlock_create_ruleset.
|
||||
* This function releases resources returned by functions such as:
|
||||
*
|
||||
* This function should never be called twice for the same file
|
||||
* descriptor, regardless of whether or not an error happened. However
|
||||
* that doesn't mean the error should be ignored.
|
||||
* - openat()
|
||||
* - socket()
|
||||
* - accept()
|
||||
* - epoll_create()
|
||||
* - landlock_create_ruleset()
|
||||
*
|
||||
* This function should never be reattempted if an error is returned;
|
||||
* however, that doesn't mean the error should be ignored. This goes
|
||||
* against the conventional wisdom of looping on `EINTR`.
|
||||
*
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @error EINTR means a signal was received while closing in which case
|
||||
* close() does not need to be called again, since the fd will close
|
||||
* in the background
|
||||
* @raise EINTR if signal was delivered; do *not* retry
|
||||
* @raise EBADF if `fd` is negative or not open; however, an exception
|
||||
* is made by Cosmopolitan Libc for `close(-1)` which returns zero
|
||||
* and does nothing, in order to assist with code that may wish to
|
||||
* close the same resource multiple times without dirtying `errno`
|
||||
* @raise EIO if a low-level i/o error occurred
|
||||
* @asyncsignalsafe
|
||||
* @vforksafe
|
||||
*/
|
||||
@@ -51,7 +59,7 @@ int close(int fd) {
|
||||
if (fd == -1) {
|
||||
rc = 0;
|
||||
} else if (fd < 0) {
|
||||
rc = einval();
|
||||
rc = ebadf();
|
||||
} else {
|
||||
// for performance reasons we want to avoid holding __fds_lock()
|
||||
// while sys_close() is happening. this leaves the kernel / libc
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/internal.h"
|
||||
#include "libc/calls/struct/sigset.h"
|
||||
#include "libc/calls/struct/sigset.internal.h"
|
||||
#include "libc/calls/syscall-sysv.internal.h"
|
||||
@@ -79,6 +80,7 @@ static void copy_file_range_init(void) {
|
||||
* @raise EXDEV if source and destination are on different filesystems
|
||||
* @raise EBADF if `infd` or `outfd` aren't open files or append-only
|
||||
* @raise EPERM if `fdout` refers to an immutable file on Linux
|
||||
* @raise ENOTSUP if `infd` or `outfd` is a zip file descriptor
|
||||
* @raise EINVAL if ranges overlap or `flags` is non-zero
|
||||
* @raise EFBIG if `setrlimit(RLIMIT_FSIZE)` is exceeded
|
||||
* @raise EFAULT if one of the pointers memory is bad
|
||||
@@ -104,6 +106,8 @@ ssize_t copy_file_range(int infd, int64_t *opt_in_out_inoffset, int outfd,
|
||||
(opt_in_out_outoffset &&
|
||||
!__asan_is_valid(opt_in_out_outoffset, 8)))) {
|
||||
rc = efault();
|
||||
} else if (__isfdkind(infd, kFdZip) || __isfdkind(outfd, kFdZip)) {
|
||||
rc = enotsup();
|
||||
} else {
|
||||
rc = sys_copy_file_range(infd, opt_in_out_inoffset, outfd,
|
||||
opt_in_out_outoffset, uptobytes, flags);
|
||||
|
||||
+11
-10
@@ -21,20 +21,21 @@
|
||||
#include "libc/sysv/consts/o.h"
|
||||
|
||||
/**
|
||||
* Creates new file, returning open()'d file descriptor.
|
||||
* Creates file.
|
||||
*
|
||||
* This function is shorthand for:
|
||||
* This is equivalent to saying:
|
||||
*
|
||||
* open(file, O_CREAT | O_WRONLY | O_TRUNC, mode)
|
||||
* int fd = openat(AT_FDCWD, file, O_CREAT | O_WRONLY | O_TRUNC, mode);
|
||||
*
|
||||
* @param file is a UTF-8 string, which is truncated if it exists
|
||||
* @param mode is an octal user/group/other permission, e.g. 0755
|
||||
* @return a number registered with the system to track the open file,
|
||||
* which must be stored using a 64-bit type in order to support both
|
||||
* System V and Windows, and must be closed later on using close()
|
||||
* @see open(), touch()
|
||||
* @param file specifies filesystem path to create
|
||||
* @param mode is octal bits, e.g. 0644 usually
|
||||
* @return file descriptor, or -1 w/ errno
|
||||
* @see openat() for further documentation
|
||||
* @asyncsignalsafe
|
||||
* @restartable
|
||||
* @threadsafe
|
||||
* @vforksafe
|
||||
*/
|
||||
dontdiscard int creat(const char *file, uint32_t mode) {
|
||||
int creat(const char *file, uint32_t mode) {
|
||||
return openat(AT_FDCWD, file, O_CREAT | O_WRONLY | O_TRUNC, mode);
|
||||
}
|
||||
+4
-3
@@ -32,15 +32,16 @@
|
||||
*
|
||||
* @param fd remains open afterwards
|
||||
* @return some arbitrary new number for fd
|
||||
* @raise EOPNOTSUPP if zipos file
|
||||
* @raise EBADF if fd isn't open
|
||||
* @raise EPERM if pledge() is in play without stdio
|
||||
* @raise ENOTSUP if `fd` is a zip file descriptor
|
||||
* @raise EBADF if `fd` is negative or not open
|
||||
* @asyncsignalsafe
|
||||
* @vforksafe
|
||||
*/
|
||||
int dup(int fd) {
|
||||
int rc;
|
||||
if (__isfdkind(fd, kFdZip)) {
|
||||
rc = eopnotsupp();
|
||||
rc = enotsup();
|
||||
} else if (!IsWindows()) {
|
||||
rc = sys_dup(fd);
|
||||
} else {
|
||||
|
||||
+7
-4
@@ -18,10 +18,10 @@
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/syscall-nt.internal.h"
|
||||
#include "libc/calls/syscall-sysv.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
/**
|
||||
@@ -38,16 +38,19 @@
|
||||
* @param newfd if already assigned, is silently closed beforehand;
|
||||
* unless it's equal to oldfd, in which case dup2() is a no-op
|
||||
* @return new file descriptor, or -1 w/ errno
|
||||
* @raise EBADF is oldfd isn't open
|
||||
* @raise EBADF is newfd negative or too big
|
||||
* @raise EPERM if pledge() is in play without stdio
|
||||
* @raise EMFILE if `RLIMIT_NOFILE` has been reached
|
||||
* @raise ENOTSUP if `oldfd` is on zip file system
|
||||
* @raise EINTR if a signal handler was called
|
||||
* @raise EBADF is `newfd` negative or too big
|
||||
* @raise EBADF is `oldfd` isn't open
|
||||
* @asyncsignalsafe
|
||||
* @vforksafe
|
||||
*/
|
||||
int dup2(int oldfd, int newfd) {
|
||||
int rc;
|
||||
if (__isfdkind(oldfd, kFdZip)) {
|
||||
rc = eopnotsupp();
|
||||
rc = enotsup();
|
||||
} else if (!IsWindows()) {
|
||||
rc = sys_dup2(oldfd, newfd);
|
||||
} else if (newfd < 0) {
|
||||
|
||||
+7
-5
@@ -38,11 +38,13 @@
|
||||
* @param flags may have O_CLOEXEC which is needed to preserve the
|
||||
* close-on-execve() state after file descriptor duplication
|
||||
* @return newfd on success, or -1 w/ errno
|
||||
* @raise EINVAL if flags has unsupported bits
|
||||
* @raise EINVAL if newfd equals oldfd
|
||||
* @raise EBADF is oldfd isn't open
|
||||
* @raise EBADF is newfd negative or too big
|
||||
* @raise ENOTSUP if `oldfd` is a zip file descriptor
|
||||
* @raise EPERM if pledge() is in play without stdio
|
||||
* @raise EINVAL if `flags` has unsupported bits
|
||||
* @raise EINTR if a signal handler was called
|
||||
* @raise EBADF is `newfd` negative or too big
|
||||
* @raise EINVAL if `newfd` equals oldfd
|
||||
* @raise EBADF is `oldfd` isn't open
|
||||
* @see dup(), dup2()
|
||||
*/
|
||||
int dup3(int oldfd, int newfd, int flags) {
|
||||
@@ -52,7 +54,7 @@ int dup3(int oldfd, int newfd, int flags) {
|
||||
} else if (oldfd < 0 || newfd < 0) {
|
||||
rc = ebadf();
|
||||
} else if (__isfdkind(oldfd, kFdZip)) {
|
||||
rc = eopnotsupp();
|
||||
rc = enotsup();
|
||||
} else if (!IsWindows()) {
|
||||
rc = sys_dup3(oldfd, newfd, flags);
|
||||
} else {
|
||||
|
||||
@@ -35,6 +35,10 @@
|
||||
/**
|
||||
* Replaces current process with program.
|
||||
*
|
||||
* On Windows, `argv` and `envp` can't contain binary strings. They need
|
||||
* to be valid UTF-8 in order to round-trip the WIN32 API, without being
|
||||
* corrupted.
|
||||
*
|
||||
* @param program will not be PATH searched, see commandv()
|
||||
* @param argv[0] is the name of the program to run
|
||||
* @param argv[1,n-2] optionally specify program arguments
|
||||
|
||||
+22
-12
@@ -17,6 +17,7 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/internal.h"
|
||||
#include "libc/calls/syscall-nt.internal.h"
|
||||
#include "libc/calls/syscall-sysv.internal.h"
|
||||
#include "libc/dce.h"
|
||||
@@ -35,33 +36,42 @@
|
||||
* @param dirfd is normally AT_FDCWD but if it's an open directory and
|
||||
* file is a relative path, then file is opened relative to dirfd
|
||||
* @param path is a filename or directory
|
||||
* @param mode can be R_OK, W_OK, X_OK, F_OK
|
||||
* @param flags can have AT_EACCESS, AT_SYMLINK_NOFOLLOW
|
||||
* @note on Linux flags is only supported on Linux 5.8+
|
||||
* @param amode can be `R_OK`, `W_OK`, `X_OK`, or `F_OK`
|
||||
* @param flags can have `AT_EACCESS` and/or `AT_SYMLINK_NOFOLLOW`
|
||||
* @return 0 if ok, or -1 and sets errno
|
||||
* @raise EINVAL if `mode` has bad value
|
||||
* @raise EPERM if pledge() is in play without rpath promise
|
||||
* @raise EACCES if access for requested `mode` would be denied
|
||||
* @raise ENOTDIR if a directory component in `path` exists as non-directory
|
||||
* @raise ENOENT if component of `path` doesn't exist or `path` is empty
|
||||
* @raise ENOTSUP if `path` is a zip file and `dirfd` isn't `AT_FDCWD`
|
||||
* @note on Linux `flags` is only supported on Linux 5.8+
|
||||
* @asyncsignalsafe
|
||||
*/
|
||||
int faccessat(int dirfd, const char *path, int mode, uint32_t flags) {
|
||||
int faccessat(int dirfd, const char *path, int amode, uint32_t flags) {
|
||||
int e, rc;
|
||||
if (IsAsan() && !__asan_is_valid(path, 1)) {
|
||||
struct ZiposUri zipname;
|
||||
if (!path || (IsAsan() && !__asan_is_valid(path, 1))) {
|
||||
rc = efault();
|
||||
} else if (_weaken(__zipos_notat) &&
|
||||
_weaken(__zipos_notat)(dirfd, path) == -1) {
|
||||
rc = -1; /* TODO(jart): implement me */
|
||||
} else if (__isfdkind(dirfd, kFdZip)) {
|
||||
rc = enotsup();
|
||||
} else if (_weaken(__zipos_open) &&
|
||||
_weaken(__zipos_parseuri)(path, &zipname) != -1) {
|
||||
rc = _weaken(__zipos_access)(&zipname, amode);
|
||||
} else if (!IsWindows()) {
|
||||
e = errno;
|
||||
if (!flags) goto NoFlags;
|
||||
if ((rc = sys_faccessat2(dirfd, path, mode, flags)) == -1) {
|
||||
if ((rc = sys_faccessat2(dirfd, path, amode, flags)) == -1) {
|
||||
if (errno == ENOSYS) {
|
||||
errno = e;
|
||||
NoFlags:
|
||||
rc = sys_faccessat(dirfd, path, mode, flags);
|
||||
rc = sys_faccessat(dirfd, path, amode, flags);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
rc = sys_faccessat_nt(dirfd, path, mode, flags);
|
||||
rc = sys_faccessat_nt(dirfd, path, amode, flags);
|
||||
}
|
||||
STRACE("faccessat(%s, %#s, %#o, %#x) → %d% m", DescribeDirfd(dirfd), path,
|
||||
mode, flags, rc);
|
||||
amode, flags, rc);
|
||||
return rc;
|
||||
}
|
||||
@@ -37,6 +37,7 @@
|
||||
* @param path must exist
|
||||
* @param mode contains octal flags (base 8)
|
||||
* @param flags can have `AT_SYMLINK_NOFOLLOW`
|
||||
* @raise ENOTSUP if `dirfd` or `path` use zip file system
|
||||
* @errors ENOENT, ENOTDIR, ENOSYS
|
||||
* @asyncsignalsafe
|
||||
* @see fchmod()
|
||||
@@ -47,7 +48,7 @@ int fchmodat(int dirfd, const char *path, uint32_t mode, int flags) {
|
||||
rc = efault();
|
||||
} else if (_weaken(__zipos_notat) &&
|
||||
(rc = __zipos_notat(dirfd, path)) == -1) {
|
||||
rc = eopnotsupp();
|
||||
rc = enotsup();
|
||||
} else if (!IsWindows()) {
|
||||
rc = sys_fchmodat(dirfd, path, mode, flags);
|
||||
} else {
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
* @param gid is group id, or -1 to not change
|
||||
* @param flags can have AT_SYMLINK_NOFOLLOW, etc.
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @raise ENOTSUP if `dirfd` or `path` use zip file system
|
||||
* @see chown(), lchown() for shorthand notation
|
||||
* @see /etc/passwd for user ids
|
||||
* @see /etc/group for group ids
|
||||
@@ -46,7 +47,7 @@ int fchownat(int dirfd, const char *path, uint32_t uid, uint32_t gid,
|
||||
rc = efault();
|
||||
} else if (_weaken(__zipos_notat) &&
|
||||
(rc = __zipos_notat(dirfd, path)) == -1) {
|
||||
STRACE("zipos fchownat not supported yet");
|
||||
rc = enotsup();
|
||||
} else {
|
||||
rc = sys_fchownat(dirfd, path, uid, gid, flags);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
/*-*- 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. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/syscall-sysv.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/fmt/itoa.h"
|
||||
#include "libc/intrin/asan.internal.h"
|
||||
#include "libc/intrin/kprintf.h"
|
||||
#include "libc/intrin/likely.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/str/str.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
int sys_fexecve(int, char *const[], char *const[]);
|
||||
|
||||
/**
|
||||
* Executes binary executable at file descriptor.
|
||||
*
|
||||
* This is only supported on Linux and FreeBSD. APE binaries currently
|
||||
* aren't supported.
|
||||
*
|
||||
* @param fd is opened executable and current file position is ignored
|
||||
* @return doesn't return on success, otherwise -1 w/ errno
|
||||
* @raise ENOEXEC if file at `fd` isn't an assimilated ELF executable
|
||||
* @raise ENOSYS on Windows, XNU, OpenBSD, NetBSD, and Metal
|
||||
*/
|
||||
int fexecve(int fd, char *const argv[], char *const envp[]) {
|
||||
int rc;
|
||||
size_t i;
|
||||
if (!argv || !envp ||
|
||||
(IsAsan() &&
|
||||
(!__asan_is_valid_strlist(argv) || !__asan_is_valid_strlist(envp)))) {
|
||||
rc = efault();
|
||||
} else {
|
||||
#ifdef SYSDEBUG
|
||||
if (UNLIKELY(__strace > 0)) {
|
||||
kprintf(STRACE_PROLOGUE "fexecve(%d, {", fd);
|
||||
for (i = 0; argv[i]; ++i) {
|
||||
if (i) kprintf(", ");
|
||||
kprintf("%#s", argv[i]);
|
||||
}
|
||||
kprintf("}, {");
|
||||
for (i = 0; envp[i]; ++i) {
|
||||
if (i) kprintf(", ");
|
||||
kprintf("%#s", envp[i]);
|
||||
}
|
||||
kprintf("})\n");
|
||||
}
|
||||
#endif
|
||||
if (IsLinux()) {
|
||||
char path[14 + 12];
|
||||
FormatInt32(stpcpy(path, "/proc/self/fd/"), fd);
|
||||
rc = __sys_execve(path, argv, envp);
|
||||
} else if (IsFreebsd()) {
|
||||
rc = sys_fexecve(fd, argv, envp);
|
||||
} else {
|
||||
rc = enosys();
|
||||
}
|
||||
}
|
||||
STRACE("fexecve(%d) failed %d% m", fd, rc);
|
||||
return rc;
|
||||
}
|
||||
@@ -16,9 +16,12 @@
|
||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/assert.h"
|
||||
#include "libc/calls/syscall_support-nt.internal.h"
|
||||
#include "libc/nt/enum/filemovemethod.h"
|
||||
#include "libc/nt/errors.h"
|
||||
#include "libc/nt/files.h"
|
||||
#include "libc/nt/runtime.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
textwindows int sys_ftruncate_nt(int64_t handle, uint64_t length) {
|
||||
@@ -28,7 +31,13 @@ textwindows int sys_ftruncate_nt(int64_t handle, uint64_t length) {
|
||||
if ((ok = SetFilePointerEx(handle, 0, &tell, kNtFileCurrent))) {
|
||||
ok = SetFilePointerEx(handle, length, NULL, kNtFileBegin) &&
|
||||
SetEndOfFile(handle);
|
||||
SetFilePointerEx(handle, tell, NULL, kNtFileBegin);
|
||||
_npassert(SetFilePointerEx(handle, tell, NULL, kNtFileBegin));
|
||||
}
|
||||
if (ok) {
|
||||
return 0;
|
||||
} else if (GetLastError() == kNtErrorAccessDenied) {
|
||||
return einval(); // ftruncate() doesn't raise EACCES
|
||||
} else {
|
||||
return __winerr();
|
||||
}
|
||||
return ok ? 0 : __winerr();
|
||||
}
|
||||
+42
-8
@@ -18,31 +18,65 @@
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/syscall-nt.internal.h"
|
||||
#include "libc/calls/syscall-sysv.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/errno.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
/**
|
||||
* Changes size of file.
|
||||
* Changes size of open file.
|
||||
*
|
||||
* If the file size is increased, the extended area shall appear as if
|
||||
* it were zero-filled. If your file size is decreased, the extra data
|
||||
* shall be lost.
|
||||
*
|
||||
* This function never changes the file position. This is true even if
|
||||
* ftruncate() causes the position to become beyond the end of file in
|
||||
* which case, the rules described in the lseek() documentation apply.
|
||||
*
|
||||
* Some operating systems implement an optimization, where `length` is
|
||||
* treated as a logical size and the requested physical space won't be
|
||||
* allocated until non-zero values get written into it. Our tests show
|
||||
* this happens on Linux (usually with 4096 byte granularity), FreeBSD
|
||||
* (which favors 512-byte granularity), and MacOS (prefers 4096 bytes)
|
||||
* however Windows, OpenBSD, and NetBSD always reserve physical space.
|
||||
* This may be inspected using fstat() and consulting stat::st_blocks.
|
||||
*
|
||||
* @param fd must be open for writing
|
||||
* @param length may be greater than current current file size, in which
|
||||
* case System V guarantees it'll be zero'd but Windows NT doesn't;
|
||||
* since the prior extends logically and the latter physically
|
||||
* @param length may be greater than current current file size
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @raise EINVAL if `length` is negative
|
||||
* @raise EINTR if signal was delivered instead
|
||||
* @raise EIO if a low-level i/o error happened
|
||||
* @raise EFBIG or EINVAL if `length` is too huge
|
||||
* @raise ENOTSUP if `fd` is a zip file descriptor
|
||||
* @raise EBADF if `fd` isn't an open file descriptor
|
||||
* @raise EINVAL if `fd` is a non-file, e.g. pipe, socket
|
||||
* @raise EINVAL if `fd` wasn't opened in a writeable mode
|
||||
* @raise ENOSYS on bare metal
|
||||
* @see truncate()
|
||||
* @asyncsignalsafe
|
||||
* @threadsafe
|
||||
*/
|
||||
int ftruncate(int fd, int64_t length) {
|
||||
int rc;
|
||||
if (fd < 0) {
|
||||
rc = einval();
|
||||
rc = ebadf();
|
||||
} else if (__isfdkind(fd, kFdZip)) {
|
||||
rc = enotsup();
|
||||
} else if (IsMetal()) {
|
||||
rc = enosys();
|
||||
} else if (!IsWindows()) {
|
||||
rc = sys_ftruncate(fd, length, length);
|
||||
} else {
|
||||
if (fd >= g_fds.n) rc = ebadf();
|
||||
if (IsNetbsd() && rc == -1 && errno == ENOSPC) {
|
||||
errno = EFBIG; // POSIX doesn't specify ENOSPC for ftruncate()
|
||||
}
|
||||
} else if (__isfdopen(fd)) {
|
||||
rc = sys_ftruncate_nt(g_fds.p[fd].handle, length);
|
||||
} else {
|
||||
rc = ebadf();
|
||||
}
|
||||
STRACE("ftruncate(%d, %'ld) → %d% m", fd, length, rc);
|
||||
return rc;
|
||||
|
||||
+25
-5
@@ -16,16 +16,36 @@
|
||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/internal.h"
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/calls/struct/timespec.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
/**
|
||||
* Sets atime/mtime on file descriptor.
|
||||
* Changes access/modified time on open file, the modern way.
|
||||
*
|
||||
* This function is the same as `utimensat(fd, 0, ts, 0)`.
|
||||
* XNU only has microsecond (1e-6) accuracy. Windows only has
|
||||
* hectonanosecond (1e-7) accuracy. RHEL5 (Linux c. 2007) doesn't
|
||||
* support this system call.
|
||||
*
|
||||
* @param ts is atime/mtime, or null for current time
|
||||
* @raise ENOSYS on RHEL5
|
||||
* @param fd is file descriptor of file whose timestamps will change
|
||||
* @param ts is {access, modified} timestamps, or null for current time
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @raise ENOTSUP if `fd` is on the zip filesystem
|
||||
* @raise EINVAL if `flags` had an unrecognized value
|
||||
* @raise EPERM if pledge() is in play without `fattr` promise
|
||||
* @raise EINVAL if `ts` specifies a nanosecond value that's out of range
|
||||
* @raise EBADF if `fd` isn't an open file descriptor
|
||||
* @raise EFAULT if `ts` memory was invalid
|
||||
* @raise ENOSYS on RHEL5 or bare metal
|
||||
* @asyncsignalsafe
|
||||
* @threadsafe
|
||||
*/
|
||||
int futimens(int fd, const struct timespec ts[2]) {
|
||||
return utimensat(fd, 0, ts, 0);
|
||||
int rc;
|
||||
rc = __utimens(fd, 0, ts, 0);
|
||||
STRACE("futimens(%d, {%s, %s}) → %d% m", fd, DescribeTimespec(0, ts),
|
||||
DescribeTimespec(0, ts ? ts + 1 : 0), rc);
|
||||
return rc;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*-*- 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 2020 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. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/asan.internal.h"
|
||||
#include "libc/calls/struct/itimerval.internal.h"
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/calls/struct/timespec.internal.h"
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
/**
|
||||
* Sets atime/mtime on file descriptor.
|
||||
*
|
||||
* @param ts is atime/mtime, or null for current time
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @raise ENOTSUP if `fd` is on zip filesystem
|
||||
* @raise EBADF if `fd` isn't an open file descriptor
|
||||
* @raise EPERM if pledge() is in play without `fattr` promise
|
||||
* @raise EINVAL if `tv` specifies a microsecond value that's out of range
|
||||
* @raise ENOSYS on RHEL5 or bare metal
|
||||
* @see futimens() for modern version
|
||||
* @asyncsignalsafe
|
||||
* @threadsafe
|
||||
*/
|
||||
int futimes(int fd, const struct timeval tv[2]) {
|
||||
int rc;
|
||||
struct timespec ts[2];
|
||||
|
||||
if (tv) {
|
||||
ts[0].tv_sec = tv[0].tv_sec;
|
||||
ts[0].tv_nsec = tv[0].tv_usec * 1000;
|
||||
ts[1].tv_sec = tv[1].tv_sec;
|
||||
ts[1].tv_nsec = tv[1].tv_usec * 1000;
|
||||
rc = __utimens(fd, 0, ts, 0);
|
||||
} else {
|
||||
rc = __utimens(fd, 0, 0, 0);
|
||||
}
|
||||
|
||||
STRACE("futimes(%d, {%s, %s}) → %d% m", fd, DescribeTimeval(0, tv),
|
||||
DescribeTimeval(0, tv ? tv + 1 : 0), rc);
|
||||
|
||||
return rc;
|
||||
}
|
||||
@@ -19,7 +19,5 @@
|
||||
#include "libc/calls/state.internal.h"
|
||||
#include "libc/thread/thread.h"
|
||||
|
||||
// TODO(jart): These should be _Thread_local but doing that currently
|
||||
// causes a regression with runitd.com on Windows.
|
||||
unsigned __sighandrvas[NSIG];
|
||||
unsigned __sighandflags[NSIG];
|
||||
@@ -0,0 +1,29 @@
|
||||
/*-*- 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. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/internal.h"
|
||||
|
||||
/**
|
||||
* Gets file descriptor table size.
|
||||
*
|
||||
* @return current limit on the number of open files per process
|
||||
*/
|
||||
int getdtablesize(void) {
|
||||
return g_fds.n;
|
||||
}
|
||||
+12
-3
@@ -16,18 +16,26 @@
|
||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/assert.h"
|
||||
#include "libc/calls/syscall-nt.internal.h"
|
||||
#include "libc/calls/syscall-sysv.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
|
||||
/**
|
||||
* Returns parent process id.
|
||||
*
|
||||
* @return parent process id (always successful)
|
||||
* @note slow on Windows; needs to iterate process tree
|
||||
* @asyncsignalsafe
|
||||
* @threadsafe
|
||||
* @vforksafe
|
||||
*/
|
||||
int getppid(void) {
|
||||
int rc;
|
||||
if (!IsWindows()) {
|
||||
if (IsMetal()) {
|
||||
rc = 1;
|
||||
} else if (!IsWindows()) {
|
||||
if (!IsNetbsd()) {
|
||||
rc = sys_getppid();
|
||||
} else {
|
||||
@@ -36,6 +44,7 @@ int getppid(void) {
|
||||
} else {
|
||||
rc = sys_getppid_nt();
|
||||
}
|
||||
STRACE("getppid() → %d% m", rc);
|
||||
_npassert(rc >= 0);
|
||||
STRACE("%s() → %d", "getppid", rc);
|
||||
return rc;
|
||||
}
|
||||
@@ -24,6 +24,6 @@
|
||||
textwindows int sys_getsetpriority_nt(int which, unsigned who, int value,
|
||||
int (*impl)(int)) {
|
||||
if (which != PRIO_PROCESS && which != PRIO_PGRP) return einval();
|
||||
if (who && who != getpid() && who != gettid()) return eopnotsupp();
|
||||
if (who && who != getpid() && who != gettid()) return esrch();
|
||||
return impl(value);
|
||||
}
|
||||
@@ -18,7 +18,6 @@
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/assert.h"
|
||||
#include "libc/calls/state.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/struct/itimerval.internal.h"
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
#include "libc/calls/struct/timeval.internal.h"
|
||||
@@ -26,7 +25,9 @@
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/asan.internal.h"
|
||||
#include "libc/intrin/describeflags.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
#include "libc/thread/tls.h"
|
||||
#include "libc/time/struct/timezone.h"
|
||||
|
||||
typedef axdx_t gettimeofday_f(struct timeval *, struct timezone *, void *);
|
||||
@@ -62,7 +63,7 @@ int gettimeofday(struct timeval *tv, struct timezone *tz) {
|
||||
rc = __gettimeofday(tv, tz, 0).ax;
|
||||
}
|
||||
#if SYSDEBUG
|
||||
if (!__time_critical) {
|
||||
if (!(__get_tls()->tib_flags & TIB_FLAG_TIME_CRITICAL)) {
|
||||
STRACE("gettimeofday([%s], %p) → %d% m", DescribeTimeval(rc, tv), tz, rc);
|
||||
}
|
||||
#endif
|
||||
|
||||
+19
-8
@@ -16,10 +16,12 @@
|
||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/assert.h"
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/syscall-sysv.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/limits.h"
|
||||
#include "libc/macros.internal.h"
|
||||
#include "libc/nt/accounting.h"
|
||||
#include "libc/runtime/runtime.h"
|
||||
@@ -38,7 +40,7 @@ static textwindows dontinline uint32_t GetUserNameHash(void) {
|
||||
char16_t buf[257];
|
||||
uint32_t size = ARRAYLEN(buf);
|
||||
GetUserName(&buf, &size);
|
||||
return KnuthMultiplicativeHash32(buf, size >> 1);
|
||||
return KnuthMultiplicativeHash32(buf, size >> 1) & INT_MAX;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -47,18 +49,22 @@ static textwindows dontinline uint32_t GetUserNameHash(void) {
|
||||
* This never fails. On Windows, which doesn't really have this concept,
|
||||
* we return a deterministic value that's likely to work.
|
||||
*
|
||||
* @return user id (always successful)
|
||||
* @asyncsignalsafe
|
||||
* @threadsafe
|
||||
* @vforksafe
|
||||
*/
|
||||
uint32_t getuid(void) {
|
||||
uint32_t rc;
|
||||
if (!IsWindows()) {
|
||||
int rc;
|
||||
if (IsMetal()) {
|
||||
rc = 0;
|
||||
} else if (!IsWindows()) {
|
||||
rc = sys_getuid();
|
||||
} else {
|
||||
rc = GetUserNameHash();
|
||||
}
|
||||
|
||||
STRACE("%s() → %u% m", "getuid", rc);
|
||||
_npassert(rc >= 0);
|
||||
STRACE("%s() → %d", "getuid", rc);
|
||||
return rc;
|
||||
}
|
||||
|
||||
@@ -68,16 +74,21 @@ uint32_t getuid(void) {
|
||||
* This never fails. On Windows, which doesn't really have this concept,
|
||||
* we return a deterministic value that's likely to work.
|
||||
*
|
||||
* @return group id (always successful)
|
||||
* @asyncsignalsafe
|
||||
* @threadsafe
|
||||
* @vforksafe
|
||||
*/
|
||||
uint32_t getgid(void) {
|
||||
uint32_t rc;
|
||||
if (!IsWindows()) {
|
||||
int rc;
|
||||
if (IsMetal()) {
|
||||
rc = 0;
|
||||
} else if (!IsWindows()) {
|
||||
rc = sys_getgid();
|
||||
} else {
|
||||
rc = GetUserNameHash();
|
||||
}
|
||||
STRACE("%s() → %u% m", "getgid", rc);
|
||||
_npassert(rc >= 0);
|
||||
STRACE("%s() → %d", "getgid", rc);
|
||||
return rc;
|
||||
}
|
||||
@@ -31,11 +31,12 @@
|
||||
|
||||
textwindows bool _check_interrupts(bool restartable, struct Fd *fd) {
|
||||
bool res;
|
||||
if (__time_critical) return false;
|
||||
if (__threaded && __threaded != gettid()) return false;
|
||||
if (_weaken(_check_sigalrm)) _weaken(_check_sigalrm)();
|
||||
if (_weaken(_check_sigchld)) _weaken(_check_sigchld)();
|
||||
if (fd && _weaken(_check_sigwinch)) _weaken(_check_sigwinch)(fd);
|
||||
if (!(__get_tls()->tib_flags & TIB_FLAG_TIME_CRITICAL)) {
|
||||
if (_weaken(_check_sigchld)) _weaken(_check_sigchld)();
|
||||
if (fd && _weaken(_check_sigwinch)) _weaken(_check_sigwinch)(fd);
|
||||
}
|
||||
res = _weaken(__sig_check) && _weaken(__sig_check)(restartable);
|
||||
return res;
|
||||
}
|
||||
+42
-4
@@ -28,13 +28,51 @@
|
||||
#include "libc/zipos/zipos.internal.h"
|
||||
|
||||
/**
|
||||
* Changes current position of file descriptor/handle.
|
||||
* Changes current position of file descriptor, e.g.
|
||||
*
|
||||
* int fd = open("hello.bin", O_RDONLY);
|
||||
* lseek(fd, 100, SEEK_SET); // set position to 100th byte
|
||||
* read(fd, buf, 8); // read bytes 100 through 107
|
||||
*
|
||||
* This function may be used to inspect the current position:
|
||||
*
|
||||
* int64_t pos = lseek(fd, 0, SEEK_CUR);
|
||||
*
|
||||
* You may seek past the end of file. If a write happens afterwards
|
||||
* then the gap leading up to it will be filled with zeroes. Please
|
||||
* note that lseek() by itself will not extend the physical medium.
|
||||
*
|
||||
* If dup() is used then the current position will be shared across
|
||||
* multiple file descriptors. If you seek in one it will implicitly
|
||||
* seek the other too.
|
||||
*
|
||||
* The current position of a file descriptor is shared between both
|
||||
* processes and threads. For example, if an fd is inherited across
|
||||
* fork(), and both the child and parent want to read from it, then
|
||||
* changes made by one are observable to the other.
|
||||
*
|
||||
* The pread() and pwrite() functions obfuscate the need for having
|
||||
* global shared file position state. Consider using them, since it
|
||||
* helps avoid the gotchas of this interface described above.
|
||||
*
|
||||
* This function is supported by all OSes within our support vector
|
||||
* and our unit tests demonstrate the behaviors described above are
|
||||
* consistent across platforms.
|
||||
*
|
||||
* @param fd is a number returned by open()
|
||||
* @param offset is the relative byte count
|
||||
* @param whence can be SEEK_SET, SEEK_CUR, or SEEK_END
|
||||
* @return new position relative to beginning, or -1 on error
|
||||
* @param offset is 0-indexed byte count w.r.t. `whence`
|
||||
* @param whence can be one of:
|
||||
* - `SEEK_SET`: Sets the file position to `offset` [default]
|
||||
* - `SEEK_CUR`: Sets the file position to `position + offset`
|
||||
* - `SEEK_END`: Sets the file position to `filesize + offset`
|
||||
* @return new position relative to beginning, or -1 w/ errno
|
||||
* @raise ESPIPE if `fd` is a pipe, socket, or fifo
|
||||
* @raise EBADF if `fd` isn't an open file descriptor
|
||||
* @raise EINVAL if resulting offset would be negative
|
||||
* @raise EINVAL if `whence` isn't valid
|
||||
* @asyncsignalsafe
|
||||
* @threadsafe
|
||||
* @vforksafe
|
||||
*/
|
||||
int64_t lseek(int fd, int64_t offset, unsigned whence) {
|
||||
int64_t rc;
|
||||
|
||||
+28
-22
@@ -34,8 +34,15 @@
|
||||
static bool NeedsQuotes(const char *s) {
|
||||
if (!*s) return true;
|
||||
do {
|
||||
if (*s == ' ' || *s == '\t') {
|
||||
return true;
|
||||
switch (*s) {
|
||||
case '"':
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\v':
|
||||
case '\n':
|
||||
return true;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} while (*s++);
|
||||
return false;
|
||||
@@ -45,19 +52,21 @@ static inline int IsAlpha(int c) {
|
||||
return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts System V argv to Windows-style command line.
|
||||
*
|
||||
* Escaping is performed and it's designed to round-trip with
|
||||
* GetDosArgv() or GetDosArgv(). This function does NOT escape
|
||||
* command interpreter syntax, e.g. $VAR (sh), %VAR% (cmd).
|
||||
*
|
||||
* @param cmdline is output buffer
|
||||
* @param prog is used as argv[0]
|
||||
* @param argv is an a NULL-terminated array of UTF-8 strings
|
||||
* @return freshly allocated lpCommandLine or NULL w/ errno
|
||||
* @see libc/runtime/dosargv.c
|
||||
*/
|
||||
// Converts System V argv to Windows-style command line.
|
||||
//
|
||||
// Escaping is performed and it's designed to round-trip with
|
||||
// GetDosArgv() or GetDosArgv(). This function does NOT escape
|
||||
// command interpreter syntax, e.g. $VAR (sh), %VAR% (cmd).
|
||||
//
|
||||
// TODO(jart): this needs fuzzing and security review
|
||||
//
|
||||
// @param cmdline is output buffer
|
||||
// @param prog is frontloaded as argv[0]
|
||||
// @param argv is an a NULL-terminated array of UTF-8 strings
|
||||
// @return 0 on success, or -1 w/ errno
|
||||
// @raise E2BIG if everything is too huge
|
||||
// @see "Everyone quotes command line arguments the wrong way" MSDN
|
||||
// @see libc/runtime/getdosargv.c
|
||||
textwindows int mkntcmdline(char16_t cmdline[ARG_MAX / 2], const char *prog,
|
||||
char *const argv[]) {
|
||||
char *arg;
|
||||
@@ -102,8 +111,8 @@ textwindows int mkntcmdline(char16_t cmdline[ARG_MAX / 2], const char *prog,
|
||||
} else {
|
||||
// turn stuff like `less /c/...`
|
||||
// into `less c:/...`
|
||||
// turn stuff like `more <\\\"/c/...\\\"`
|
||||
// into `more <\\\"c:/...\\\"`
|
||||
// turn stuff like `more <"/c/..."`
|
||||
// into `more <"c:/..."`
|
||||
if (k > 3 && IsAlpha(cmdline[k - 1]) &&
|
||||
(cmdline[k - 2] == '/' || cmdline[k - 2] == '\\') &&
|
||||
(cmdline[k - 3] == '"' || cmdline[k - 3] == ' ')) {
|
||||
@@ -115,11 +124,8 @@ textwindows int mkntcmdline(char16_t cmdline[ARG_MAX / 2], const char *prog,
|
||||
if (x == '\\') {
|
||||
++slashes;
|
||||
} else if (x == '"') {
|
||||
for (s = 0; s < slashes * 2; ++s) {
|
||||
APPEND(u'\\');
|
||||
}
|
||||
slashes = 0;
|
||||
APPEND(u'\\');
|
||||
APPEND(u'"');
|
||||
APPEND(u'"');
|
||||
APPEND(u'"');
|
||||
} else {
|
||||
for (s = 0; s < slashes; ++s) {
|
||||
|
||||
+21
-2
@@ -17,8 +17,8 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/ntmagicpaths.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/syscall_support-nt.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/macros.internal.h"
|
||||
#include "libc/nt/systeminfo.h"
|
||||
#include "libc/str/oldutf16.internal.h"
|
||||
@@ -173,5 +173,24 @@ textwindows int __mkntpath2(const char *path,
|
||||
p[j] = 0;
|
||||
n = j;
|
||||
|
||||
return x + m + n;
|
||||
// our path is now stored at `path16` with length `n`
|
||||
n = x + m + n;
|
||||
|
||||
// To avoid toil like this:
|
||||
//
|
||||
// CMD.EXE was started with the above path as the current directory.
|
||||
// UNC paths are not supported. Defaulting to Windows directory.
|
||||
// Access is denied.
|
||||
//
|
||||
// Remove \\?\ prefix if we're within 260 character limit.
|
||||
if (n > 4 && n < 260 && //
|
||||
path16[0] == '\\' && //
|
||||
path16[1] == '\\' && //
|
||||
path16[2] == '?' && //
|
||||
path16[3] == '\\') {
|
||||
memmove(path16, path16 + 4, (n - 4 + 1) * sizeof(char16_t));
|
||||
n -= 4;
|
||||
}
|
||||
|
||||
return n;
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
/*-*- 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 2021 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. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/assert.h"
|
||||
#include "libc/calls/internal.h"
|
||||
#include "libc/calls/sig.internal.h"
|
||||
#include "libc/calls/state.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/struct/timespec.internal.h"
|
||||
#include "libc/limits.h"
|
||||
#include "libc/macros.internal.h"
|
||||
#include "libc/nexgen32e/rdtsc.h"
|
||||
#include "libc/nt/errors.h"
|
||||
#include "libc/nt/synchronization.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
#include "libc/time/clockstonanos.internal.h"
|
||||
|
||||
textwindows int sys_nanosleep_nt(const struct timespec *req,
|
||||
struct timespec *rem) {
|
||||
bool alertable;
|
||||
uint32_t slice;
|
||||
uint64_t begin;
|
||||
int64_t ms, toto, nanos;
|
||||
struct timespec elapsed;
|
||||
|
||||
// check req is legal timespec
|
||||
if (!(0 <= req->tv_nsec && req->tv_nsec < 1000000000)) {
|
||||
return einval();
|
||||
}
|
||||
|
||||
// save beginning timestamp
|
||||
if (!__time_critical && rem) {
|
||||
begin = rdtsc();
|
||||
} else {
|
||||
begin = 0; // to prevent uninitialized warning
|
||||
}
|
||||
|
||||
// convert timespec to milliseconds
|
||||
if (__builtin_mul_overflow(req->tv_sec, 1000, &ms) ||
|
||||
__builtin_add_overflow(ms, (req->tv_nsec + 999999) / 1000000, &ms)) {
|
||||
ms = INT64_MAX;
|
||||
}
|
||||
|
||||
for (toto = ms;;) {
|
||||
|
||||
// check if signal was delivered
|
||||
if (!__time_critical && _check_interrupts(false, g_fds.p)) {
|
||||
if (rem) {
|
||||
nanos = ClocksToNanos(rdtsc(), begin);
|
||||
elapsed.tv_sec = nanos / 1000000000;
|
||||
elapsed.tv_nsec = nanos % 1000000000;
|
||||
*rem = _timespec_sub(*req, elapsed);
|
||||
if (rem->tv_sec < 0) {
|
||||
rem->tv_sec = 0;
|
||||
rem->tv_nsec = 0;
|
||||
}
|
||||
}
|
||||
return eintr();
|
||||
}
|
||||
|
||||
// configure the sleep
|
||||
slice = MIN(__SIG_POLLING_INTERVAL_MS, ms);
|
||||
if (__time_critical) {
|
||||
alertable = false;
|
||||
} else {
|
||||
alertable = true;
|
||||
POLLTRACE("... sleeping %'ldms of %'ld", toto - ms, toto);
|
||||
}
|
||||
|
||||
// perform the sleep
|
||||
if (SleepEx(slice, alertable) == kNtWaitIoCompletion) {
|
||||
POLLTRACE("IOCP EINTR"); // in case we ever figure it out
|
||||
continue;
|
||||
}
|
||||
|
||||
// check if full duration has elapsed
|
||||
if ((ms -= slice) <= 0) {
|
||||
if (rem) {
|
||||
rem->tv_sec = 0;
|
||||
rem->tv_nsec = 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-20
@@ -19,40 +19,34 @@
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/calls/struct/timespec.internal.h"
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
#include "libc/calls/struct/timeval.internal.h"
|
||||
#include "libc/errno.h"
|
||||
#include "libc/fmt/conv.h"
|
||||
#include "libc/sock/internal.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
|
||||
// nanosleep() on xnu: a bloodbath of a polyfill
|
||||
// consider using clock_nanosleep(TIMER_ABSTIME)
|
||||
int sys_nanosleep_xnu(const struct timespec *req, struct timespec *rem) {
|
||||
int rc;
|
||||
axdx_t axdx;
|
||||
struct timeval tv;
|
||||
struct timespec begin, end, elapsed;
|
||||
|
||||
if (rem) {
|
||||
if (sys_clock_gettime_xnu(CLOCK_MONOTONIC, &begin) == -1) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
tv = _timespec2timeval(*req);
|
||||
rc = sys_select(0, 0, 0, 0, &tv);
|
||||
|
||||
struct timeval wt, t1, t2, td;
|
||||
if (rem) sys_gettimeofday_xnu(&t1, 0, 0);
|
||||
wt = _timespec_totimeval(*req); // rounds up
|
||||
rc = sys_select(0, 0, 0, 0, &wt);
|
||||
if (rem) {
|
||||
if (!rc) {
|
||||
rem->tv_sec = 0;
|
||||
rem->tv_nsec = 0;
|
||||
} else if (rc == -1 && errno == EINTR) {
|
||||
sys_clock_gettime_xnu(CLOCK_MONOTONIC, &end);
|
||||
elapsed = _timespec_sub(end, begin);
|
||||
*rem = _timespec_sub(*req, elapsed);
|
||||
if (rem->tv_sec < 0) {
|
||||
// xnu select() doesn't modify timeout
|
||||
// so we need, yet another system call
|
||||
sys_gettimeofday_xnu(&t2, 0, 0);
|
||||
td = _timeval_sub(t2, t1);
|
||||
if (_timeval_gte(td, wt)) {
|
||||
rem->tv_sec = 0;
|
||||
rem->tv_nsec = 0;
|
||||
} else {
|
||||
*rem = _timeval_totimespec(_timeval_sub(wt, td));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rc;
|
||||
}
|
||||
+12
-49
@@ -16,67 +16,30 @@
|
||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/asan.internal.h"
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/state.internal.h"
|
||||
#include "libc/calls/struct/timespec.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/describeflags.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/errno.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
|
||||
/**
|
||||
* Sleeps for a particular amount of time.
|
||||
* Sleeps for relative amount of time.
|
||||
*
|
||||
* @param req is the duration of time we should sleep
|
||||
* @param rem if non-NULL will receive the amount of time that wasn't
|
||||
* slept because a signal was delivered. If no signal's delivered
|
||||
* then this value will be set to `{0, 0}`. It's also fine to set
|
||||
* this value to the same pointer as `req`.
|
||||
* @param rem if non-null will be updated with the remainder of unslept
|
||||
* time when -1 w/ `EINTR` is returned otherwise `rem` is undefined
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @raise EINVAL if `req->tv_nsec ∉ [0,1000000000)`
|
||||
* @raise EINTR if a signal was delivered, and `rem` is updated
|
||||
* @raise EINTR if a signal was delivered and `rem` is updated
|
||||
* @raise EFAULT if `req` is NULL or `req` / `rem` is a bad pointer
|
||||
* @raise ENOSYS on bare metal
|
||||
* @note POSIX.1 specifies nanosleep() measures against `CLOCK_REALTIME`
|
||||
* however Linux measures uses `CLOCK_MONOTONIC`. This shouldn't
|
||||
* matter, since POSIX.1 further specifies that discontinuous
|
||||
* changes in `CLOCK_REALTIME` shouldn't impact nanosleep()
|
||||
* @see clock_nanosleep()
|
||||
* @norestart
|
||||
*/
|
||||
int nanosleep(const struct timespec *req, struct timespec *rem) {
|
||||
int rc;
|
||||
|
||||
if (!req || (IsAsan() && (!__asan_is_valid_timespec(req) ||
|
||||
(rem && !__asan_is_valid_timespec(rem))))) {
|
||||
rc = efault();
|
||||
} else if (req->tv_sec < 0 ||
|
||||
!(0 <= req->tv_nsec && req->tv_nsec <= 999999999)) {
|
||||
rc = einval();
|
||||
} else if (!IsWindows() && !IsMetal() && !IsXnu()) {
|
||||
rc = sys_nanosleep(req, rem);
|
||||
} else if (IsXnu()) {
|
||||
rc = sys_nanosleep_xnu(req, rem);
|
||||
} else if (IsMetal()) {
|
||||
rc = enosys(); /* TODO: Sleep on Metal */
|
||||
if (!(rc = clock_nanosleep(CLOCK_REALTIME, 0, req, rem))) {
|
||||
return 0;
|
||||
} else {
|
||||
rc = sys_nanosleep_nt(req, rem);
|
||||
errno = rc;
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Linux Kernel doesn't change the remainder value on success, but
|
||||
// some kernels like OpenBSD will. POSIX doesn't specify the Linux
|
||||
// behavior. So we polyfill it here.
|
||||
if (!rc && rem) {
|
||||
rem->tv_sec = 0;
|
||||
rem->tv_nsec = 0;
|
||||
}
|
||||
|
||||
#ifdef SYSDEBUG
|
||||
if (!__time_critical) {
|
||||
STRACE("nanosleep(%s, [%s]) → %d% m", DescribeTimespec(rc, req),
|
||||
DescribeTimespec(rc, rem), rc);
|
||||
}
|
||||
#endif
|
||||
|
||||
return rc;
|
||||
}
|
||||
+7
-8
@@ -17,20 +17,21 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/assert.h"
|
||||
#include "libc/intrin/bits.h"
|
||||
#include "libc/intrin/initializer.internal.h"
|
||||
#include "libc/intrin/safemacros.internal.h"
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/clock_gettime.internal.h"
|
||||
#include "libc/calls/state.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/syscall_support-sysv.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/bits.h"
|
||||
#include "libc/intrin/initializer.internal.h"
|
||||
#include "libc/intrin/safemacros.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/macros.internal.h"
|
||||
#include "libc/nexgen32e/rdtsc.h"
|
||||
#include "libc/nexgen32e/x86feature.h"
|
||||
#include "libc/str/str.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
#include "libc/thread/tls.h"
|
||||
#include "libc/time/time.h"
|
||||
|
||||
static clock_gettime_f *__gettime;
|
||||
@@ -53,11 +54,9 @@ static long double GetTimeSample(void) {
|
||||
}
|
||||
|
||||
static long double MeasureNanosPerCycle(void) {
|
||||
bool tc;
|
||||
int i, n;
|
||||
long double avg, samp;
|
||||
tc = __time_critical;
|
||||
__time_critical = true;
|
||||
__get_tls()->tib_flags |= TIB_FLAG_TIME_CRITICAL;
|
||||
if (IsWindows()) {
|
||||
n = 10;
|
||||
} else {
|
||||
@@ -67,7 +66,7 @@ static long double MeasureNanosPerCycle(void) {
|
||||
samp = GetTimeSample();
|
||||
avg += (samp - avg) / i;
|
||||
}
|
||||
__time_critical = tc;
|
||||
__get_tls()->tib_flags &= ~TIB_FLAG_TIME_CRITICAL;
|
||||
STRACE("MeasureNanosPerCycle cpn*1000=%d", (long)(avg * 1000));
|
||||
return avg;
|
||||
}
|
||||
|
||||
@@ -18,17 +18,18 @@
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/state.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/bits.h"
|
||||
#include "libc/intrin/initializer.internal.h"
|
||||
#include "libc/intrin/safemacros.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/macros.internal.h"
|
||||
#include "libc/nexgen32e/rdtsc.h"
|
||||
#include "libc/nexgen32e/x86feature.h"
|
||||
#include "libc/str/str.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
#include "libc/thread/tls.h"
|
||||
#include "libc/time/time.h"
|
||||
|
||||
static struct Now {
|
||||
@@ -50,11 +51,9 @@ static long double GetTimeSample(void) {
|
||||
}
|
||||
|
||||
static long double MeasureNanosPerCycle(void) {
|
||||
bool tc;
|
||||
int i, n;
|
||||
long double avg, samp;
|
||||
tc = __time_critical;
|
||||
__time_critical = true;
|
||||
__get_tls()->tib_flags |= TIB_FLAG_TIME_CRITICAL;
|
||||
if (IsWindows()) {
|
||||
n = 30;
|
||||
} else {
|
||||
@@ -64,7 +63,7 @@ static long double MeasureNanosPerCycle(void) {
|
||||
samp = GetTimeSample();
|
||||
avg += (samp - avg) / i;
|
||||
}
|
||||
__time_critical = tc;
|
||||
__get_tls()->tib_flags &= ~TIB_FLAG_TIME_CRITICAL;
|
||||
STRACE("MeasureNanosPerCycle cpn*1000=%d", (long)(avg * 1000));
|
||||
return avg;
|
||||
}
|
||||
|
||||
+9
-8
@@ -22,16 +22,17 @@
|
||||
/**
|
||||
* Opens file.
|
||||
*
|
||||
* @param file is a UTF-8 string, preferably relative w/ forward slashes
|
||||
* @param flags should be O_RDONLY, O_WRONLY, or O_RDWR, and can be or'd
|
||||
* with O_CREAT, O_TRUNC, O_APPEND, O_EXCL, O_CLOEXEC, O_TMPFILE
|
||||
* @param mode is an octal user/group/other permission signifier, that's
|
||||
* ignored if O_CREAT or O_TMPFILE weren't passed
|
||||
* @return number needing close(), or -1 w/ errno
|
||||
* @asyncsignalsafe (zip files may have issues)
|
||||
* @vforksafe (raises error if zip file)
|
||||
* This is equivalent to saying:
|
||||
*
|
||||
* int fd = openat(AT_FDCWD, file, flags, ...);
|
||||
*
|
||||
* @param file specifies filesystem path to open
|
||||
* @return file descriptor, or -1 w/ errno
|
||||
* @see openat() for further documentation
|
||||
* @asyncsignalsafe
|
||||
* @restartable
|
||||
* @threadsafe
|
||||
* @vforksafe
|
||||
*/
|
||||
int open(const char *file, int flags, ...) {
|
||||
va_list va;
|
||||
|
||||
+109
-12
@@ -36,17 +36,114 @@
|
||||
/**
|
||||
* Opens file.
|
||||
*
|
||||
* @param dirfd is normally AT_FDCWD but if it's an open directory and
|
||||
* file is a relative path, then file is opened relative to dirfd
|
||||
* @param file is a UTF-8 string, preferably relative w/ forward slashes
|
||||
* @param flags should be O_RDONLY, O_WRONLY, or O_RDWR, and can be or'd
|
||||
* with O_CREAT, O_TRUNC, O_APPEND, O_EXCL, O_CLOEXEC, O_TMPFILE
|
||||
* @param mode is an octal user/group/other permission signifier, that's
|
||||
* ignored if O_CREAT or O_TMPFILE weren't passed
|
||||
* @return number needing close(), or -1 w/ errno
|
||||
* @asyncsignalsafe (zip files may have issues)
|
||||
* @vforksafe (raises error if zip file)
|
||||
* Here's an example of how a file can be created:
|
||||
*
|
||||
* int fd = openat(AT_FDCWD, "hi.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644);
|
||||
* write(fd, "hello\n", 6);
|
||||
* close(fd);
|
||||
*
|
||||
* Here's an example of how that file could read back into memory:
|
||||
*
|
||||
* char data[513] = {0};
|
||||
* int fd = openat(AT_FDCWD, "hi.txt", O_RDONLY);
|
||||
* read(fd, data, 512);
|
||||
* close(fd);
|
||||
* assert(!strcmp(data, "hello\n"));
|
||||
*
|
||||
* If your main() source file has this statement:
|
||||
*
|
||||
* STATIC_YOINK("zip_uri_support");
|
||||
*
|
||||
* Then you can read zip assets by adding a `"/zip/..."` prefix to `file`, e.g.
|
||||
*
|
||||
* // run `zip program.com hi.txt` beforehand
|
||||
* openat(AT_FDCWD, "/zip/hi.txt", O_RDONLY);
|
||||
*
|
||||
* @param dirfd is normally `AT_FDCWD` but if it's an open directory and
|
||||
* `file` names a relative path then it's opened relative to `dirfd`
|
||||
* @param file is a UTF-8 string naming filesystem entity, e.g. `foo/bar.txt`,
|
||||
* which on Windows is bludgeoned into a WIN32 path automatically, e.g.
|
||||
* - `foo/bar.txt` becomes `foo\bar.txt`
|
||||
* - `/tmp/...` becomes whatever GetTempPath() is
|
||||
* - `\\...` or `//...` is passed through to WIN32 unchanged
|
||||
* - `/c/foo` or `\c\foo` becomes `\\?\c:\foo`
|
||||
* - `c:/foo` or `c:\foo` becomes `\\?\c:\foo`
|
||||
* - `/D` becomes `\\?\D:\`
|
||||
* @param flags must have one of the following under the `O_ACCMODE` bits:
|
||||
* - `O_RDONLY` to open `file` for reading only
|
||||
* - `O_WRONLY` to open `file` for writing
|
||||
* - `O_RDWR` to open `file` for reading and writing
|
||||
* The following may optionally be bitwise or'd into `flags`:
|
||||
* - `O_CREAT` create file if it doesn't exist
|
||||
* - `O_TRUNC` automatic `ftruncate(fd,0)` if exists
|
||||
* - `O_CLOEXEC` automatic close() upon execve()
|
||||
* - `O_EXCL` exclusive access (see below)
|
||||
* - `O_APPEND` open file for appending only
|
||||
* - `O_EXEC` open file for execution only; see fexecve()
|
||||
* - `O_NOCTTY` prevents `file` possibly becoming controlling terminal
|
||||
* - `O_NONBLOCK` asks read/write to fail with `EAGAIN` rather than block
|
||||
* - `O_DIRECT` it's complicated (not supported on Apple and OpenBSD)
|
||||
* - `O_DIRECTORY` useful for stat'ing (hint on UNIX but required on NT)
|
||||
* - `O_NOFOLLOW` fail if it's a symlink (zero on Windows)
|
||||
* - `O_DSYNC` it's complicated (zero on non-Linux/Apple)
|
||||
* - `O_RSYNC` it's complicated (zero on non-Linux/Apple)
|
||||
* - `O_VERIFY` it's complicated (zero on non-FreeBSD)
|
||||
* - `O_SHLOCK` it's complicated (zero on non-BSD)
|
||||
* - `O_EXLOCK` it's complicated (zero on non-BSD)
|
||||
* - `O_PATH` open only for metadata (Linux 2.6.39+ otherwise zero)
|
||||
* - `O_NOATIME` don't record access time (zero on non-Linux)
|
||||
* - `O_RANDOM` hint random access intent (zero on non-Windows)
|
||||
* - `O_SEQUENTIAL` hint sequential access intent (zero on non-Windows)
|
||||
* - `O_COMPRESSED` ask fs to abstract compression (zero on non-Windows)
|
||||
* - `O_INDEXED` turns on that slow performance (zero on non-Windows)
|
||||
* - `O_TMPFILE` should not be used; use tmpfd() or tmpfile() instead
|
||||
* There are three regular combinations for the above flags:
|
||||
* - `O_RDONLY`: Opens existing file for reading. If it doesn't
|
||||
* exist then nil is returned and errno will be `ENOENT` (or in
|
||||
* some other cases `ENOTDIR`).
|
||||
* - `O_WRONLY|O_CREAT|O_TRUNC`: Creates file. If it already
|
||||
* exists, then the existing copy is destroyed and the opened
|
||||
* file will start off with a length of zero. This is the
|
||||
* behavior of the traditional creat() system call.
|
||||
* - `O_WRONLY|O_CREAT|O_EXCL`: Create file only if doesn't exist
|
||||
* already. If it does exist then `nil` is returned along with
|
||||
* `errno` set to `EEXIST`.
|
||||
* @param mode is an octal user/group/other permission signifier that's
|
||||
* ignored if `O_CREAT` isn't passed in `flags`; when creating files
|
||||
* you'll usually want `mode` to be `0644` which enables global read
|
||||
* and only permits the owner to write; or when creating executables
|
||||
* you'll usually want `mode` to be `0755` which is the same, except
|
||||
* the executable bit is set thrice too
|
||||
* @return file descriptor (which needs to be close()'d), or -1 w/ errno
|
||||
* @raise EPERM if pledge() is in play w/o appropriate rpath/wpath/cpath
|
||||
* @raise EACCES if unveil() is in play and didn't unveil your `file` path
|
||||
* @raise EACCES if we don't have permission to search a component of `file`
|
||||
* @raise EACCES if file exists but requested `flags & O_ACCMODE` was denied
|
||||
* @raise EACCES if file doesn't exist and parent dir lacks write permissions
|
||||
* @raise EACCES if `O_TRUNC` was specified in `flags` but writing was denied
|
||||
* @raise ENOTSUP if `file` is on zip file system and `dirfd` isn't `AT_FDCWD`
|
||||
* @raise ENOTDIR if a directory component in `file` exists as non-directory
|
||||
* @raise ENOTDIR if `file` is relative and `dirfd` isn't an open directory
|
||||
* @raise EROFS when writing is requested w/ `file` on read-only filesystem
|
||||
* @raise ENAMETOOLONG if symlink-resolved `file` length exceeds `PATH_MAX`
|
||||
* @raise ENAMETOOLONG if component in `file` exists longer than `NAME_MAX`
|
||||
* @raise ENOTSUP if `file` is on zip file system and process is vfork()'d
|
||||
* @raise ENOSPC if file system is full when `file` would be `O_CREAT`ed
|
||||
* @raise EINTR if we needed to block and a signal was delivered instead
|
||||
* @raise ENOENT if `file` doesn't exist when `O_CREAT` isn't in `flags`
|
||||
* @raise ENOENT if `file` points to a string that's empty
|
||||
* @raise ENOMEM if insufficient memory was available
|
||||
* @raise EMFILE if `RLIMIT_NOFILE` has been reached
|
||||
* @raise EOPNOTSUPP if `file` names a named socket
|
||||
* @raise EFAULT if `file` points to invalid memory
|
||||
* @raise ETXTBSY if writing is requested on `file` that's being executed
|
||||
* @raise ELOOP if `flags` had `O_NOFOLLOW` and `file` is a symbolic link
|
||||
* @raise ELOOP if a loop was detected resolving components of `file`
|
||||
* @raise EISDIR if writing is requested and `file` names a directory
|
||||
* @asyncsignalsafe
|
||||
* @restartable
|
||||
* @threadsafe
|
||||
* @vforksafe
|
||||
*/
|
||||
int openat(int dirfd, const char *file, int flags, ...) {
|
||||
int rc;
|
||||
@@ -63,7 +160,7 @@ int openat(int dirfd, const char *file, int flags, ...) {
|
||||
if (!__vforked && dirfd == AT_FDCWD) {
|
||||
rc = _weaken(__zipos_open)(&zipname, flags, mode);
|
||||
} else {
|
||||
rc = eopnotsupp(); /* TODO */
|
||||
rc = enotsup(); /* TODO */
|
||||
}
|
||||
} else if (!IsWindows() && !IsMetal()) {
|
||||
rc = sys_openat(dirfd, file, flags, mode);
|
||||
@@ -73,7 +170,7 @@ int openat(int dirfd, const char *file, int flags, ...) {
|
||||
rc = sys_open_nt(dirfd, file, flags, mode);
|
||||
}
|
||||
} else {
|
||||
rc = eopnotsupp(); /* TODO */
|
||||
rc = enotsup(); /* TODO */
|
||||
}
|
||||
} else {
|
||||
rc = efault();
|
||||
|
||||
@@ -554,6 +554,8 @@ static const uint16_t kPledgeStdio[] = {
|
||||
__NR_linux_set_robust_list, //
|
||||
__NR_linux_get_robust_list, //
|
||||
__NR_linux_prlimit | STDIO, //
|
||||
__NR_linux_sched_getaffinity, //
|
||||
__NR_linux_sched_setaffinity, //
|
||||
};
|
||||
|
||||
static const uint16_t kPledgeFlock[] = {
|
||||
@@ -705,8 +707,6 @@ static const uint16_t kPledgeProc[] = {
|
||||
__NR_linux_sched_setscheduler, //
|
||||
__NR_linux_sched_get_priority_min, //
|
||||
__NR_linux_sched_get_priority_max, //
|
||||
__NR_linux_sched_getaffinity, //
|
||||
__NR_linux_sched_setaffinity, //
|
||||
__NR_linux_sched_getparam, //
|
||||
__NR_linux_sched_setparam, //
|
||||
};
|
||||
|
||||
+2
-2
@@ -19,11 +19,11 @@
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/pledge.internal.h"
|
||||
#include "libc/calls/state.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/syscall-sysv.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/errno.h"
|
||||
#include "libc/intrin/promises.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/runtime/runtime.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
@@ -110,7 +110,7 @@
|
||||
* fcntl(F_SETFD), fcntl(F_GETFL), fcntl(F_SETFL), sched_yield,
|
||||
* epoll_create, epoll_create1, epoll_ctl, epoll_wait, epoll_pwait,
|
||||
* epoll_pwait2, clone(CLONE_THREAD), futex, set_robust_list,
|
||||
* get_robust_list, sigpending.
|
||||
* get_robust_list, setaffinity, sigpending.
|
||||
*
|
||||
* - "rpath" (read-only path ops) allows chdir, getcwd, open(O_RDONLY),
|
||||
* openat(O_RDONLY), stat, fstat, lstat, fstatat, access, faccessat,
|
||||
|
||||
@@ -41,6 +41,8 @@ int sys_fadvise_netbsd(int, int, int64_t, int64_t, int) asm("sys_fadvise");
|
||||
* @raise EINVAL if `advice` is invalid or `len` is huge
|
||||
* @raise ESPIPE if `fd` refers to a pipe
|
||||
* @raise ENOSYS on XNU and OpenBSD
|
||||
* @returnserrno
|
||||
* @threadsafe
|
||||
*/
|
||||
errno_t posix_fadvise(int fd, uint64_t offset, uint64_t len, int advice) {
|
||||
int rc, e = errno;
|
||||
|
||||
@@ -17,7 +17,21 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/errno.h"
|
||||
|
||||
int posix_madvise(void *addr, uint64_t len, int advice) {
|
||||
return madvise(addr, len, advice);
|
||||
/**
|
||||
* Advises kernel about memory intentions, the POSIX way.
|
||||
*
|
||||
* @return 0 on success, or errno on error
|
||||
* @returnserrno
|
||||
* @threadsafe
|
||||
*/
|
||||
errno_t posix_madvise(void *addr, uint64_t len, int advice) {
|
||||
int rc, e = errno;
|
||||
rc = madvise(addr, len, advice);
|
||||
if (rc == -1) {
|
||||
rc = errno;
|
||||
errno = e;
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
+9
-1
@@ -32,7 +32,9 @@
|
||||
#include "libc/zipos/zipos.internal.h"
|
||||
|
||||
/**
|
||||
* Reads from file at offset, thus avoiding superfluous lseek().
|
||||
* Reads from file at offset.
|
||||
*
|
||||
* This function never changes the current position of `fd`.
|
||||
*
|
||||
* @param fd is something open()'d earlier, noting pipes might not work
|
||||
* @param buf is copied into, cf. copy_file_range(), sendfile(), etc.
|
||||
@@ -40,8 +42,14 @@
|
||||
* @param offset is bytes from start of file at which read begins
|
||||
* @return [1..size] bytes on success, 0 on EOF, or -1 w/ errno; with
|
||||
* exception of size==0, in which case return zero means no error
|
||||
* @raise ESPIPE if `fd` isn't seekable
|
||||
* @raise EINVAL if `offset` is negative
|
||||
* @raise EBADF if `fd` isn't an open file descriptor
|
||||
* @raise EIO if a complicated i/o error happened
|
||||
* @raise EINTR if signal was delivered instead
|
||||
* @see pwrite(), write()
|
||||
* @asyncsignalsafe
|
||||
* @threadsafe
|
||||
* @vforksafe
|
||||
*/
|
||||
ssize_t pread(int fd, void *buf, size_t size, int64_t offset) {
|
||||
|
||||
+4
-1
@@ -29,7 +29,9 @@
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
/**
|
||||
* Writes to file at offset, thus avoiding superfluous lseek().
|
||||
* Writes to file at offset.
|
||||
*
|
||||
* This function never changes the current position of `fd`.
|
||||
*
|
||||
* @param fd is something open()'d earlier, noting pipes might not work
|
||||
* @param buf is copied from, cf. copy_file_range(), sendfile(), etc.
|
||||
@@ -41,6 +43,7 @@
|
||||
* impossible unless size was passed as zero to do an error check
|
||||
* @see pread(), write()
|
||||
* @asyncsignalsafe
|
||||
* @threadsafe
|
||||
* @vforksafe
|
||||
*/
|
||||
ssize_t pwrite(int fd, const void *buf, size_t size, int64_t offset) {
|
||||
|
||||
+11
-5
@@ -37,10 +37,12 @@
|
||||
|
||||
static textwindows ssize_t sys_read_nt_impl(struct Fd *fd, void *data,
|
||||
size_t size, ssize_t offset) {
|
||||
bool32 ok;
|
||||
int64_t p;
|
||||
uint32_t got, avail;
|
||||
struct NtOverlapped overlap;
|
||||
|
||||
// our terrible polling mechanism
|
||||
if (GetFileType(fd->handle) == kNtFileTypePipe) {
|
||||
for (;;) {
|
||||
if (!PeekNamedPipe(fd->handle, 0, 0, 0, &avail, 0)) break;
|
||||
@@ -62,11 +64,15 @@ static textwindows ssize_t sys_read_nt_impl(struct Fd *fd, void *data,
|
||||
_npassert(SetFilePointerEx(fd->handle, 0, &p, SEEK_CUR));
|
||||
}
|
||||
|
||||
if (ReadFile(fd->handle, data, _clampio(size), &got,
|
||||
_offset2overlap(fd->handle, offset, &overlap))) {
|
||||
if (offset != -1) {
|
||||
_npassert(SetFilePointerEx(fd->handle, p, 0, SEEK_SET));
|
||||
}
|
||||
ok = ReadFile(fd->handle, data, _clampio(size), &got,
|
||||
_offset2overlap(fd->handle, offset, &overlap));
|
||||
|
||||
if (offset != -1) {
|
||||
// windows clobbers file pointer even on error
|
||||
_npassert(SetFilePointerEx(fd->handle, p, 0, SEEK_SET));
|
||||
}
|
||||
|
||||
if (ok) {
|
||||
return got;
|
||||
}
|
||||
|
||||
|
||||
+21
-3
@@ -33,19 +33,37 @@
|
||||
/**
|
||||
* Reads data from file descriptor.
|
||||
*
|
||||
* This function changes the current file position. For documentation
|
||||
* on file position behaviors and gotchas, see the lseek() function.
|
||||
* This function may be used on socket file descriptors, including on
|
||||
* Windows.
|
||||
*
|
||||
* @param fd is something open()'d earlier
|
||||
* @param buf is copied into, cf. copy_file_range(), sendfile(), etc.
|
||||
* @param size in range [1..0x7ffff000] is reasonable
|
||||
* @return [1..size] bytes on success, 0 on EOF, or -1 w/ errno; with
|
||||
* exception of size==0, in which case return zero means no error
|
||||
* @see write(), pread(), readv()
|
||||
* @raise EBADF if `fd` is negative or not an open file descriptor
|
||||
* @raise EBADF if `fd` is open in `O_WRONLY` mode
|
||||
* @raise EFAULT if `size` is nonzero and `buf` points to bad memory
|
||||
* @raise EPERM if pledge() is in play without the stdio promise
|
||||
* @raise EIO if low-level i/o error happened
|
||||
* @raise EINTR if signal was delivered instead
|
||||
* @raise ENOTCONN if `fd` is a socket and it isn't connected
|
||||
* @raise ECONNRESET if socket peer forcibly closed connection
|
||||
* @raise ETIMEDOUT if socket transmission timeout occurred
|
||||
* @raise EAGAIN if `O_NONBLOCK` is in play and read needs to block,
|
||||
* or `SO_RCVTIMEO` is in play and the time interval elapsed
|
||||
* @raise ENOBUFS is specified by POSIX
|
||||
* @raise ENXIO is specified by POSIX
|
||||
* @asyncsignalsafe
|
||||
* @restartable
|
||||
* @vforksafe
|
||||
*/
|
||||
ssize_t read(int fd, void *buf, size_t size) {
|
||||
ssize_t rc;
|
||||
if (fd >= 0) {
|
||||
if (IsAsan() && !__asan_is_valid(buf, size)) {
|
||||
if ((!buf && size) || (IsAsan() && !__asan_is_valid(buf, size))) {
|
||||
rc = efault();
|
||||
} else if (fd < g_fds.n && g_fds.p[fd].kind == kFdZip) {
|
||||
rc = _weaken(__zipos_read)(
|
||||
@@ -61,7 +79,7 @@ ssize_t read(int fd, void *buf, size_t size) {
|
||||
rc = sys_readv_nt(g_fds.p + fd, &(struct iovec){buf, size}, 1);
|
||||
}
|
||||
} else {
|
||||
rc = einval();
|
||||
rc = ebadf();
|
||||
}
|
||||
DATATRACE("read(%d, [%#.*hhs%s], %'zu) → %'zd% m", fd, MAX(0, MIN(40, rc)),
|
||||
buf, rc > 40 ? "..." : "", size, rc);
|
||||
|
||||
+5
-1
@@ -46,8 +46,8 @@
|
||||
* @restartable
|
||||
*/
|
||||
ssize_t readv(int fd, const struct iovec *iov, int iovlen) {
|
||||
int i;
|
||||
ssize_t rc;
|
||||
|
||||
if (fd >= 0 && iovlen >= 0) {
|
||||
if (IsAsan() && !__asan_is_valid_iov(iov, iovlen)) {
|
||||
rc = efault();
|
||||
@@ -67,9 +67,12 @@ ssize_t readv(int fd, const struct iovec *iov, int iovlen) {
|
||||
} else {
|
||||
rc = sys_readv_nt(g_fds.p + fd, iov, iovlen);
|
||||
}
|
||||
} else if (fd < 0) {
|
||||
rc = ebadf();
|
||||
} else {
|
||||
rc = einval();
|
||||
}
|
||||
|
||||
#if defined(SYSDEBUG) && _DATATRACE
|
||||
if (UNLIKELY(__strace > 0)) {
|
||||
if (rc == -1 && errno == EFAULT) {
|
||||
@@ -81,5 +84,6 @@ ssize_t readv(int fd, const struct iovec *iov, int iovlen) {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
return rc;
|
||||
}
|
||||
@@ -49,7 +49,7 @@ int __ensurefds_unlocked(int fd) {
|
||||
bool relocate;
|
||||
if (fd < g_fds.n) return fd;
|
||||
g_fds.n = fd + 1;
|
||||
g_fds.e = _extend(g_fds.p, g_fds.n * sizeof(*g_fds.p), g_fds.e,
|
||||
g_fds.e = _extend(g_fds.p, g_fds.n * sizeof(*g_fds.p), g_fds.e, MAP_PRIVATE,
|
||||
kMemtrackFdsStart + kMemtrackFdsSize);
|
||||
return fd;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
#ifndef COSMOPOLITAN_LIBC_CALLS_SCHED_SYSV_INTERNAL_H_
|
||||
#define COSMOPOLITAN_LIBC_CALLS_SCHED_SYSV_INTERNAL_H_
|
||||
#include "libc/calls/struct/sched_param.h"
|
||||
#if !(__ASSEMBLER__ + __LINKER__ + 0)
|
||||
COSMOPOLITAN_C_START_
|
||||
|
||||
#define MAXCPUS_NETBSD 256
|
||||
#define MAXCPUS_FREEBSD 256
|
||||
#define MAXCPUS_OPENBSD 64
|
||||
#define P_ALL_LWPS 0 /* for effect on all threads in pid */
|
||||
|
||||
#define CPU_LEVEL_WHICH 3
|
||||
#define CPU_WHICH_TID 1
|
||||
#define CPU_WHICH_PID 2
|
||||
|
||||
#if !(__ASSEMBLER__ + __LINKER__ + 0)
|
||||
COSMOPOLITAN_C_START_
|
||||
|
||||
int sys_sched_get_priority_max(int);
|
||||
int sys_sched_get_priority_min(int);
|
||||
int sys_sched_getparam(int, struct sched_param *);
|
||||
@@ -28,6 +34,12 @@ int sys_sched_setaffinity_netbsd(int, int, size_t, const void *) //
|
||||
int sys_sched_getaffinity_netbsd(int, int, size_t, void *) //
|
||||
asm("sys_sched_setaffinity");
|
||||
|
||||
int sys_sched_setaffinity_freebsd(
|
||||
int level, int which, int id, size_t setsize,
|
||||
const void *mask) asm("sys_sched_setaffinity");
|
||||
int sys_sched_getaffinity_freebsd(int level, int which, int id, size_t setsize,
|
||||
void *mask) asm("sys_sched_getaffinity");
|
||||
|
||||
COSMOPOLITAN_C_END_
|
||||
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
|
||||
#endif /* COSMOPOLITAN_LIBC_CALLS_SCHED_SYSV_INTERNAL_H_ */
|
||||
@@ -17,59 +17,79 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/internal.h"
|
||||
#include "libc/calls/sched-sysv.internal.h"
|
||||
#include "libc/calls/struct/cpuset.h"
|
||||
#include "libc/calls/syscall_support-nt.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/macros.internal.h"
|
||||
#include "libc/nt/enum/processaccess.h"
|
||||
#include "libc/nt/process.h"
|
||||
#include "libc/nt/runtime.h"
|
||||
#include "libc/nt/thread.h"
|
||||
#include "libc/str/str.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
static textwindows int sys_sched_getaffinity_nt(int tid, size_t size,
|
||||
cpu_set_t *bitset) {
|
||||
uint64_t ProcessAffinityMask, SystemAffinityMask;
|
||||
if (GetProcessAffinityMask(GetCurrentProcess(), &ProcessAffinityMask,
|
||||
&SystemAffinityMask)) {
|
||||
bzero(bitset, size);
|
||||
bitset->__bits[0] = ProcessAffinityMask;
|
||||
return 0;
|
||||
static dontinline textwindows int sys_sched_getaffinity_nt(int pid, size_t size,
|
||||
cpu_set_t *bitset) {
|
||||
int rc;
|
||||
int64_t h, closeme = -1;
|
||||
uint64_t SystemAffinityMask;
|
||||
|
||||
if (!pid || pid == getpid()) {
|
||||
h = GetCurrentProcess();
|
||||
} else if (__isfdkind(pid, kFdProcess)) {
|
||||
h = g_fds.p[pid].handle;
|
||||
} else {
|
||||
return __winerr();
|
||||
h = OpenProcess(kNtProcessQueryInformation, false, pid);
|
||||
if (!h) return __winerr();
|
||||
closeme = h;
|
||||
}
|
||||
|
||||
if (GetProcessAffinityMask(h, bitset->__bits, &SystemAffinityMask)) {
|
||||
rc = 8;
|
||||
} else {
|
||||
rc = __winerr();
|
||||
}
|
||||
|
||||
if (closeme != -1) {
|
||||
CloseHandle(closeme);
|
||||
}
|
||||
|
||||
return rc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets CPU affinity for thread.
|
||||
* Gets CPU affinity for process.
|
||||
*
|
||||
* While Windows allows us to change the thread affinity mask, it's only
|
||||
* possible to read the process affinity mask. Therefore this function
|
||||
* won't reflect the changes made by sched_setaffinity() on Windows.
|
||||
*
|
||||
* @param pid is the process or thread id (or 0 for caller)
|
||||
* @param size is byte length of bitset, which should 128
|
||||
* @param pid is the process id (or 0 for caller)
|
||||
* @param size is bytes in bitset, which should be `sizeof(cpuset_t)`
|
||||
* @param bitset receives bitset and should be uint64_t[16] in order to
|
||||
* work on older versions of Linux
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @raise ENOSYS if not Linux, NetBSD, or Windows
|
||||
* @raise ENOSYS if not Linux, FreeBSD, NetBSD, or Windows
|
||||
* @see pthread_getaffinity_np() for threads
|
||||
*/
|
||||
int sched_getaffinity(int tid, size_t size, cpu_set_t *bitset) {
|
||||
int sched_getaffinity(int pid, size_t size, cpu_set_t *bitset) {
|
||||
int rc;
|
||||
if (size != 128) {
|
||||
if (size != sizeof(cpu_set_t)) {
|
||||
rc = einval();
|
||||
} else if (IsWindows()) {
|
||||
rc = sys_sched_getaffinity_nt(tid, size, bitset);
|
||||
rc = sys_sched_getaffinity_nt(pid, size, bitset);
|
||||
} else if (IsFreebsd()) {
|
||||
if (!sys_sched_getaffinity_freebsd(CPU_LEVEL_WHICH, CPU_WHICH_PID, pid, 32,
|
||||
bitset)) {
|
||||
rc = 32;
|
||||
} else {
|
||||
rc = -1;
|
||||
}
|
||||
} else if (IsNetbsd()) {
|
||||
if (!sys_sched_getaffinity_netbsd(0, tid, MIN(size, 32), bitset)) {
|
||||
rc = MIN(size, 32);
|
||||
if (!sys_sched_getaffinity_netbsd(P_ALL_LWPS, pid, 32, bitset)) {
|
||||
rc = 32;
|
||||
} else {
|
||||
rc = -1;
|
||||
}
|
||||
} else {
|
||||
rc = sys_sched_getaffinity(tid, size, bitset);
|
||||
rc = sys_sched_getaffinity(pid, size, bitset);
|
||||
}
|
||||
if (rc > 0) {
|
||||
if (rc < size) {
|
||||
@@ -77,6 +97,6 @@ int sched_getaffinity(int tid, size_t size, cpu_set_t *bitset) {
|
||||
}
|
||||
rc = 0;
|
||||
}
|
||||
STRACE("sched_getaffinity(%d, %'zu, %p) → %d% m", tid, size, bitset);
|
||||
STRACE("sched_getaffinity(%d, %'zu, %p) → %d% m", pid, size, bitset, rc);
|
||||
return rc;
|
||||
}
|
||||
@@ -16,75 +16,69 @@
|
||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/internal.h"
|
||||
#include "libc/calls/sched-sysv.internal.h"
|
||||
#include "libc/calls/struct/cpuset.h"
|
||||
#include "libc/calls/syscall-sysv.internal.h"
|
||||
#include "libc/calls/syscall_support-nt.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/safemacros.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/limits.h"
|
||||
#include "libc/macros.internal.h"
|
||||
#include "libc/nt/enum/processaccess.h"
|
||||
#include "libc/nt/enum/threadaccess.h"
|
||||
#include "libc/nt/process.h"
|
||||
#include "libc/nt/runtime.h"
|
||||
#include "libc/nt/thread.h"
|
||||
#include "libc/str/str.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
static textwindows dontinline int sys_sched_setaffinity_nt(int pid,
|
||||
uint64_t size,
|
||||
const void *bitset) {
|
||||
static dontinline textwindows int sys_sched_setaffinity_nt(
|
||||
int pid, uint64_t size, const cpu_set_t *bitset) {
|
||||
int rc;
|
||||
int64_t handle;
|
||||
uintptr_t mask;
|
||||
typeof(SetThreadAffinityMask) *SetAffinityMask = SetThreadAffinityMask;
|
||||
mask = 0;
|
||||
memcpy(&mask, bitset, min(size, sizeof(uintptr_t)));
|
||||
handle = 0;
|
||||
if (!pid) pid = GetCurrentThreadId();
|
||||
if (0 < pid && pid <= UINT32_MAX) {
|
||||
if (pid == GetCurrentProcessId()) {
|
||||
pid = GetCurrentProcess();
|
||||
SetAffinityMask = SetProcessAffinityMask;
|
||||
} else if (pid == GetCurrentThreadId()) {
|
||||
pid = GetCurrentThread();
|
||||
} else {
|
||||
handle = OpenThread(kNtThreadSetInformation | kNtThreadQueryInformation,
|
||||
false, pid);
|
||||
if (!handle) {
|
||||
handle = OpenProcess(
|
||||
kNtProcessSetInformation | kNtProcessQueryInformation, false, pid);
|
||||
SetAffinityMask = SetProcessAffinityMask;
|
||||
}
|
||||
}
|
||||
int64_t h, closeme = -1;
|
||||
|
||||
if (!pid /* || pid == getpid() */) {
|
||||
h = GetCurrentProcess();
|
||||
} else if (__isfdkind(pid, kFdProcess)) {
|
||||
h = g_fds.p[pid].handle;
|
||||
} else {
|
||||
h = OpenProcess(kNtProcessSetInformation | kNtProcessQueryInformation,
|
||||
false, pid);
|
||||
if (!h) return __winerr();
|
||||
closeme = h;
|
||||
}
|
||||
rc = SetAffinityMask(handle ? handle : pid, mask) ? 0 : __winerr();
|
||||
if (handle) CloseHandle(handle);
|
||||
|
||||
if (SetProcessAffinityMask(h, bitset->__bits[0])) {
|
||||
rc = 0;
|
||||
} else {
|
||||
rc = __winerr();
|
||||
}
|
||||
|
||||
if (closeme != -1) {
|
||||
CloseHandle(closeme);
|
||||
}
|
||||
|
||||
return rc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks kernel to only schedule thread on particular CPUs.
|
||||
* Asks kernel to only schedule process on particular CPUs.
|
||||
*
|
||||
* @param tid is the process or thread id (or 0 for caller)
|
||||
* @param size is byte length of bitset, which should be 128
|
||||
* @param pid is the process or process id (or 0 for caller)
|
||||
* @param size is bytes in bitset, which should be `sizeof(cpuset_t)`
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @raise ENOSYS if not Linux, NetBSD, or Windows
|
||||
* @raise ENOSYS if not Linux, FreeBSD, NetBSD, or Windows
|
||||
* @see pthread_getaffinity_np() for threads
|
||||
*/
|
||||
int sched_setaffinity(int tid, size_t size, const cpu_set_t *bitset) {
|
||||
int sched_setaffinity(int pid, size_t size, const cpu_set_t *bitset) {
|
||||
int rc;
|
||||
if (size != 128) {
|
||||
if (size != sizeof(cpu_set_t)) {
|
||||
rc = einval();
|
||||
} else if (IsWindows()) {
|
||||
rc = sys_sched_setaffinity_nt(tid, size, bitset);
|
||||
rc = sys_sched_setaffinity_nt(pid, size, bitset);
|
||||
} else if (IsFreebsd()) {
|
||||
rc = sys_sched_setaffinity_freebsd(CPU_LEVEL_WHICH, CPU_WHICH_PID, pid, 32,
|
||||
bitset);
|
||||
} else if (IsNetbsd()) {
|
||||
rc = sys_sched_setaffinity_netbsd(0, tid, MIN(size, 32), bitset);
|
||||
rc = sys_sched_setaffinity_netbsd(P_ALL_LWPS, pid, 32, bitset);
|
||||
} else {
|
||||
rc = sys_sched_setaffinity(tid, size, bitset);
|
||||
rc = sys_sched_setaffinity(pid, size, bitset);
|
||||
}
|
||||
STRACE("sched_setaffinity(%d, %'zu, %p) → %d% m", tid, size, bitset);
|
||||
STRACE("sched_setaffinity(%d, %'zu, %p) → %d% m", pid, size, bitset, rc);
|
||||
return rc;
|
||||
}
|
||||
+18
-16
@@ -16,11 +16,11 @@
|
||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/struct/itimerval.h"
|
||||
#include "libc/calls/struct/itimerval.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/asan.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
#include "libc/time/time.h"
|
||||
|
||||
@@ -29,28 +29,28 @@
|
||||
*
|
||||
* Raise SIGALRM every 1.5s:
|
||||
*
|
||||
* CHECK_NE(-1, sigaction(SIGALRM,
|
||||
* &(struct sigaction){.sa_sigaction = _missingno},
|
||||
* NULL));
|
||||
* CHECK_NE(-1, setitimer(ITIMER_REAL,
|
||||
* &(const struct itimerval){{1, 500000},
|
||||
* {1, 500000}},
|
||||
* NULL));
|
||||
* sigaction(SIGALRM,
|
||||
* &(struct sigaction){.sa_sigaction = _missingno},
|
||||
* NULL);
|
||||
* setitimer(ITIMER_REAL,
|
||||
* &(const struct itimerval){{1, 500000},
|
||||
* {1, 500000}},
|
||||
* NULL);
|
||||
*
|
||||
* Set single-shot 50ms timer callback to interrupt laggy connect():
|
||||
*
|
||||
* CHECK_NE(-1, sigaction(SIGALRM,
|
||||
* &(struct sigaction){.sa_sigaction = _missingno,
|
||||
* .sa_flags = SA_RESETHAND},
|
||||
* NULL));
|
||||
* CHECK_NE(-1, setitimer(ITIMER_REAL,
|
||||
* &(const struct itimerval){{0, 0}, {0, 50000}},
|
||||
* NULL));
|
||||
* sigaction(SIGALRM,
|
||||
* &(struct sigaction){.sa_sigaction = _missingno,
|
||||
* .sa_flags = SA_RESETHAND},
|
||||
* NULL);
|
||||
* setitimer(ITIMER_REAL,
|
||||
* &(const struct itimerval){{0, 0}, {0, 50000}},
|
||||
* NULL);
|
||||
* if (connect(...) == -1 && errno == EINTR) { ... }
|
||||
*
|
||||
* Disarm timer:
|
||||
*
|
||||
* CHECK_NE(-1, setitimer(ITIMER_REAL, &(const struct itimerval){0}, NULL));
|
||||
* setitimer(ITIMER_REAL, &(const struct itimerval){0}, NULL);
|
||||
*
|
||||
* Be sure to check for EINTR on your i/o calls, for best low latency.
|
||||
*
|
||||
@@ -81,6 +81,7 @@ int setitimer(int which, const struct itimerval *newvalue,
|
||||
rc = sys_setitimer_nt(which, newvalue, oldvalue);
|
||||
}
|
||||
|
||||
#ifdef SYSDEBUG
|
||||
if (newvalue && oldvalue) {
|
||||
STRACE("setitimer(%d, "
|
||||
"{{%'ld, %'ld}, {%'ld, %'ld}}, "
|
||||
@@ -100,6 +101,7 @@ int setitimer(int which, const struct itimerval *newvalue,
|
||||
} else {
|
||||
STRACE("setitimer(%d, NULL, NULL) → %d% m", which, rc);
|
||||
}
|
||||
#endif
|
||||
|
||||
return rc;
|
||||
}
|
||||
@@ -18,11 +18,11 @@
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/assert.h"
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/struct/rlimit.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/asan.internal.h"
|
||||
#include "libc/intrin/describeflags.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/sysv/consts/rlimit.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
@@ -43,6 +43,8 @@
|
||||
* - `RLIMIT_FSIZE` causes `SIGXFSZ` to sent to the process when the
|
||||
* soft limit on file size is exceeded and the process is destroyed
|
||||
* when the hard limit is exceeded. It works everywhere but Windows
|
||||
* and it also causes `EFBIG` to be returned by i/o functions after
|
||||
* the `SIGXFSZ` signal is delivered or ignored
|
||||
*
|
||||
* - `RLIMIT_NPROC` limits the number of simultaneous processes and it
|
||||
* should work on all platforms except Windows. Please be advised it
|
||||
|
||||
@@ -48,10 +48,9 @@
|
||||
* @vforksafe
|
||||
*/
|
||||
int sigprocmask(int how, const sigset_t *opt_set, sigset_t *opt_out_oldset) {
|
||||
sigset_t old;
|
||||
int res, rc, arg1;
|
||||
sigset_t old = {0};
|
||||
const sigset_t *arg2;
|
||||
sigemptyset(&old);
|
||||
if (IsAsan() &&
|
||||
((opt_set && !__asan_is_valid(opt_set, sizeof(*opt_set))) ||
|
||||
(opt_out_oldset &&
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
#include "libc/sysv/errfuns.h"
|
||||
|
||||
/**
|
||||
* Blocks until SIG ∉ MASK is delivered to process.
|
||||
* Blocks until SIG ∉ MASK is delivered to thread.
|
||||
*
|
||||
* This temporarily replaces the signal mask until a signal that it
|
||||
* doesn't contain is delivered.
|
||||
@@ -46,7 +46,7 @@
|
||||
int sigsuspend(const sigset_t *ignore) {
|
||||
int rc;
|
||||
long ms, totoms;
|
||||
sigset_t save, mask, *arg;
|
||||
sigset_t save, *arg, mask = {0};
|
||||
STRACE("sigsuspend(%s) → ...", DescribeSigset(0, ignore));
|
||||
if (IsAsan() && ignore && !__asan_is_valid(ignore, sizeof(*ignore))) {
|
||||
rc = efault();
|
||||
@@ -63,7 +63,6 @@ int sigsuspend(const sigset_t *ignore) {
|
||||
if (ignore) {
|
||||
arg = ignore;
|
||||
} else {
|
||||
sigemptyset(&mask);
|
||||
arg = &mask;
|
||||
}
|
||||
if (!IsWindows()) {
|
||||
|
||||
+3
-6
@@ -17,8 +17,8 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/errno.h"
|
||||
#include "libc/limits.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
#include "libc/time/time.h"
|
||||
|
||||
/**
|
||||
@@ -28,17 +28,14 @@
|
||||
* was delivered, in which case the errno condition is ignored, and
|
||||
* this function shall return the number of unslept seconds rounded
|
||||
* using the ceiling function
|
||||
* @see nanosleep(), usleep()
|
||||
* @see clock_nanosleep()
|
||||
* @asyncsignalsafe
|
||||
* @norestart
|
||||
*/
|
||||
unsigned sleep(unsigned seconds) {
|
||||
int err;
|
||||
unsigned unslept;
|
||||
struct timespec tv = {seconds};
|
||||
err = errno;
|
||||
nanosleep(&tv, &tv);
|
||||
errno = err;
|
||||
if (!clock_nanosleep(CLOCK_REALTIME, 0, &tv, &tv)) return 0;
|
||||
unslept = tv.tv_sec;
|
||||
if (tv.tv_nsec && unslept < UINT_MAX) {
|
||||
++unslept;
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/internal.h"
|
||||
#include "libc/calls/syscall-sysv.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/errno.h"
|
||||
@@ -64,6 +65,7 @@ static void splice_init(void) {
|
||||
* used as both an input and output parameter for pwrite() behavior
|
||||
* @return number of bytes transferred, 0 on input end, or -1 w/ errno
|
||||
* @raise EBADF if `infd` or `outfd` aren't open files or append-only
|
||||
* @raise ENOTSUP if `infd` or `outfd` is a zip file descriptor
|
||||
* @raise ESPIPE if an offset arg was specified for a pipe fd
|
||||
* @raise EINVAL if offset was given for non-seekable device
|
||||
* @raise EINVAL if file system doesn't support splice()
|
||||
@@ -85,6 +87,8 @@ ssize_t splice(int infd, int64_t *opt_in_out_inoffset, int outfd,
|
||||
(opt_in_out_outoffset &&
|
||||
!__asan_is_valid(opt_in_out_outoffset, 8)))) {
|
||||
rc = efault();
|
||||
} else if (__isfdkind(infd, kFdZip) || __isfdkind(outfd, kFdZip)) {
|
||||
rc = enotsup();
|
||||
} else {
|
||||
rc = sys_splice(infd, opt_in_out_inoffset, outfd, opt_in_out_outoffset,
|
||||
uptobytes, flags);
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
#if !(__ASSEMBLER__ + __LINKER__ + 0)
|
||||
COSMOPOLITAN_C_START_
|
||||
|
||||
#define _timespec_zero ((struct timespec){0})
|
||||
#define _timespec_max ((struct timespec){0x7fffffffffffffff, 999999999})
|
||||
|
||||
struct timespec {
|
||||
int64_t tv_sec;
|
||||
int64_t tv_nsec; /* nanoseconds */
|
||||
@@ -10,6 +13,7 @@ struct timespec {
|
||||
|
||||
int clock_getres(int, struct timespec *);
|
||||
int clock_gettime(int, struct timespec *);
|
||||
int clock_nanosleep(int, int, const struct timespec *, struct timespec *);
|
||||
int futimens(int, const struct timespec[2]);
|
||||
int nanosleep(const struct timespec *, struct timespec *);
|
||||
int sys_futex(int *, int, int, const struct timespec *, int *);
|
||||
@@ -19,6 +23,7 @@ int timespec_getres(struct timespec *, int);
|
||||
|
||||
int _timespec_cmp(struct timespec, struct timespec) pureconst;
|
||||
bool _timespec_eq(struct timespec, struct timespec) pureconst;
|
||||
bool _timespec_gt(struct timespec, struct timespec) pureconst;
|
||||
bool _timespec_gte(struct timespec, struct timespec) pureconst;
|
||||
int64_t _timespec_tomicros(struct timespec) pureconst;
|
||||
int64_t _timespec_tomillis(struct timespec) pureconst;
|
||||
@@ -27,8 +32,10 @@ struct timespec _timespec_add(struct timespec, struct timespec) pureconst;
|
||||
struct timespec _timespec_fromnanos(int64_t) pureconst;
|
||||
struct timespec _timespec_frommicros(int64_t) pureconst;
|
||||
struct timespec _timespec_frommillis(int64_t) pureconst;
|
||||
struct timespec _timespec_mono(void);
|
||||
struct timespec _timespec_real(void);
|
||||
struct timespec _timespec_mono(void);
|
||||
struct timespec _timespec_sleep(struct timespec);
|
||||
int _timespec_sleep_until(struct timespec);
|
||||
struct timespec _timespec_sub(struct timespec, struct timespec) pureconst;
|
||||
|
||||
COSMOPOLITAN_C_END_
|
||||
|
||||
@@ -4,12 +4,18 @@
|
||||
#include "libc/mem/alloca.h"
|
||||
#if !(__ASSEMBLER__ + __LINKER__ + 0)
|
||||
COSMOPOLITAN_C_START_
|
||||
/* clang-format off */
|
||||
|
||||
int __sys_utimensat(int, const char *, const struct timespec[2], int) hidden;
|
||||
int __utimens(int, const char *, const struct timespec[2], int) hidden;
|
||||
int sys_clock_getres(int, struct timespec *) hidden;
|
||||
int sys_clock_gettime(int, struct timespec *) hidden;
|
||||
int sys_clock_gettime_nt(int, struct timespec *) hidden;
|
||||
int sys_clock_gettime_xnu(int, struct timespec *) hidden;
|
||||
int sys_clock_nanosleep(int, int, const struct timespec *, struct timespec *) hidden;
|
||||
int sys_clock_nanosleep_nt(int, int, const struct timespec *, struct timespec *) hidden;
|
||||
int sys_clock_nanosleep_xnu(int, int, const struct timespec *, struct timespec *) hidden;
|
||||
int sys_clock_nanosleep_openbsd(int, int, const struct timespec *, struct timespec *) hidden;
|
||||
int sys_futimens(int, const struct timespec[2]) hidden;
|
||||
int sys_nanosleep(const struct timespec *, struct timespec *) hidden;
|
||||
int sys_nanosleep_nt(const struct timespec *, struct timespec *) hidden;
|
||||
|
||||
@@ -16,9 +16,14 @@ int gettimeofday(struct timeval *, struct timezone *);
|
||||
int lutimes(const char *, const struct timeval[2]);
|
||||
int utimes(const char *, const struct timeval[2]);
|
||||
|
||||
struct timeval _timeval_add(struct timeval, struct timeval);
|
||||
struct timeval _timespec_totimeval(struct timespec);
|
||||
struct timespec _timeval_totimespec(struct timeval);
|
||||
int _timeval_cmp(struct timeval, struct timeval) pureconst;
|
||||
bool _timeval_eq(struct timeval, struct timeval) pureconst;
|
||||
bool _timeval_gt(struct timeval, struct timeval) pureconst;
|
||||
bool _timeval_gte(struct timeval, struct timeval) pureconst;
|
||||
struct timeval _timeval_add(struct timeval, struct timeval) pureconst;
|
||||
struct timeval _timeval_sub(struct timeval, struct timeval) pureconst;
|
||||
struct timeval _timespec_totimeval(struct timespec) pureconst;
|
||||
struct timespec _timeval_totimespec(struct timeval) pureconst;
|
||||
|
||||
COSMOPOLITAN_C_END_
|
||||
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
|
||||
|
||||
+2
-1
@@ -17,10 +17,10 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/syscall-sysv.internal.h"
|
||||
#include "libc/calls/syscall_support-nt.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/nt/enum/threadaccess.h"
|
||||
#include "libc/nt/runtime.h"
|
||||
#include "libc/nt/thread.h"
|
||||
@@ -48,6 +48,7 @@ static textwindows int sys_tkill_nt(int tid, int sig) {
|
||||
* @param tid is thread id
|
||||
* @param sig does nothing on xnu
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @asyncsignalsafe
|
||||
*/
|
||||
int tkill(int tid, int sig) {
|
||||
int rc;
|
||||
|
||||
@@ -27,7 +27,6 @@
|
||||
|
||||
textwindows int sys_truncate_nt(const char *path, uint64_t length) {
|
||||
int rc;
|
||||
bool32 ok;
|
||||
int64_t fh;
|
||||
uint16_t path16[PATH_MAX];
|
||||
if (__mkntpath(path, path16) == -1) return -1;
|
||||
|
||||
+47
-7
@@ -17,25 +17,65 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/calls/syscall-nt.internal.h"
|
||||
#include "libc/calls/syscall-sysv.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/errno.h"
|
||||
#include "libc/intrin/asan.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/intrin/weaken.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
#include "libc/zipos/zipos.internal.h"
|
||||
|
||||
/**
|
||||
* Reduces or extends underlying physical medium of file.
|
||||
* Changes size of file.
|
||||
*
|
||||
* If file was originally larger, content >length is lost.
|
||||
* If the file size is increased, the extended area shall appear as if
|
||||
* it were zero-filled. If your file size is decreased, the extra data
|
||||
* shall be lost.
|
||||
*
|
||||
* @param path must exist
|
||||
* @return 0 on success or -1 w/ errno
|
||||
* Some operating systems implement an optimization, where `length` is
|
||||
* treated as a logical size and the requested physical space won't be
|
||||
* allocated until non-zero values get written into it. Our tests show
|
||||
* this happens on Linux (usually with 4096 byte granularity), FreeBSD
|
||||
* (which favors 512-byte granularity), and MacOS (prefers 4096 bytes)
|
||||
* however Windows, OpenBSD, and NetBSD always reserve physical space.
|
||||
* This may be inspected using stat() then consulting stat::st_blocks.
|
||||
*
|
||||
* @param path is name of file that shall be resized
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @raise EINVAL if `length` is negative
|
||||
* @raise EINTR if signal was delivered instead
|
||||
* @raise EFBIG or EINVAL if `length` is too huge
|
||||
* @raise EFAULT if `path` points to invalid memory
|
||||
* @raise ENOTSUP if `path` is a zip filesystem path
|
||||
* @raise EACCES if we don't have permission to search a component of `path`
|
||||
* @raise ENOTDIR if a directory component in `path` exists as non-directory
|
||||
* @raise ENAMETOOLONG if symlink-resolved `path` length exceeds `PATH_MAX`
|
||||
* @raise ENAMETOOLONG if component in `path` exists longer than `NAME_MAX`
|
||||
* @raise ELOOP if a loop was detected resolving components of `path`
|
||||
* @raise ENOENT if `path` doesn't exist or is an empty string
|
||||
* @raise ETXTBSY if `path` is an executable being executed
|
||||
* @raise EROFS if `path` is on a read-only filesystem
|
||||
* @raise ENOSYS on bare metal
|
||||
* @see ftruncate()
|
||||
* @error ENOENT
|
||||
* @threadsafe
|
||||
*/
|
||||
int truncate(const char *path, uint64_t length) {
|
||||
int rc;
|
||||
if (!IsWindows()) {
|
||||
struct ZiposUri zipname;
|
||||
if (IsMetal()) {
|
||||
rc = enosys();
|
||||
} else if (!path || (IsAsan() && !__asan_is_valid(path, 1))) {
|
||||
rc = efault();
|
||||
} else if (_weaken(__zipos_parseuri) &&
|
||||
_weaken(__zipos_parseuri)(path, &zipname) != -1) {
|
||||
rc = enotsup();
|
||||
} else if (!IsWindows()) {
|
||||
rc = sys_truncate(path, length, length);
|
||||
if (IsNetbsd() && rc == -1 && errno == ENOSPC) {
|
||||
errno = EFBIG; // POSIX doesn't specify ENOSPC for truncate()
|
||||
}
|
||||
} else {
|
||||
rc = sys_truncate_nt(path, length);
|
||||
}
|
||||
|
||||
+6
-6
@@ -17,6 +17,8 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/struct/timespec.h"
|
||||
#include "libc/sysv/consts/clock.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
#include "libc/time/time.h"
|
||||
|
||||
/**
|
||||
@@ -24,13 +26,11 @@
|
||||
*
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @raise EINTR if a signal was delivered while sleeping
|
||||
* @see nanosleep(), sleep()
|
||||
* @see clock_nanosleep()
|
||||
* @norestart
|
||||
*/
|
||||
int usleep(uint32_t micros) {
|
||||
struct timespec ts = {
|
||||
micros / 1000000,
|
||||
micros % 1000000 * 1000,
|
||||
};
|
||||
return nanosleep(&ts, 0);
|
||||
struct timespec ts = _timespec_frommicros(micros);
|
||||
if (clock_nanosleep(CLOCK_REALTIME, 0, &ts, 0)) return eintr();
|
||||
return 0;
|
||||
}
|
||||
+3
-3
@@ -17,16 +17,16 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
#include "libc/str/str.h"
|
||||
#include "libc/sysv/consts/at.h"
|
||||
#include "libc/time/struct/utimbuf.h"
|
||||
|
||||
/**
|
||||
* Changes last accessed/modified times on file.
|
||||
*
|
||||
* @param times if NULL means now
|
||||
* @return 0 on success or -1 w/ errno
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @see utimensat() for modern version
|
||||
* @asyncsignalsafe
|
||||
* @threadsafe
|
||||
*/
|
||||
int utime(const char *path, const struct utimbuf *times) {
|
||||
struct timeval tv[2];
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/*-*- 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 2020 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. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/assert.h"
|
||||
#include "libc/calls/asan.internal.h"
|
||||
#include "libc/calls/calls.h"
|
||||
#include "libc/calls/internal.h"
|
||||
#include "libc/calls/struct/timespec.internal.h"
|
||||
#include "libc/calls/struct/timeval.internal.h"
|
||||
#include "libc/calls/syscall_support-sysv.internal.h"
|
||||
#include "libc/dce.h"
|
||||
#include "libc/intrin/asan.internal.h"
|
||||
#include "libc/intrin/describeflags.internal.h"
|
||||
#include "libc/intrin/strace.internal.h"
|
||||
#include "libc/intrin/weaken.h"
|
||||
#include "libc/sysv/consts/at.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
#include "libc/zipos/zipos.internal.h"
|
||||
|
||||
int __utimens(int fd, const char *path, const struct timespec ts[2],
|
||||
int flags) {
|
||||
int rc;
|
||||
struct ZiposUri zipname;
|
||||
if (IsMetal()) {
|
||||
rc = enosys();
|
||||
} else if (IsAsan() && ((fd == AT_FDCWD && !__asan_is_valid(path, 1)) ||
|
||||
(ts && (!__asan_is_valid_timespec(ts + 0) ||
|
||||
!__asan_is_valid_timespec(ts + 1))))) {
|
||||
rc = efault(); // bad memory
|
||||
} else if ((flags & ~AT_SYMLINK_NOFOLLOW)) {
|
||||
rc = einval(); // unsupported flag
|
||||
} else if (__isfdkind(fd, kFdZip) ||
|
||||
(path && (_weaken(__zipos_parseuri) &&
|
||||
_weaken(__zipos_parseuri)(path, &zipname) != -1))) {
|
||||
rc = enotsup();
|
||||
} else if (IsLinux() && !__is_linux_2_6_23() && fd == AT_FDCWD && !flags) {
|
||||
rc = sys_utimes(path, (void *)ts); // rhel5 truncates to seconds
|
||||
} else if (!IsWindows()) {
|
||||
rc = sys_utimensat(fd, path, ts, flags);
|
||||
} else {
|
||||
rc = sys_utimensat_nt(fd, path, ts, flags);
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
@@ -39,8 +39,8 @@ int sys_utimensat(int dirfd, const char *path, const struct timespec ts[2],
|
||||
if (rc == -1 && errno == ENOSYS && path) {
|
||||
errno = olderr;
|
||||
if (ts) {
|
||||
tv[0] = _timespec2timeval(ts[0]);
|
||||
tv[1] = _timespec2timeval(ts[1]);
|
||||
tv[0] = _timespec_totimeval(ts[0]);
|
||||
tv[1] = _timespec_totimeval(ts[1]);
|
||||
rc = sys_utimes(path, tv);
|
||||
} else {
|
||||
rc = sys_utimes(path, NULL);
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/calls/struct/stat.h"
|
||||
#include "libc/calls/struct/timeval.h"
|
||||
#include "libc/calls/struct/timeval.internal.h"
|
||||
#include "libc/fmt/conv.h"
|
||||
#include "libc/nexgen32e/nexgen32e.h"
|
||||
@@ -41,16 +42,16 @@ int sys_utimensat_xnu(int dirfd, const char *path, const struct timespec ts[2],
|
||||
if (ts[0].tv_nsec == UTIME_NOW) {
|
||||
tv[0] = now;
|
||||
} else if (ts[0].tv_nsec == UTIME_OMIT) {
|
||||
tv[0] = _timespec2timeval(st.st_atim);
|
||||
tv[0] = _timespec_totimeval(st.st_atim);
|
||||
} else {
|
||||
tv[0] = _timespec2timeval(ts[0]);
|
||||
tv[0] = _timespec_totimeval(ts[0]);
|
||||
}
|
||||
if (ts[1].tv_nsec == UTIME_NOW) {
|
||||
tv[1] = now;
|
||||
} else if (ts[1].tv_nsec == UTIME_OMIT) {
|
||||
tv[1] = _timespec2timeval(st.st_mtim);
|
||||
tv[1] = _timespec_totimeval(st.st_mtim);
|
||||
} else {
|
||||
tv[1] = _timespec2timeval(ts[1]);
|
||||
tv[1] = _timespec_totimeval(ts[1]);
|
||||
}
|
||||
} else {
|
||||
tv[0] = now;
|
||||
|
||||
+33
-39
@@ -30,54 +30,48 @@
|
||||
#include "libc/zipos/zipos.internal.h"
|
||||
|
||||
/**
|
||||
* Sets atime/mtime on file, the modern way.
|
||||
* Sets access/modified time on file, the modern way.
|
||||
*
|
||||
* This is two functions in one. If `path` is null then this function
|
||||
* becomes the same as `futimens(dirfd, ts)`.
|
||||
* XNU only has microsecond (1e-6) accuracy and there's no
|
||||
* `dirfd`-relative support. Windows only has hectonanosecond (1e-7)
|
||||
* accuracy. RHEL5 doesn't support `dirfd` or `flags` and will truncate
|
||||
* timestamps to seconds.
|
||||
*
|
||||
* XNU and RHEL5 only have microsecond accuracy and there's no `dirfd`
|
||||
* relative support.
|
||||
* If you'd rather specify an open file descriptor rather than its
|
||||
* filesystem path, then consider using futimens().
|
||||
*
|
||||
* @param dirfd should AT_FDCWD
|
||||
* @param ts is atime/mtime, or null for current time
|
||||
* @param flags can have AT_SYMLINK_NOFOLLOW
|
||||
* @raise ENOSYS on RHEL5 if path is NULL
|
||||
* @raise EINVAL if flags had unrecognized bits
|
||||
* @raise EINVAL if path is NULL and flags has AT_SYMLINK_NOFOLLOW
|
||||
* @raise EBADF if dirfd isn't a valid fd or AT_FDCWD
|
||||
* @raise EFAULT if path or ts memory was invalid
|
||||
* @raise EROFS if file system is read-only
|
||||
* @raise ENAMETOOLONG
|
||||
* @raise EPERM
|
||||
* @see futimens()
|
||||
* @param dirfd can be `AT_FDCWD` or an open directory
|
||||
* @param path is filename whose timestamps should be modified
|
||||
* @param ts is {access, modified} timestamps, or null for current time
|
||||
* @param flags can have `AT_SYMLINK_NOFOLLOW` when `path` is specified
|
||||
* @return 0 on success, or -1 w/ errno
|
||||
* @raise EINVAL if `flags` had an unrecognized value
|
||||
* @raise EPERM if pledge() is in play without `fattr` promise
|
||||
* @raise EACCES if unveil() is in play and `path` isn't unveiled
|
||||
* @raise ENOTSUP if `path` is a zip filesystem path or `dirfd` is zip
|
||||
* @raise EINVAL if `ts` specifies a nanosecond value that's out of range
|
||||
* @raise ENAMETOOLONG if symlink-resolved `path` length exceeds `PATH_MAX`
|
||||
* @raise ENAMETOOLONG if component in `path` exists longer than `NAME_MAX`
|
||||
* @raise EBADF if `dirfd` isn't a valid fd or `AT_FDCWD`
|
||||
* @raise EFAULT if `path` or `ts` memory was invalid
|
||||
* @raise EROFS if `path` is on read-only filesystem
|
||||
* @raise ENOSYS on bare metal or on rhel5 when `dirfd` or `flags` is used
|
||||
* @asyncsignalsafe
|
||||
* @threadsafe
|
||||
*/
|
||||
int utimensat(int dirfd, const char *path, const struct timespec ts[2],
|
||||
int flags) {
|
||||
int rc;
|
||||
if (IsAsan() && ((dirfd == AT_FDCWD && !__asan_is_valid(path, 1)) ||
|
||||
(ts && (!__asan_is_valid_timespec(ts + 0) ||
|
||||
!__asan_is_valid_timespec(ts + 1))))) {
|
||||
rc = efault(); // bad memory
|
||||
} else if ((flags & ~AT_SYMLINK_NOFOLLOW)) {
|
||||
rc = einval(); // unsupported flag
|
||||
} else if (!path && flags) {
|
||||
rc = einval(); // futimens() doesn't take flags
|
||||
} else if ((path || __isfdkind(dirfd, kFdZip)) && _weaken(__zipos_notat) &&
|
||||
(rc = __zipos_notat(dirfd, path)) == -1) {
|
||||
STRACE("zipos utimensat not supported yet");
|
||||
} else if (!IsWindows()) {
|
||||
rc = sys_utimensat(dirfd, path, ts, flags);
|
||||
|
||||
if (!path) {
|
||||
rc = efault(); // linux kernel abi behavior isn't supported
|
||||
} else {
|
||||
rc = sys_utimensat_nt(dirfd, path, ts, flags);
|
||||
}
|
||||
if (ts) {
|
||||
STRACE("utimensat(%s, %#s, {{%,ld, %,ld}, {%,ld, %,ld}}, %#b) → %d% m",
|
||||
DescribeDirfd(dirfd), path, ts[0].tv_sec, ts[0].tv_nsec,
|
||||
ts[1].tv_sec, ts[1].tv_nsec, flags, rc);
|
||||
} else {
|
||||
STRACE("utimensat(%s, %#s, 0, %#b) → %d% m", DescribeDirfd(dirfd), path,
|
||||
flags, rc);
|
||||
rc = __utimens(dirfd, path, ts, flags);
|
||||
}
|
||||
|
||||
STRACE("utimensat(%s, %#s, {%s, %s}, %#o) → %d% m", DescribeDirfd(dirfd),
|
||||
path, DescribeTimespec(0, ts), DescribeTimespec(0, ts ? ts + 1 : 0),
|
||||
flags, rc);
|
||||
|
||||
return rc;
|
||||
}
|
||||
Loaded 100 of 360 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user