Compare commits

..
17 Commits
Author SHA1 Message Date
Joshua Wierenga fea68b142e Fully support old windows 8ib user space virtual memory
Addresses are converted in blocks(asan, automap, stack, ...), with the start and end addresses modified using (address & 0xffffff) | ((address >> 28) << 24).

Following addresses are only specified to frame accuracy with the last 4 hex digits chopped off.
null, loader, image and arena blocks have not been modified.
asan     [0x00007fff, 0x10007fff] ⇒ [0x00007fff, 0x01007fff] Not currently supported.
automap  [0x10008004, 0x1fe7fffb] ⇒ [0x01008004, 0x01e7fffb]
_mmi     [0x1fe7fffc, 0x1ffffffb] ⇒ [0x01e7fffc, 0x01fffffb] Listed as memtrack outside of the memtrack files.
fixedmap [0x30000004, 0x40000003] ⇒ [0x03000004, 0x04000003]
nsync    [0x6fc00004, 0x6fcffffb] ⇒ [0x06c00004, 0x06cffffb]
zipos    [0x6fd00004, 0x6fdffffb] ⇒ [0x06d00004, 0x06dffffb] I don't think this is used currently on the vista branch.
g_fds    [0x6fe00004, 0x6feffffb] ⇒ [0x06e00004, 0x06effffb]
winargs  [0x6ffffffe, 0x6fffffff] ⇒ [0x06fffffe, 0x06ffffff] Not entirely confident on if this is accurate.
stack    [0x70000000, 0x70000003] ⇒ [0x07000000, 0x07000003] Not entirely confident on if this is accurate.

This map is documented in memtrack64-8tib.txt with the original 128tib version renamed to memtrack64-128tib.txt.

Modified windows 8.1 check macro name to match existing windows 10 one.
Modified IsShadowFrame to correctly identify the asan block on old windows. Required as the asan block on 128tib virtual memory systems is larger than 2^43 - 1 and so all blocks were reporting as asan.
2023-03-20 21:07:01 -04:00
Joshua Wierenga 8f001857de Fix build breaks
Revert the changes that 827f25f made to libc/calls/readv-metal.c regarding internal functions having underlines due to 6f7d0cb being missing at the time.
Use the versions of libc/intrin/lockfileex.c and libc/intrin/unlockfileex.c from 3f49889 to account for strace changes.
Revert d86916e and use the versions of libc/calls/getgroups.c, libc/calls/setgroups.c, libc/runtime/getlogin.c and libc/runtime/getlogin_r.c from 4c40c50 to again account for strace changes.
Fix include statements and internal underlined function calls in libc/stdio/cocmd.c, libc/testlib/extract.c and test/libc/stdio/system_test.c.
Fix missing closing paren in nsync memory size macro in memtrack.internal.h.
2023-03-20 21:07:01 -04:00
Justine Tunney 7b26b42769 Pay off more technical debt
This makes breaking changes to add underscores to many non-standard
function names provided by the c library. MODE=tiny is now tinier and
we now use smaller locks that are better for tiny apps in this mode.
Some headers have been renamed to be in the same folder as the build
package, so it'll be easier to know which build dependency is needed.
Certain old misguided interfaces have been removed. Intel intrinsics
headers are now listed in libc/isystem (but not in the amalgamation)
to help further improve open source compatibility. Header complexity
has also been reduced. Lastly, more shell scripts are now available.

Compared to 6f7d0cb1c3, some tiny corrections were made in libc/intrin/g_fds.c and libc/zipos/open.c including double semi colons and incorrect indentation for existing vista changes that were manually pulled from this commit previously.
2023-03-20 21:07:01 -04:00
Justine Tunney 555260d2e5 Optimize memory layout
Compared to b69f3d2488, old windows specific fd, zipos and nsync memory ranges in libc/runtime/memtrack.internal.h were kept.
2023-03-20 21:07:01 -04:00
Gavin HayesandHugues Morisset 0740e68ea0 Add imaxdiv, wcscoll, getdtablesize (#639) (#721)
Co-authored-by: Hugues Morisset <[email protected]>
2023-01-29 19:33:00 -08:00
Gavin HayesandJustine Tunney 9c5a7795ad vista: backport execve escaping and using cocmd as shell for system, etc. (#660)
* Introduce testlib_extract() helper

* Have execve() escape double quotes in cmd.exe's preferred style

This makes it possible for us to use system() and popen() with paths
that redirect to filenames that contain spaces, e.g.

    system("echo.com hello >\"hello there.txt\"")

It's difficult to solve this problem, because WIN32 only allows passing
one single argument when launching programs and each program is allowed
to tokenize that however it wants. Most software follows the convention
of cmd.exe which is poorly documented and positively byzantine.

In the future we're going to solve this by not using cmd.exe at all and
instead embedding the cocmd.com interpreter into the system() function.
In the meantime, our documentation has been updated to help recalibrate
any expectation the user might hold regarding the security of using the
Windows command interpreter.

Fixes #644

* Introduce double quote support in cocmd.com shell

* Add some tests for execve()

* Embed cocmd.com interpreter for system() / open()

This change lets you use system() in an easier and portable way. The
problem with the call in the past has always been that bourne and
cmd.com on Windows have less than nothing in common, so pretty much the
only command system() could be used for across platforms was maybe echo.
cmd.exe is also a security liability due to its escaping rules.

Since cocmd.com implements 85% of what we need from bourne, in a really
tiny way, it makes perfect sense to be embedded in these functionss. We
get a huge performance boost too.

Fixes #644

* Support whitespace after cocmd output redirection

Co-authored-by: Justine Tunney <[email protected]>
2022-10-11 21:17:50 -07:00
Gavin Hayes f4ff1729d1 Backport main branch improvements (#658)
* Add sys_ prefix to unwrapped system calls
* This change also implements getlogin() and getlogin_r().
* Add getgroups and setgroups (#619)
* Fix getgroups / setgroups tests across platforms. See #619
* Change accept type to struct sockaddr * (#630)
* vista: use old strace path
2022-10-10 20:44:29 -07:00
Joshua Wierenga 4381b3d925 Get cosmopolitation working on Vista again (#635)
* Fixes virtual memory support for Windows Vista/7/8

Fixes file desciptor and zipos virtual memory sizes given that old versions of windows limit their user virtual memory space to 8tb.
Includes some changes from b69f3d2488 and 6f7d0cb1c3 in preparation for potentially using them on old windows and because it avoids duplicating addresses everywhere.

* Optimise windows version checking

Added GetNtMinorVersion() and IsAtleastWindows8p1() macros which get nt version info from the peb.

* Planned nsync memory region for old windows

Added nsync regon start and size macros that can switch to smaller values on old windows, just like previous fds and zipos change.
2022-10-04 01:20:39 -07:00
Justine Tunney 30140812f0 Add README description for new vista branch 2022-09-15 12:51:24 -07:00
Justine Tunney c64e7eaf7c Fix F_DUPFD_CLOEXEC on some systems 2022-09-15 12:48:26 -07:00
Justine Tunney a5fa90a21f Fix POSIX advisory locks on Windows 2022-09-15 12:44:00 -07:00
Justine Tunney 050062bcbb Fix preadv() and pwritev() 2022-09-15 12:30:36 -07:00
Justine Tunney 827f25f054 Fix bug with sendfile() on XNU 2022-09-15 12:27:30 -07:00
Justine Tunney 790c661317 Fix the build 2022-09-15 12:02:44 -07:00
tkchiaandtkchia c4eb701d56 Bare metal VGA: implement "status report" escape codes (#613)
* Bare metal VGA: implement "status report" escape codes
* Minor fix to pseudoteletypewriter code

Co-authored-by: tkchia <[email protected]>
2022-09-15 12:02:35 -07:00
tkchiaandtkchia 116bda997e [WIP] Get bare metal working outside of an emulator (#609)
You can now run bare metal on bare metal!

* Fix handling of int 0x15 eax = 0xe820 memory map
* Fix some issues in initial page table creation
* hello4.com now works outside emulators
* Ensure area for identity page tables are zeroed first
* Simplify logic for creating page table entries, this partly
  reverts 577c0f6226
* Add degenerate MBR partition entry, to ease testing

Co-authored-by: tkchia <[email protected]>
2022-09-15 12:02:28 -07:00
Justine Tunney c03359c637 Add Vista branch to GitHub workflows 2022-09-15 12:01:16 -07:00
1246 changed files with 16110 additions and 42468 deletions

No files matched your search

+4 -5
View File
@@ -4,10 +4,12 @@ on:
push:
branches:
- "master"
- "vista"
- "flake"
pull_request:
branches:
- "master"
- "vista"
# run workflow manually from the Actions tab
workflow_dispatch:
@@ -21,11 +23,8 @@ jobs:
steps:
- uses: actions/checkout@v3
- 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: support ape bins
run: sudo sh -c "echo ':APE:M::MZqFpD::/bin/sh:' >/proc/sys/fs/binfmt_misc/register"
- name: make matrix
run: V=0 make -j2 MODE=${{ matrix.mode }}
+83 -106
View File
@@ -61,19 +61,13 @@
SHELL = build/bootstrap/cocmd.com
HOSTS ?= freebsd openbsd netbsd rhel7 rhel5 win10 xnu
MAKEFLAGS += -j --no-builtin-rules
MAKEFLAGS += --no-builtin-rules
.SUFFIXES:
.DELETE_ON_ERROR:
.FEATURES: output-sync
.PHONY: all o bins check test depend tags
ifneq ($(m),)
ifeq ($(MODE),)
MODE := $(m)
endif
endif
all: o
o: o/$(MODE)
@@ -94,7 +88,7 @@ o/$(MODE): \
libc/disclaimer.inc \
rx:build/bootstrap \
rx:o/third_party/gcc \
/proc/stat \
/proc/self/status \
rw:/dev/null \
w:o/stack.log \
/etc/hosts \
@@ -121,7 +115,6 @@ include third_party/compiler_rt/compiler_rt.mk # │
include libc/str/str.mk # │
include third_party/xed/xed.mk # │
include third_party/zlib/zlib.mk # │
include third_party/double-conversion/dc.mk # │
include libc/elf/elf.mk # │
include ape/ape.mk # │
include libc/fmt/fmt.mk # │
@@ -135,7 +128,6 @@ include libc/mem/mem.mk #─┐
include libc/zipos/zipos.mk # ├──DYNAMIC RUNTIME
include third_party/gdtoa/gdtoa.mk # │ You can now use stdio
include libc/time/time.mk # │ You can finally call malloc()
include third_party/nsync/mem/mem.mk # │
include libc/thread/thread.mk # │
include libc/stdio/stdio.mk # │
include third_party/libcxx/libcxx.mk # │
@@ -161,7 +153,6 @@ 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
@@ -169,7 +160,7 @@ include test/tool/args/test.mk
include third_party/linenoise/linenoise.mk
include third_party/maxmind/maxmind.mk
include net/finger/finger.mk
include third_party/double-conversion/test/test.mk
include third_party/double-conversion/double-conversion.mk
include third_party/lua/lua.mk
include third_party/sed/sed.mk
include third_party/awk/awk.mk
@@ -204,7 +195,6 @@ 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
@@ -275,102 +265,98 @@ o/$(MODE)/srcs-old.txt: o/$(MODE)/.x $(MAKEFILES) $(call uniq,$(foreach x,$(SRCS
o/$(MODE)/hdrs-old.txt: o/$(MODE)/.x $(MAKEFILES) $(call uniq,$(foreach x,$(HDRS) $(INCS),$(dir $(x))))
$(file >$@) $(foreach x,$(HDRS) $(INCS),$(file >>$@,$(x)))
TAGS: private .UNSANDBOXED = 1
TAGS: .UNSANDBOXED = 1
TAGS: o/$(MODE)/srcs-old.txt $(SRCS)
@$(RM) $@
@$(TAGS) $(TAGSFLAGS) -L $< -o $@
HTAGS: private .UNSANDBOXED = 1
HTAGS: .UNSANDBOXED = 1
HTAGS: o/$(MODE)/hdrs-old.txt $(HDRS)
@$(RM) $@
@build/htags -L $< -o $@
loc: private .UNSANDBOXED = 1
loc: .UNSANDBOXED = 1
loc: o/$(MODE)/tool/build/summy.com
find -name \*.h -or -name \*.c -or -name \*.S | \
$(XARGS) wc -l | grep total | awk '{print $$1}' | $<
# PLEASE: MAINTAIN TOPOLOGICAL ORDER
# FROM HIGHEST LEVEL TO LOWEST LEVEL
COSMOPOLITAN_OBJECTS = \
NET_HTTP \
LIBC_DNS \
LIBC_SOCK \
LIBC_NT_WS2_32 \
LIBC_NT_IPHLPAPI \
LIBC_NT_MSWSOCK \
LIBC_X \
THIRD_PARTY_GETOPT \
LIBC_LOG \
LIBC_TIME \
LIBC_ZIPOS \
THIRD_PARTY_ZLIB \
THIRD_PARTY_MUSL \
LIBC_STDIO \
THIRD_PARTY_GDTOA \
THIRD_PARTY_REGEX \
LIBC_THREAD \
THIRD_PARTY_NSYNC_MEM \
LIBC_MEM \
THIRD_PARTY_DLMALLOC \
LIBC_RUNTIME \
THIRD_PARTY_NSYNC \
LIBC_ELF \
LIBC_CALLS \
LIBC_SYSV_CALLS \
LIBC_VGA \
LIBC_NT_PSAPI \
LIBC_NT_POWRPROF \
LIBC_NT_PDH \
LIBC_NT_GDI32 \
LIBC_NT_COMDLG32 \
LIBC_NT_URL \
LIBC_NT_USER32 \
LIBC_NT_NTDLL \
LIBC_NT_ADVAPI32 \
LIBC_NT_SYNCHRONIZATION \
LIBC_FMT \
THIRD_PARTY_COMPILER_RT \
LIBC_TINYMATH \
THIRD_PARTY_XED \
LIBC_STR \
LIBC_SYSV \
LIBC_INTRIN \
LIBC_NT_KERNEL32 \
LIBC_NEXGEN32E
COSMOPOLITAN_OBJECTS = \
NET_HTTP \
LIBC_DNS \
LIBC_SOCK \
LIBC_NT_WS2_32 \
LIBC_NT_IPHLPAPI \
LIBC_NT_MSWSOCK \
LIBC_X \
THIRD_PARTY_GETOPT \
LIBC_LOG \
LIBC_TIME \
LIBC_ZIPOS \
THIRD_PARTY_ZLIB \
THIRD_PARTY_MUSL \
LIBC_STDIO \
THIRD_PARTY_GDTOA \
THIRD_PARTY_REGEX \
LIBC_MEM \
THIRD_PARTY_DLMALLOC \
LIBC_RUNTIME \
THIRD_PARTY_NSYNC \
LIBC_ELF \
LIBC_CALLS \
LIBC_SYSV_CALLS \
LIBC_NT_PSAPI \
LIBC_NT_POWRPROF \
LIBC_NT_PDH \
LIBC_NT_GDI32 \
LIBC_NT_COMDLG32 \
LIBC_NT_URL \
LIBC_NT_USER32 \
LIBC_NT_NTDLL \
LIBC_NT_ADVAPI32 \
LIBC_FMT \
THIRD_PARTY_COMPILER_RT \
LIBC_THREAD \
LIBC_TINYMATH \
THIRD_PARTY_XED \
LIBC_STR \
LIBC_SYSV \
LIBC_INTRIN \
LIBC_NT_KERNEL32 \
LIBC_NEXGEN32E \
LIBC_VGA
COSMOPOLITAN_HEADERS = \
APE \
LIBC \
LIBC_CALLS \
LIBC_DNS \
LIBC_ELF \
LIBC_FMT \
LIBC_INTRIN \
LIBC_LOG \
LIBC_MEM \
LIBC_NEXGEN32E \
LIBC_NT \
LIBC_RUNTIME \
LIBC_SOCK \
LIBC_STDIO \
THIRD_PARTY_NSYNC \
THIRD_PARTY_XED \
LIBC_STR \
LIBC_SYSV \
LIBC_THREAD \
LIBC_TIME \
LIBC_TINYMATH \
LIBC_X \
LIBC_ZIPOS \
LIBC_VGA \
NET_HTTP \
THIRD_PARTY_DLMALLOC \
THIRD_PARTY_GDTOA \
THIRD_PARTY_GETOPT \
THIRD_PARTY_MUSL \
THIRD_PARTY_ZLIB \
THIRD_PARTY_ZLIB_GZ \
COSMOPOLITAN_HEADERS = \
APE \
LIBC \
LIBC_CALLS \
LIBC_DNS \
LIBC_ELF \
LIBC_FMT \
LIBC_INTRIN \
LIBC_LOG \
LIBC_MEM \
LIBC_NEXGEN32E \
LIBC_NT \
LIBC_RUNTIME \
LIBC_SOCK \
LIBC_STDIO \
THIRD_PARTY_NSYNC \
THIRD_PARTY_XED \
LIBC_STR \
LIBC_SYSV \
LIBC_THREAD \
LIBC_TIME \
LIBC_TINYMATH \
LIBC_X \
LIBC_ZIPOS \
LIBC_VGA \
NET_HTTP \
THIRD_PARTY_DLMALLOC \
THIRD_PARTY_GDTOA \
THIRD_PARTY_GETOPT \
THIRD_PARTY_MUSL \
THIRD_PARTY_ZLIB \
THIRD_PARTY_ZLIB_GZ \
THIRD_PARTY_REGEX
o/$(MODE)/cosmopolitan.a: \
@@ -384,7 +370,7 @@ o/cosmopolitan.h: \
$(file >$(TMPDIR)/$(subst /,_,$@),libc/integral/normalize.inc $(foreach x,$(COSMOPOLITAN_HEADERS),$($(x)_HDRS)))
@$(COMPILE) -AROLLUP -T$@ o/$(MODE)/tool/build/rollup.com @$(TMPDIR)/$(subst /,_,$@) >$@
o/cosmopolitan.html: private .UNSANDBOXED = 1
o/cosmopolitan.html: .UNSANDBOXED = 1
o/cosmopolitan.html: \
o/$(MODE)/third_party/chibicc/chibicc.com.dbg \
$(filter-out %.s,$(foreach x,$(COSMOPOLITAN_OBJECTS),$($(x)_SRCS))) \
@@ -403,15 +389,6 @@ $(SRCS): \
libc/integral/lp64arg.inc \
libc/integral/lp64.inc
.PHONY: toolchain
toolchain: o/cosmopolitan.h \
o/$(MODE)/ape/public/ape.lds \
o/$(MODE)/libc/crt/crt.o \
o/$(MODE)/ape/ape.o \
o/$(MODE)/ape/ape-copy-self.o \
o/$(MODE)/ape/ape-no-modify-self.o \
o/$(MODE)/cosmopolitan.a
# UNSPECIFIED PREREQUISITES TUTORIAL
#
# A build rule must exist for all files that make needs to consider in
+21 -21
View File
@@ -1,7 +1,10 @@
![Cosmopolitan Honeybadger](usr/share/img/honeybadger.png)
[![build](https://github.com/jart/cosmopolitan/actions/workflows/build.yml/badge.svg)](https://github.com/jart/cosmopolitan/actions/workflows/build.yml)
# Cosmopolitan
# Cosmopolitan (Vista Edition)
**This is a community supported legacy branch of Cosmopolitan 2.0 that's
intended to preserve compatibility with Windows Vista and Windows 7.**
[Cosmopolitan Libc](https://justine.lol/cosmopolitan/index.html) makes C
a build-once run-anywhere language, like Java, except it doesn't need an
@@ -23,11 +26,11 @@ 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.1.zip
unzip cosmopolitan-amalgamation-2.1.1.zip
wget https://justine.lol/cosmopolitan/cosmopolitan-amalgamation-2.0.1.zip
unzip cosmopolitan-amalgamation-2.0.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 \
-fno-omit-frame-pointer -pg -mnop-mcount -mno-tls-direct-seg-refs \
-o hello.com.dbg hello.c -fuse-ld=bfd -Wl,-T,ape.lds -Wl,--gc-sections \
-include cosmopolitan.h crt.o ape-no-modify-self.o cosmopolitan.a
objcopy -S -O binary hello.com.dbg hello.com
@@ -100,7 +103,7 @@ heavyweight features like tracing to your binaries by default. In that
case, you may want to consider using our build system:
```sh
make m=tiny
make -j8 MODE=tiny
```
Which will cause programs such as `hello.com` and `life.com` to shrink
@@ -155,7 +158,7 @@ cd cosmopolitan
This will build the entire repository and run all the tests:
```sh
build/bootstrap/make.com
build/bootstrap/make.com -j16
o//examples/hello.com
find o -name \*.com | xargs ls -rShal | less
```
@@ -174,7 +177,7 @@ having minimal deterministic builds. For example, if you wanted to build
only hello.com then you could do that as follows:
```sh
build/bootstrap/make.com o//examples/hello.com
build/bootstrap/make.com -j16 o//examples/hello.com
```
Sometimes it's desirable to build a subset of targets, without having to
@@ -183,7 +186,7 @@ directory name. For example, if you wanted to build only the targets and
subtargets of the chibicc package including its tests, you would say:
```sh
build/bootstrap/make.com o//third_party/chibicc
build/bootstrap/make.com -j16 o//third_party/chibicc
o//third_party/chibicc/chibicc.com --help
```
@@ -191,19 +194,18 @@ Cosmopolitan provides a variety of build modes. For example, if you want
really tiny binaries (as small as 12kb in size) then you'd say:
```sh
build/bootstrap/make.com m=tiny
build/bootstrap/make.com -j16 MODE=tiny
```
Here's some other build modes you can try:
```sh
build/bootstrap/make.com m=dbg # asan + ubsan + debug
build/bootstrap/make.com m=asan # production memory safety
build/bootstrap/make.com m=opt # -march=native optimizations
build/bootstrap/make.com m=rel # traditional release binaries
build/bootstrap/make.com m=optlinux # optimal linux-only performance
build/bootstrap/make.com m=fastbuild # build 28% faster w/o debugging
build/bootstrap/make.com m=tinylinux # tiniest linux-only 4kb binaries
build/bootstrap/make.com -j16 MODE=dbg # asan + ubsan + debug
build/bootstrap/make.com -j16 MODE=asan # production memory safety
build/bootstrap/make.com -j16 MODE=opt # -march=native optimizations
build/bootstrap/make.com -j16 MODE=rel # traditional release binaries
build/bootstrap/make.com -j16 MODE=optlinux # optimal linux-only performance
build/bootstrap/make.com -j16 MODE=tinylinux # tiniest linux-only 4kb binaries
```
For further details, see [//build/config.mk](build/config.mk).
@@ -245,11 +247,11 @@ gdb foo.com -ex 'add-symbol-file foo.com.dbg 0x401000'
| :--- | ---: | ---: |
| AMD | K8 Venus | 2005 |
| Intel | Core | 2006 |
| Windows | Vista | 2006 |
| Linux | 2.6.18 | 2007 |
| Windows | 8 | 2012 |
| Mac OS X | 15.6 | 2018 |
| OpenBSD | 6.4 | 2018 |
| FreeBSD | 13 | 2020 |
| OpenBSD | 6.4 | 2018 |
| NetBSD | 9.2 | 2021 |
## Special Thanks
@@ -258,10 +260,8 @@ 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 groups and individuals:
the following 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.
+28 -38
View File
@@ -125,7 +125,6 @@ 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
@@ -236,9 +235,8 @@ pc: cld
#endif
ljmp $0,$REAL(1f)
1: mov %cx,%ds
.set mm,0x0500 # struct mman
mov $IMAGE_BASE_REAL-mm,%cx # clears bss
mov $mm>>4,%ax
mov $IMAGE_BASE_REAL-0x0500,%cx # clears bss
mov $0x0500>>4,%ax # struct mman
mov %ax,%es
xor %ax,%ax
xor %di,%di
@@ -251,6 +249,7 @@ 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
@@ -329,7 +328,7 @@ dsknfo: push %bx
movpp %es,%ds
xor %si,%si
mov %si,%es
mov $mm+"struct mman::pc_drive_base_table",%si
mov $0x1d10,%si # mman::pc_drive_base_table
xchg %si,%di
movsw #→ headunloadtime, headloadtime
movsw #→ shutofftime, bytespersector
@@ -382,11 +381,11 @@ pcread: push %ax
add $512>>4,%si
mov %si,%es
inc %al # ++sector
cmp mm+"struct mman::pc_drive_last_sector",%al
cmp 0x1d1c,%al # mman::pc_drive_last_sector
jbe 2f
mov $1,%al
inc %dh # ++head
cmp mm+"struct mman::pc_drive_last_head",%dh
cmp 0x1d20,%dh # mman::pc_drive_last_head
jbe 2f
xor %dh,%dh
inc %cx # ++cylinder
@@ -549,7 +548,7 @@ ape_disk:
the bourne executable & linkable format */
#if SupportsWindows() || SupportsMetal() || SupportsXnu()
apesh: .ascii "\n@\n#'\"\n" # sixth edition shebang
apesh: .ascii "'\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.
@@ -874,7 +873,7 @@ ape_macho:
.long (520f-510f)/4 # count
510: .quad 0 # rax
.quad IMAGE_BASE_VIRTUAL # rbx
.quad _HOSTXNU # rcx
.quad XNU # rcx
.quad 0 # rdx
.quad 0 # rdi
.quad 0 # rsi
@@ -1137,17 +1136,12 @@ sconf: .short 1843200/*hz*/ / 16/*wut*/ / 9600/*baud*/
.endobj sconf,global,hidden
// Global Descriptor Table
//
// @note address portion only concern legacy modes
.align 8
_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:
gdt: .short 2f-1f # table byte length
.long REAL(1f),0 # table address
.zero 2
1:
// ┌G:granularity (1 → limit *= 0x1000)
// │┌D/B:default operation size (0 = 16|64bit, 1 = 32-bit)
@@ -1177,9 +1171,7 @@ _gdt:
.quad 0b0000000011001111100100100000000000000000000000001111111111111111 #32
.quad 0b0000000010101111100110110000000000000000000000001111111111111111 #40
.quad 0b0000000010101111100100110000000000000000000000001111111111111111 #48
.tssdescstub _tss #56,64
2:
.endobj _gdt,global,hidden
2: .endobj gdt,global,hidden
/*─────────────────────────────────────────────────────────────────────────────╗
│ αcτµαlly pδrταblε εxεcµταblε § real mode │
@@ -1285,8 +1277,8 @@ lcheck: pushf # check for i8086 / i8088 / i80186
jl 10f
mov %edi,%eax
cpuid
mov $1<<29|1<<20,%edi # need nexgen32e long mode support
and %edi,%edx # & nx support
mov $1<<29,%edi # need nexgen32e long mode support
and %edi,%edx
cmp %edi,%edx
jne 10f
xor %ax,%ax
@@ -1296,9 +1288,10 @@ lcheck: pushf # check for i8086 / i8088 / i80186
.endfn lcheck
// Gets memory map from BIOS.
e820: xor %ebx,%ebx # %ebx is an api state tracker
mov %bx,%es
mov $mm+"struct mman::e820",%di # es:di is destination buffer
e820: mov $0x0510>>4,%di # mman::e820
mov %di,%es
xor %di,%di # es:di is destination buffer
xor %ebx,%ebx # ebx is an api state tracker
1: mov $0xE820,%eax # magic
mov $8+8+4+4,%ecx # sizeof(struct SmapEntry)
mov $0x534d4150,%edx # magic number
@@ -1322,7 +1315,7 @@ e820: xor %ebx,%ebx # %ebx is an api state tracker
4: add $8+8+4+4,%di # keep entry
5: test %ebx,%ebx # last entry?
jz 8f
cmp $mm+"struct mman::e820_end"-(8+8+4+4),%di
cmp $(256-1)*(8+8+4+4),%di
jb 1b
8: xor %ax,%ax # add a blank sentinel entry
mov $(8+8)/2,%cx
@@ -1415,7 +1408,7 @@ pinit: push %ds
movl $0x79000+PAGE_V+PAGE_RW,0x7b000-SEG # PD←PDT (+)
movl $0x79000+PAGE_V+PAGE_RW,0x7a000-SEG # PD←PDT (-)
mov $512,%cx # PD±2MB
mov $PAGE_V+PAGE_RSRV+PAGE_RW,%eax
mov $PAGE_V+PAGE_RW,%eax
xor %di,%di
0: stosl
add $0x1000,%eax
@@ -1432,15 +1425,15 @@ pinit: push %ds
//
// @see Intel Manual V3A §4.1.2
golong: cli
lidt mm+"struct mman::bad_idt"
lidt 0x1d22 # mman::bad_idt
mov %cr4,%eax
or $CR4_PAE|CR4_PGE|CR4_OSFXSR,%eax
mov %eax,%cr4
movl $EFER,%ecx
rdmsr
or $EFER_LME|EFER_SCE|EFER_NXE,%eax
or $EFER_LME|EFER_SCE,%eax
wrmsr
lgdt REAL(_gdtrphy)
lgdt REAL(gdt)
mov %cr0,%eax
or $CR0_PE|CR0_PG|CR0_MP,%eax
and $~CR0_EM,%eax
@@ -1458,8 +1451,6 @@ 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
@@ -1467,14 +1458,12 @@ long: xor %eax,%eax
xor %ebx,%ebx
xor %ebp,%ebp
push %rbp
mov $mm,%rdi
mov $0x0500,%rdi # mman
mov %cr3,%rsi
mov $IMAGE_BASE_REAL,%edx
call __map_phdrs
push $0x037f
fldcw (%rsp)
lgdt _gdtr # reload GDTR for
# virtual memory space
movabs $kernel,%rax
jmp *%rax
.endfn long
@@ -1555,7 +1544,7 @@ kernel: movabs $ape_stack_vaddr,%rsp
.byte 0x0f,0x1f,0207 # nop rdi binbase
.long (IMAGE_BASE_VIRTUAL-IMAGE_BASE_REAL)/512
#endif
push $_HOSTMETAL # sets __hostos in crt.S
push $METAL # sets __hostos in crt.S
pop %rcx
push $0
mov %rsp,%rbp
@@ -1597,6 +1586,7 @@ 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
View File
@@ -427,7 +427,7 @@ SECTIONS {
KEEP(*(.bssepilogue))
/*END: NT FORK COPYING */
. = ALIGN(PAGESIZE);
. = ALIGN(FRAMESIZE); /* for brk()/sbrk() allocation */
HIDDEN(_end = .);
PROVIDE_HIDDEN(end = .);
} :Bss
@@ -458,7 +458,6 @@ SECTIONS {
.debug_line 0 : { *(.debug_line .debug_line.* .debug_line_end ) }
.debug_frame 0 : { *(.debug_frame) }
.debug_str 0 : { *(.debug_str) }
.debug_line_str 0 : { *(.debug_line_str) }
.debug_loc 0 : { *(.debug_loc) }
.debug_macinfo 0 : { *(.debug_macinfo) }
.debug_weaknames 0 : { *(.debug_weaknames) }
@@ -467,7 +466,6 @@ SECTIONS {
.debug_varnames 0 : { *(.debug_varnames) }
.debug_pubtypes 0 : { *(.debug_pubtypes) }
.debug_ranges 0 : { *(.debug_ranges) }
.debug_rnglists 0 : { *(.debug_rnglists) }
.debug_macro 0 : { *(.debug_macro) }
.debug_addr 0 : { *(.debug_addr) }
.gnu.attributes 0 : { KEEP(*(.gnu.attributes)) }
@@ -565,11 +563,13 @@ SHSTUB2(ape_loader_dd_count,
#if SupportsMetal()
HIDDEN(v_ape_realsectors =
MIN(0x70000 - IMAGE_BASE_REAL,
ROUNDUP(RVA(_edata), 512)) / 512);
ROUNDUP(RVA(_edata), 4096)) / 512);
HIDDEN(v_ape_realslacksectors =
v_ape_realsectors - MIN(0x70000 - IMAGE_BASE_REAL,
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);
TSSDESCSTUB2(_tss, _tss, _tss_end ? _tss_end - _tss - 1 : 0);
#endif
/* ZIP End of Central Directory header */
-2
View File
@@ -65,7 +65,6 @@ o/$(MODE)/ape/ape.lds: \
libc/intrin/bits.h \
libc/thread/tls.h \
libc/calls/struct/timespec.h \
libc/thread/thread.h \
libc/dce.h \
libc/elf/def.h \
libc/elf/pf2prot.internal.h \
@@ -83,7 +82,6 @@ o/$(MODE)/ape/public/ape.lds: \
libc/intrin/bits.h \
libc/thread/tls.h \
libc/calls/struct/timespec.h \
libc/thread/thread.h \
libc/dce.h \
libc/elf/def.h \
libc/elf/pf2prot.internal.h \
+33 -33
View File
@@ -32,23 +32,23 @@
// @see ape/ape.lds
// @see winimp
.macro .imp dll:req fn:req actual:req hint
.dll "\dll"
.section ".piro.data.sort.iat.2.\dll\().2.\actual","aw",@progbits
.dll \dll
.section .piro.data.sort.iat.2.\dll\().2.\actual,"aw",@progbits
.type \fn,@object
.align __SIZEOF_POINTER__
\fn: .quad RVA(("\dll\().\actual"))
\fn: .quad RVA((\dll\().\actual))
.size \fn,.-\fn
.globl \fn
.hidden \fn
.previous
.section ".idata.ro.ilt.\dll\().2.\actual","a",@progbits
".Lidata.ilt.\dll\().\actual":
.quad RVA("\dll\().\actual")
.type ".Lidata.ilt.\dll\().\actual",@object
.size ".Lidata.ilt.\dll\().\actual",.-".Lidata.ilt.\dll\().\actual"
.section .idata.ro.ilt.\dll\().2.\actual,"a",@progbits
.Lidata.ilt.\dll\().\actual:
.quad RVA((\dll\().\actual))
.type .Lidata.ilt.\dll\().\actual,@object
.size .Lidata.ilt.\dll\().\actual,.-.Lidata.ilt.\dll\().\actual
.previous
.section ".idata.ro.hnt.\dll\().2.\actual","a",@progbits
"\dll\().\actual":
.section .idata.ro.hnt.\dll\().2.\actual,"a",@progbits
\dll\().\actual:
.ifnb \hint # hint i.e. guess function ordinal
.short \hint
.else
@@ -56,55 +56,55 @@
.endif
.asciz "\actual"
.align 2 # documented requirement
.globl "\dll\().\actual"
.hidden "\dll\().\actual"
.type "\dll\().\actual",@object
.size "\dll\().\actual",.-"\dll\().\actual"
.globl \dll\().\actual
.hidden \dll\().\actual
.type \dll\().\actual,@object
.size \dll\().\actual,.-\dll\().\actual
.previous
.endm
// Defines DLL import.
// @note this is an implementation detail of .imp
.macro .dll name:req
.section ".idata.ro.idt.2.\name","aG",@progbits,"\name",comdat
.equ ".Lidata.idt.\name",.
.long RVA("idata.ilt.\name") # ImportLookupTable
.section .idata.ro.idt.2.\name,"aG",@progbits,\name,comdat
.equ .Lidata.idt.\name,.
.long RVA(idata.ilt.\name) # ImportLookupTable
.long 0 # TimeDateStamp
.long 0 # ForwarderChain
.long RVA(".Lidata.str.\name") # DllNameRva
.long RVA("idata.iat.\name") # ImportAddressTable
.type ".Lidata.idt.\name",@object
.size ".Lidata.idt.\name",.-".Lidata.idt.\name"
.long RVA(.Lidata.str.\name) # DllNameRva
.long RVA(idata.iat.\name) # ImportAddressTable
.type .Lidata.idt.\name,@object
.size .Lidata.idt.\name,.-.Lidata.idt.\name
.previous
.section ".idata.ro.ilt.\name\().1","aG",@progbits,"\name",comdat
.section .idata.ro.ilt.\name\().1,"aG",@progbits,\name,comdat
.align __SIZEOF_POINTER__
.type "idata.ilt.\name",@object
"idata.ilt.\name":
.type idata.ilt.\name,@object
idata.ilt.\name:
.previous/*
...
decentralized content
...
*/.section ".idata.ro.ilt.\name\().3","aG",@progbits,"\name",comdat
*/.section .idata.ro.ilt.\name\().3,"aG",@progbits,\name,comdat
.quad 0
.previous
.section ".idata.ro.hnt.\name\().1","aG",@progbits,"\name",comdat
.section .idata.ro.hnt.\name\().1,"aG",@progbits,\name,comdat
.align __SIZEOF_POINTER__
.type "idata.hnt.\name",@object
.equ "idata.hnt.\name",.
.type idata.hnt.\name,@object
.equ idata.hnt.\name,.
.previous
.section ".piro.data.sort.iat.2.\name\().1","awG",@progbits,"\name",comdat
.section .piro.data.sort.iat.2.\name\().1,"awG",@progbits,\name,comdat
.align __SIZEOF_POINTER__
.type "idata.iat.\name",@object
"idata.iat.\name":
.type idata.iat.\name,@object
idata.iat.\name:
.previous/*
...
decentralized content
...
*/.section ".piro.data.sort.iat.2.\name\().3","awG",@progbits,"\name",comdat
*/.section .piro.data.sort.iat.2.\name\().3,"awG",@progbits,\name,comdat
.quad 0
.previous
.section .rodata.str1.1,"aSM",@progbits,1
".Lidata.str.\name":
.Lidata.str.\name:
.asciz "\name\().dll"
.previous
.endm
+2 -2
View File
@@ -175,7 +175,7 @@ macho: .long 0xFEEDFACE+1
510: .quad 0 # rax
.quad 0 # rbx
.quad 0 # rcx
.quad _HOSTXNU # rdx
.quad XNU # rdx
.quad 0 # rdi
.quad 0 # rsi
.quad 0 # rbp
@@ -221,7 +221,7 @@ _start:
jne 0f
cmp $+1,%edx
jne 0f
mov $_HOSTXNU,%dl
mov $XNU,%dl
xor %ecx,%ecx
0: mov %rsp,%rsi
+2 -2
View File
@@ -90,7 +90,7 @@ macho: .long 0xFEEDFACE+1
510: .quad 0 # rax
.quad 0 # rbx
.quad 0 # rcx
.quad _HOSTXNU # rdx
.quad XNU # rdx
.quad 0 # rdi
.quad 0 # rsi
.quad 0 # rbp
@@ -121,7 +121,7 @@ _start:
jne 0f
cmp $+1,%edx
jne 0f
mov $_HOSTXNU,%dl
mov $XNU,%dl
xor %ecx,%ecx
0: mov %rsp,%rsi
-31
View File
@@ -180,20 +180,6 @@
.stub \name\()_bcs\n,long
.endm
// Task State Segment Descriptor Entries.
.macro .tssdescstub name:req
.ifndef \name
.weak \name
.set \name,0
.endif
.ifndef \name\()_end
.weak \name\()_end
.set \name\()_end,0
.endif
.stub \name\()_desc_ent0,quad
.stub \name\()_desc_ent1,quad
.endm
/* clang-format on */
#elif defined(__LINKER__)
@@ -271,22 +257,5 @@
(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_ */
Binary file not shown.
Binary file not shown.
+1 -43
View File
@@ -102,7 +102,7 @@ endif
# - Larger binaries
#
ifeq ($(MODE), asan)
CONFIG_CCFLAGS += $(BACKTRACES) -O2 -DSYSDEBUG
CONFIG_CCFLAGS += $(BACKTRACES) -O2
CONFIG_COPTS += -fsanitize=address
TARGET_ARCH ?= -msse3
endif
@@ -152,10 +152,6 @@ CONFIG_CCFLAGS += \
-fomit-frame-pointer \
-momit-leaf-frame-pointer \
-foptimize-sibling-calls
CONFIG_OFLAGS += \
-g0
CONFIG_LDFLAGS += \
-S
TARGET_ARCH ?= \
-msse3
PYFLAGS += \
@@ -184,10 +180,6 @@ CONFIG_CPPFLAGS += \
-DSUPPORT_VECTOR=1
DEFAULT_COPTS += \
-mred-zone
CONFIG_OFLAGS += \
-g0
CONFIG_LDFLAGS += \
-S
CONFIG_CCFLAGS += \
-Os \
-fno-align-functions \
@@ -220,10 +212,6 @@ CONFIG_CPPFLAGS += \
-DSUPPORT_VECTOR=113
DEFAULT_COPTS += \
-mred-zone
CONFIG_OFLAGS += \
-g0
CONFIG_LDFLAGS += \
-S
CONFIG_CCFLAGS += \
-Os \
-fno-align-functions \
@@ -261,10 +249,6 @@ CONFIG_CCFLAGS += \
-fno-align-jumps \
-fno-align-labels \
-fno-align-loops
CONFIG_OFLAGS += \
-g0
CONFIG_LDFLAGS += \
-S
TARGET_ARCH ?= \
-msse3
endif
@@ -294,36 +278,10 @@ CONFIG_CCFLAGS += \
-fno-align-jumps \
-fno-align-labels \
-fno-align-loops
CONFIG_OFLAGS += \
-g0
CONFIG_LDFLAGS += \
-S
TARGET_ARCH ?= \
-msse3
endif
# GCC11 Mode
# https://justine.lol/compilers/x86_64-linux-musl__x86_64-linux-musl__g++-11.2.0.tar.xz
ifeq ($(MODE), gcc11)
.UNVEIL += rx:/opt/gcc11
CONFIG_CCFLAGS += $(BACKTRACES) $(FTRACE) -DSYSDEBUG -O2
AS = /opt/gcc11/bin/x86_64-linux-musl-as
CC = /opt/gcc11/bin/x86_64-linux-musl-gcc
CXX = /opt/gcc11/bin/x86_64-linux-musl-g++
CXXFILT = /opt/gcc11/bin/x86_64-linux-musl-c++filt
LD = /opt/gcc11/bin/x86_64-linux-musl-ld.bfd
NM = /opt/gcc11/bin/x86_64-linux-musl-nm
GCC = /opt/gcc11/bin/x86_64-linux-musl-gcc
STRIP = /opt/gcc11/bin/x86_64-linux-musl-strip
OBJCOPY = /opt/gcc11/bin/x86_64-linux-musl-objcopy
OBJDUMP = /opt/gcc11/bin/x86_64-linux-musl-objdump
ADDR2LINE = /opt/gcc11/bin/x86_64-linux-musl-addr2line
CONFIG_CCFLAGS += $(BACKTRACES) $(FTRACE) -O2 -Wno-stringop-overread
CONFIG_CFLAGS += -Wno-old-style-definition
CONFIG_CPPFLAGS += -DNDEBUG -DSYSDEBUG
TARGET_ARCH ?= -msse3
endif
# LLVM Mode
ifeq ($(MODE), llvm)
TARGET_ARCH ?= -msse3
+23 -16
View File
@@ -73,25 +73,33 @@ 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-*)","")
PREFIX = o/third_party/gcc/bin/x86_64-pc-linux-gnu-
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
else
IGNORE := $(shell build/bootstrap/unbundle.com)
PREFIX = o/third_party/gcc/bin/x86_64-linux-musl-
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
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
@@ -140,7 +148,6 @@ DEFAULT_CCFLAGS = \
DEFAULT_OFLAGS = \
-g \
-gdwarf-4 \
-gdescribe-dies
DEFAULT_COPTS = \
+8 -8
View File
@@ -163,15 +163,15 @@ o/$(MODE)%/.zip.o: %
# and it would be too costly in terms of make latency to have every
# header file depend on $(HDRS) and $(INCS).
o/%.h.ok: private .UNSANDBOXED = 1
o/%.h.ok: .UNSANDBOXED = 1
o/%.h.ok: %.h
@$(COMPILE) -ACHECK.h $(COMPILE.c) -xc -g0 -o $@ $<
o/$(MODE)/%.h.ok: private .UNSANDBOXED = 1
o/$(MODE)/%.h.ok: .UNSANDBOXED = 1
o/$(MODE)/%.h.ok: %.h
@$(COMPILE) -ACHECK.h $(COMPILE.c) -xc -g0 -o $@ $<
o/$(MODE)/%.hh.ok: private .UNSANDBOXED = 1
o/$(MODE)/%.hh.ok: .UNSANDBOXED = 1
o/$(MODE)/%.hh.ok: %.hh
@$(COMPILE) -ACHECK.h $(COMPILE.cxx) -xc++ -g0 -o $@ $<
@@ -179,7 +179,7 @@ o/%.okk: .UNSANDBOXED = 1
o/%.okk: %
@$(COMPILE) -ACHECK.h $(COMPILE.cxx) -xc++ -g0 -o $@ $<
o/$(MODE)/%.okk: private .UNSANDBOXED = 1
o/$(MODE)/%.okk: .UNSANDBOXED = 1
o/$(MODE)/%.okk: %
@$(COMPILE) -ACHECK.h $(COMPILE.cxx) -xc++ -g0 -o $@ $<
@@ -207,19 +207,19 @@ MAKE_SYMTAB_ZIP = \
################################################################################
# EMACS ASSEMBLY GENERATION
o/$(MODE)/%-gcc.asm: private .UNSANDBOXED = 1
o/$(MODE)/%-gcc.asm: .UNSANDBOXED = 1
o/$(MODE)/%-gcc.asm: %.c
@$(COMPILE) -AOBJECTIFY.c $(OBJECTIFY.c) -S -g0 $(OUTPUT_OPTION) $<
o/$(MODE)/%-gcc.asm: private .UNSANDBOXED = 1
o/$(MODE)/%-gcc.asm: .UNSANDBOXED = 1
o/$(MODE)/%-gcc.asm: %.cc
@$(COMPILE) -AOBJECTIFY.c $(OBJECTIFY.cxx) -S -g0 $(OUTPUT_OPTION) $<
o/$(MODE)/%-clang.asm: private .UNSANDBOXED = 1
o/$(MODE)/%-clang.asm: .UNSANDBOXED = 1
o/$(MODE)/%-clang.asm: %.c
@$(COMPILE) -AOBJECTIFY.c $(OBJECTIFY.c) -S -g0 $(OUTPUT_OPTION) $<
o/$(MODE)/%-clang.asm: CC = $(CLANG)
o/$(MODE)/%-clang.asm: private .UNSANDBOXED = 1
o/$(MODE)/%-clang.asm: .UNSANDBOXED = 1
o/$(MODE)/%-clang.asm: %.cc
@$(COMPILE) -AOBJECTIFY.c $(OBJECTIFY.cxx) -S -g0 $(OUTPUT_OPTION) $<
+1 -1
View File
@@ -30,7 +30,7 @@
* @see ttyconfig(), ttyrestore()
*/
int ttyconfig(int ttyfd, ttyconf_f fn, int64_t arg,
struct termios *opt_out_oldconf) {
const struct termios *opt_out_oldconf) {
struct termios conf[2];
if (tcgetattr(ttyfd, &conf[0]) != -1 &&
fn(memcpy(&conf[1], &conf[0], sizeof(conf[0])), arg) != -1 &&
+1 -1
View File
@@ -44,7 +44,7 @@ int ttysendtitle(int, const char *, const struct TtyIdent *);
int ttyident(struct TtyIdent *, int, int);
void ttyidentclear(struct TtyIdent *);
char *ttydescribe(char *, size_t, const struct TtyIdent *);
int ttyconfig(int, ttyconf_f, int64_t, struct termios *);
int ttyconfig(int, ttyconf_f, int64_t, const struct termios *);
int ttyrestore(int, const struct termios *);
int ttysetrawdeadline(struct termios *, int64_t);
int ttysetrawmode(struct termios *, int64_t);
-56
View File
@@ -1,56 +0,0 @@
#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/struct/timespec.h"
#include "libc/errno.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/kprintf.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/clock.h"
int n;
int shown[64];
void show(int clock) {
int i;
struct timespec ts;
if (clock == 127) return;
for (i = 0; i < n; ++i) {
if (shown[i] == clock) {
return;
}
}
shown[n++] = clock;
if (clock_getres(clock, &ts) != -1) {
kprintf("%s %'ld ns\n", DescribeClockName(clock), _timespec_tonanos(ts));
} else {
kprintf("%s %s\n", DescribeClockName(clock), _strerrno(errno));
}
}
int main(int argc, char *argv[]) {
show(CLOCK_REALTIME);
show(CLOCK_REALTIME_FAST);
show(CLOCK_REALTIME_PRECISE);
show(CLOCK_MONOTONIC);
show(CLOCK_MONOTONIC_RAW);
show(CLOCK_MONOTONIC_FAST);
show(CLOCK_MONOTONIC_PRECISE);
show(CLOCK_PROCESS_CPUTIME_ID);
show(CLOCK_THREAD_CPUTIME_ID);
show(CLOCK_PROF);
show(CLOCK_BOOTTIME);
show(CLOCK_REALTIME_ALARM);
show(CLOCK_BOOTTIME_ALARM);
show(CLOCK_TAI);
show(CLOCK_UPTIME);
show(CLOCK_UPTIME_PRECISE);
show(CLOCK_UPTIME_FAST);
show(CLOCK_SECOND);
}
+1 -1
View File
@@ -183,7 +183,7 @@ int main(int argc, char *argv[]) {
struct Url url;
char *host, *port;
bool usessl = false;
_gc(ParseUrl(urlarg, -1, &url, kUrlPlus));
_gc(ParseUrl(urlarg, -1, &url));
_gc(url.params.p);
if (url.scheme.n) {
if (url.scheme.n == 5 && !memcasecmp(url.scheme.p, "https", 5)) {
-2
View File
@@ -73,7 +73,6 @@ EXAMPLES_DIRECTDEPS = \
NET_HTTPS \
THIRD_PARTY_COMPILER_RT \
THIRD_PARTY_DLMALLOC \
THIRD_PARTY_DOUBLECONVERSION \
THIRD_PARTY_GDTOA \
THIRD_PARTY_GETOPT \
THIRD_PARTY_LIBCXX \
@@ -82,7 +81,6 @@ EXAMPLES_DIRECTDEPS = \
THIRD_PARTY_MBEDTLS \
THIRD_PARTY_MUSL \
THIRD_PARTY_NSYNC \
THIRD_PARTY_NSYNC_MEM \
THIRD_PARTY_QUICKJS \
THIRD_PARTY_STB \
THIRD_PARTY_XED \
+8 -1
View File
@@ -9,12 +9,19 @@
#endif
#include "libc/calls/calls.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/nt/nt/process.h"
#include "libc/mem/gc.h"
#include "libc/runtime/memtrack.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/rand.h"
#include "libc/stdio/stdio.h"
#include "libc/time/time.h"
#include "libc/x/x.h"
dontinline void dostuff(const char *s) {
int i, us;
srand(_rand64()); /* seeds rand() w/ intel rdrnd, auxv, etc. */
srand(rand64()); /* seeds rand() w/ intel rdrnd, auxv, etc. */
for (i = 0; i < 5; ++i) {
us = rand() % 500000;
usleep(us);
+2 -2
View File
@@ -8,8 +8,8 @@
╚─────────────────────────────────────────────────────────────────*/
#endif
#include "libc/intrin/kprintf.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/sysconf.h"
int main() {
kprintf("%d\n", _getcpucount());
kprintf("%d\n", GetCpuCount());
}
+2 -2
View File
@@ -102,7 +102,7 @@ uint64_t rngset64(void) {
static unsigned i;
static uint64_t s;
if (!i) {
s = _rand64();
s = rand64();
i = (s + 1) & (511);
}
return MarsagliaXorshift64(&s);
@@ -215,7 +215,7 @@ const struct Function {
{"moby", moby}, //
{"mt19937", _mt19937}, //
{"python", pythonx2}, //
{"rand64", _rand64}, //
{"rand64", rand64}, //
{"rdrand", rdrand}, //
{"rdrnd", rdrand}, //
{"rdseed", rdseed}, //
+3 -2
View File
@@ -28,6 +28,7 @@
#include "libc/runtime/internal.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/stack.h"
#include "libc/runtime/sysconf.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/pollfd.h"
#include "libc/sock/struct/sockaddr.h"
@@ -136,7 +137,7 @@ void *Worker(void *id) {
setsockopt(server, SOL_TCP, TCP_QUICKACK, &yes, sizeof(yes));
errno = 0;
if (bind(server, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
if (bind(server, &addr, sizeof(addr)) == -1) {
kprintf("%s() failed %m\n", "socket");
goto CloseWorker;
}
@@ -298,7 +299,7 @@ int main(int argc, char *argv[]) {
PORT);
}
threads = argc > 1 ? atoi(argv[1]) : _getcpucount();
threads = argc > 1 ? atoi(argv[1]) : GetCpuCount();
if (!(1 <= threads && threads <= 100000)) {
kprintf("error: invalid number of threads: %d\n", threads);
exit(1);
@@ -16,17 +16,995 @@
│ limitations under the License. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/weirdtypes.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/fmt/fmt.h"
#include "libc/limits.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/stdio/temp.h"
#include "libc/str/str.h"
#include "libc/thread/thread.h"
#include "third_party/nsync/atomic.internal.h"
#include "third_party/nsync/cv.h"
#include "third_party/nsync/dll.h"
#include "third_party/nsync/mu.h"
#include "third_party/nsync/mu_wait.h"
#include "third_party/nsync/testing/closure.h"
#include "third_party/nsync/testing/smprintf.h"
#include "third_party/nsync/testing/testing.h"
#include "third_party/nsync/testing/time_extra.h"
#include "third_party/nsync/races.internal.h"
#include "third_party/nsync/time.h"
// clang-format off
/**
* @fileoverview *NSYNC Mutex Tests / Benchmarks.
*
* make -j8 o//examples/mu_test.com
* o//examples/mu_test.com -b
*
*/
typedef struct testing_base_s *testing_base;
typedef const struct testing_base_s *const_testing_base;
typedef struct testing_s *testing;
/* Return a newly initialized testing_base. */
testing_base testing_new (int argc, char *argv[], int flags);
/* Return the index of the first argument in argv[] not processed by testing_new() */
int testing_base_argn (testing_base tb);
/* exit() with the test's exit status */
int testing_base_exit (testing_base tb);
/* Stop and start the benchmark timer. */
void testing_stop_timer (testing t);
void testing_start_timer (testing t);
/* Return whether the machine appears to be a uniprocessor.
Some tests get different results on uniprocessors, because
the probability of certain interleavings of thread actions is
greatly reduced. */
int testing_is_uniprocessor (testing t);
/* Given a testing_base, run f (t), where t has type testing.
Output will be for a test. */
#define TEST_RUN(tb, f) testing_run_ ((tb), &f, #f, 0)
/* Given a testing_base, run f (t), where t has type testing.
Output will be for a benchmark, which should iterate testing_n (t) times. */
#define BENCHMARK_RUN(tb, f) testing_run_ ((tb), &f, #f, 1)
/* Return the iteration count for a benchmark. */
int testing_n (testing t);
/* Output nul-terminated string msg[] to stderr, then abort(). */
void testing_panic (const char *msg);
/* Return a value below 0 if tests should run short, 0 if normal, and a value exceeding
0 if tests should run long. */
int testing_longshort (testing t);
/* Return non-zero if the user requested verbose output. */
int testing_verbose (testing t);
/* Output a printf-formated log message associated with *t.
Example: TEST_LOG (t, ("wombat %d", some_int));
The TEST_ERROR() and TEST_FATAL() forms of the call makr the test as failing.
The TEST_FATAL() form causes other subtests not to run. */
#define TEST_LOG(t, args) testing_error_ ((t), 0, __FILE__, __LINE__, smprintf args);
#define TEST_ERROR(t, args) testing_error_ ((t), 1, __FILE__, __LINE__, smprintf args);
#define TEST_FATAL(t, args) testing_error_ ((t), 2, __FILE__, __LINE__, smprintf args);
/* ---------------------------------------- */
/* internal details follow */
/* An internal routine used by TEST_RUN() and BENCHMARK_RUN(). */
void testing_run_ (testing_base tb, void (*f) (testing t), const char *name, int is_benchmark);
/* Output an error message msg, and record status. */
void testing_error_ (testing t, int status, const char *file, int line, char *msg);
////////////////////////////////////////////////////////////////////////////////
// time_extra.h
/* Return a malloced nul-terminated string representing time t, using
"decimals" decimal places. */
char *nsync_time_str (nsync_time t, int decimals);
/* Sleep until the specified time. Returns 0 on success, and EINTR
if the call was interrupted. */
int nsync_time_sleep_until (nsync_time abs_deadline);
/* Return t as a double. */
double nsync_time_to_dbl (nsync_time t);
/* Return a time corresponding to double d. */
nsync_time nsync_time_from_dbl (double d);
////////////////////////////////////////////////////////////////////////////////
// smprintf.h
char *smprintf (const char *fmt, ...);
////////////////////////////////////////////////////////////////////////////////
// smprintf.c
char *smprintf (const char *fmt, ...) {
int m = strlen (fmt) * 2 + 1;
char *buf = (char *) malloc (m);
int didnt_fit;
do {
va_list ap;
int x;
va_start (ap, fmt);
x = vsnprintf (buf, m, fmt, ap);
va_end (ap);
if (x >= m) {
buf = (char *) realloc (buf, m = x+1);
didnt_fit = 1;
} else if (x < 0 || x == m-1) {
buf = (char *) realloc (buf, m *= 2);
didnt_fit = 1;
} else {
didnt_fit = 0;
}
} while (didnt_fit);
return (buf);
}
////////////////////////////////////////////////////////////////////////////////
// time_extra.c
char *nsync_time_str (nsync_time t, int decimals) {
static const struct {
const char *suffix;
double multiplier;
} scale[] = {
{ "ns", 1.0e-9, },
{ "us", 1e-6, },
{ "ms", 1e-3, },
{ "s", 1.0, },
{ "hr", 3600.0, },
};
double s = nsync_time_to_dbl (t);
int i = 0;
while (i + 1 != sizeof (scale) / sizeof (scale[0]) && scale[i + 1].multiplier <= s) {
i++;
}
return (smprintf ("%.*f%s", decimals, s/scale[i].multiplier, scale[i].suffix));
}
int nsync_time_sleep_until (nsync_time abs_deadline) {
int result = 0;
nsync_time now;
now = nsync_time_now ();
if (nsync_time_cmp (abs_deadline, now) > 0) {
nsync_time remaining;
remaining = nsync_time_sleep (nsync_time_sub (abs_deadline, now));
if (nsync_time_cmp (remaining, nsync_time_zero) > 0) {
result = EINTR;
}
}
return (result);
}
double nsync_time_to_dbl (nsync_time t) {
return (((double) NSYNC_TIME_SEC (t)) + ((double) NSYNC_TIME_NSEC (t) * 1e-9));
}
nsync_time nsync_time_from_dbl (double d) {
time_t s = (time_t) d;
if (d < s) {
s--;
}
return (nsync_time_s_ns (s, (unsigned) ((d - (double) s) * 1e9)));
}
////////////////////////////////////////////////////////////////////////////////
// start_thread.c
struct thd_args {
void (*f) (void *);
void *arg;
};
static void *body (void *v) {
struct thd_args *args = (struct thd_args *) v;
(*args->f) (args->arg);
free (args);
return (NULL);
}
void nsync_start_thread_ (void (*f) (void *), void *arg) {
struct thd_args *args = (struct thd_args *) malloc (sizeof (*args));
pthread_t t;
args->f = f;
args->arg = arg;
pthread_create (&t, NULL, body, args);
pthread_detach (t);
}
////////////////////////////////////////////////////////////////////////////////
// closure.h
/* A run-once, self-freeing closure. */
typedef struct closure_s {
void (*f0) (void *);
} closure;
/* Run the closure *cl, and free it. */
void closure_run (closure *cl);
/* Fork a new thread running the closure *cl, which will be freed when the
thread exits. */
void closure_fork (closure *cl);
/* To create a closure, declare a closure constructor with the right function arguments.
For functions taking no arguments, use
CLOSURE_DECL_BODY0 (foo)
to generate the static routine:
static closure *closure_foo (void (*f) (void));
that will return a closure for any function *f that takes no argument.
For an 1-argument function, use
CLOSURE_DECL_BODY1 (foo, type)
to generate the static routine:
static closure *closure_foo (void (*f) (type), type x);
that will return a closure for any function taking a single argument of the
specified type.
For an 2-argument function, use
CLOSURE_DECL_BODY2 (foo, type0, type1)
to generate the static routine:
static closure *closure_foo (void (*f) (type0, type1), type0 x0, type1 x1);
that will return a closure for any function taking a "type0" argument, and
a "type1" argument.
And so on, up to 9 arguments.
For example, to make closures out of qsort():
// First, just once (per module) define:
// static closure *closure_qsort_args (
// void (*f) (void *, size_t, size_t, int (*)(const void *, const void *))
// void *x0, size_t x1, size_t x2, int (*x3)(const void *, const void *));
// by writing:
CLOSURE_DECL_BODY4 (qsort_args, void *, size_t, size_t, int (*)(const void *, const void *))
// Second, for each closure to be created, write something like this:
closure *cl = closure_qsort_args (array, n_elements, sizeof (array[0]), &elem_cmp);
// Then to run (and free) each closure:
closure_run (cl);
// This is like calling
// qsort (array, n_elements, sizeof (array[0]), &elem_cmp);
// free (cl);
*/
/* ------------------------------------------------------------------ */
/* Internal macro details follow. */
#define CLOSURE_S0(x,e) e
#define CLOSURE_S1(x,e) x##0
#define CLOSURE_S2(x,e) x##0, x##1
#define CLOSURE_S3(x,e) x##0, x##1, x##2
#define CLOSURE_S4(x,e) x##0, x##1, x##2, x##3
#define CLOSURE_S5(x,e) x##0, x##1, x##2, x##3, x##4
#define CLOSURE_S6(x,e) x##0, x##1, x##2, x##3, x##4, x##5
#define CLOSURE_S7(x,e) x##0, x##1, x##2, x##3, x##4, x##5, x##6
#define CLOSURE_S8(x,e) x##0, x##1, x##2, x##3, x##4, x##5, x##6, x##7
#define CLOSURE_S9(x,e) x##0, x##1, x##2, x##3, x##4, x##5, x##6, x##7, x##8
#define CLOSURE_P0(x,y,p,s,t)
#define CLOSURE_P1(x,y,p,s,t) p x##0 y##0 t
#define CLOSURE_P2(x,y,p,s,t) p x##0 y##0 s x##1 y##1 t
#define CLOSURE_P3(x,y,p,s,t) p x##0 y##0 s x##1 y##1 s x##2 y##2 t
#define CLOSURE_P4(x,y,p,s,t) p x##0 y##0 s x##1 y##1 s x##2 y##2 s x##3 y##3 t
#define CLOSURE_P5(x,y,p,s,t) p x##0 y##0 s x##1 y##1 s x##2 y##2 s x##3 y##3 s x##4 y##4 t
#define CLOSURE_P6(x,y,p,s,t) p x##0 y##0 s x##1 y##1 s x##2 y##2 s x##3 y##3 s x##4 y##4 s \
x##5 y##5 t
#define CLOSURE_P7(x,y,p,s,t) p x##0 y##0 s x##1 y##1 s x##2 y##2 s x##3 y##3 s x##4 y##4 s \
x##5 y##5 s x##6 y##6 t
#define CLOSURE_P8(x,y,p,s,t) p x##0 y##0 s x##1 y##1 s x##2 y##2 s x##3 y##3 s x##4 y##4 s \
x##5 y##5 s x##6 y##6 s x##7 y##7 t
#define CLOSURE_P9(x,y,p,s,t) p x##0 y##0 s x##1 y##1 s x##2 y##2 s x##3 y##3 s x##4 y##4 s \
x##5 y##5 s x##6 y##6 s x##7 y##7 s x##8 y##8 t
#define CLOSURE_COMMA_ ,
#define CLOSURE_SEMI_ ;
#define CLOSURE_BLANK_
#define CLOSURE_DECL_BODY_N_(name, n) \
struct closure_s_##name { \
void (*f0) (void *); /* must be first; matches closure. */ \
void (*f) (CLOSURE_S##n (closure_t_##name##_,void)); \
CLOSURE_P##n (closure_t_##name##_, a, CLOSURE_BLANK_, \
CLOSURE_SEMI_, CLOSURE_SEMI_) \
}; \
static void closure_f0_##name (void *v) { \
struct closure_s_##name *a = (struct closure_s_##name *) v; \
(*a->f) (CLOSURE_S##n (a->a,CLOSURE_BLANK_)); \
free (a); \
} \
static closure *closure_##name (void (*f) (CLOSURE_S##n (closure_t_##name##_,void)) \
CLOSURE_P##n (closure_t_##name##_, a, CLOSURE_COMMA_, \
CLOSURE_COMMA_, CLOSURE_BLANK_)) { \
struct closure_s_##name *cl = (struct closure_s_##name *) malloc (sizeof (*cl)); \
cl->f0 = &closure_f0_##name; \
cl->f = f; \
CLOSURE_P##n (cl->a, = a, CLOSURE_BLANK_, CLOSURE_SEMI_, CLOSURE_SEMI_) \
return ((closure *) cl); \
}
#define CLOSURE_DECL_BODY0(name) \
CLOSURE_DECL_BODY_N_ (name, 0)
#define CLOSURE_DECL_BODY1(name, t0) \
typedef t0 closure_t_##name##_0; \
CLOSURE_DECL_BODY_N_ (name, 1)
#define CLOSURE_DECL_BODY2(name, t0, t1) \
typedef t0 closure_t_##name##_0; \
typedef t1 closure_t_##name##_1; \
CLOSURE_DECL_BODY_N_ (name, 2)
#define CLOSURE_DECL_BODY3(name, t0, t1, t2) \
typedef t0 closure_t_##name##_0; \
typedef t1 closure_t_##name##_1; \
typedef t2 closure_t_##name##_2; \
CLOSURE_DECL_BODY_N_ (name, 3)
#define CLOSURE_DECL_BODY4(name, t0, t1, t2, t3) \
typedef t0 closure_t_##name##_0; \
typedef t1 closure_t_##name##_1; \
typedef t2 closure_t_##name##_2; \
typedef t3 closure_t_##name##_3; \
CLOSURE_DECL_BODY_N_ (name, 4)
#define CLOSURE_DECL_BODY5(name, t0, t1, t2, t3, t4) \
typedef t0 closure_t_##name##_0; \
typedef t1 closure_t_##name##_1; \
typedef t2 closure_t_##name##_2; \
typedef t3 closure_t_##name##_3; \
typedef t4 closure_t_##name##_4; \
CLOSURE_DECL_BODY_N_ (name, 5)
#define CLOSURE_DECL_BODY6(name, t0, t1, t2, t3, t4, t5) \
typedef t0 closure_t_##name##_0; \
typedef t1 closure_t_##name##_1; \
typedef t2 closure_t_##name##_2; \
typedef t3 closure_t_##name##_3; \
typedef t4 closure_t_##name##_4; \
typedef t5 closure_t_##name##_5; \
CLOSURE_DECL_BODY_N_ (name, 6)
#define CLOSURE_DECL_BODY7(name, t0, t1, t2, t3, t4, t5, t6) \
typedef t0 closure_t_##name##_0; \
typedef t1 closure_t_##name##_1; \
typedef t2 closure_t_##name##_2; \
typedef t3 closure_t_##name##_3; \
typedef t4 closure_t_##name##_4; \
typedef t5 closure_t_##name##_5; \
typedef t6 closure_t_##name##_6; \
CLOSURE_DECL_BODY_N_ (name, 7)
#define CLOSURE_DECL_BODY8(name, t0, t1, t2, t3, t4, t5, t6, t7) \
typedef t0 closure_t_##name##_0; \
typedef t1 closure_t_##name##_1; \
typedef t2 closure_t_##name##_2; \
typedef t3 closure_t_##name##_3; \
typedef t4 closure_t_##name##_4; \
typedef t5 closure_t_##name##_5; \
typedef t6 closure_t_##name##_6; \
typedef t7 closure_t_##name##_7; \
CLOSURE_DECL_BODY_N_ (name, 8)
#define CLOSURE_DECL_BODY9(name, t0, t1, t2, t3, t4, t5, t6, t7, t8) \
typedef t0 closure_t_##name##_0; \
typedef t1 closure_t_##name##_1; \
typedef t2 closure_t_##name##_2; \
typedef t3 closure_t_##name##_3; \
typedef t4 closure_t_##name##_4; \
typedef t5 closure_t_##name##_5; \
typedef t6 closure_t_##name##_6; \
typedef t7 closure_t_##name##_7; \
typedef t8 closure_t_##name##_8; \
CLOSURE_DECL_BODY_N_ (name, 9)
////////////////////////////////////////////////////////////////////////////////
// closure.c
void nsync_start_thread_ (void (*f) (void *), void *arg);
/* Run the closure *cl. */
void closure_run (closure *cl) {
(*cl->f0) (cl);
}
/* Run the closure (closure *), but wrapped to fix the type. */
static void closure_run_body (void *v) {
closure_run ((closure *)v);
}
void closure_fork (closure *cl) {
nsync_start_thread_ (&closure_run_body, cl);
}
////////////////////////////////////////////////////////////////////////////////
// atm_log.h
void nsync_atm_log_ (int c, void *p, uint32_t o, uint32_t n, const char *file, int line);
void nsync_atm_log_print_ (void);
////////////////////////////////////////////////////////////////////////////////
// atm_log.c
#ifndef NSYNC_ATM_LOG
#define NSYNC_ATM_LOG 0
#endif
struct atm_log {
uintptr_t i;
uintptr_t thd_id;
uintptr_t c;
void *p;
uintptr_t o;
uintptr_t n;
const char *file;
uintptr_t line;
};
#define LOG_N 14
static struct atm_log log_entries[1 << LOG_N];
static uint32_t log_i;
static pthread_mutex_t log_mu;
static pthread_key_t key;
static pthread_once_t once = PTHREAD_ONCE_INIT;
static void do_once (void) {
pthread_mutex_init (&log_mu, NULL);
pthread_key_create (&key, NULL);
}
static int thread_id;
void nsync_atm_log_ (int c, void *p, uint32_t o, uint32_t n, const char *file, int line) {
if (NSYNC_ATM_LOG) {
struct atm_log *e;
uint32_t i;
int *pthd_id;
int thd_id;
pthread_once (&once, &do_once);
pthd_id = (int *) pthread_getspecific (key);
pthread_mutex_lock (&log_mu);
i = log_i++;
if (pthd_id == NULL) {
thd_id = thread_id++;
pthd_id = (int *) malloc (sizeof (*pthd_id));
pthread_setspecific (key, pthd_id);
*pthd_id = thd_id;
} else {
thd_id = *pthd_id;
}
pthread_mutex_unlock (&log_mu);
e = &log_entries[i & ((1 << LOG_N) - 1)];
e->i = i;
e->thd_id = thd_id;
e->c = c;
e->p = p;
e->o = o;
e->n = n;
e->file = file;
e->line = line;
}
}
void nsync_atm_log_print_ (void) {
if (NSYNC_ATM_LOG) {
uint32_t i;
pthread_once (&once, &do_once);
pthread_mutex_lock (&log_mu);
for (i = 0; i != (1 << LOG_N); i++) {
struct atm_log *e = &log_entries[i];
if (e->file != 0) {
fprintf (stderr, "%6lx %3d %c p %16p o %8x n %8x %10s:%d\n",
(unsigned long) e->i,
(int) e->thd_id,
e->c <= ' '? '?' : (char)e->c,
e->p,
(uint32_t) e->o,
(uint32_t) e->n,
e->file,
(int) e->line);
}
}
pthread_mutex_unlock (&log_mu);
}
}
////////////////////////////////////////////////////////////////////////////////
// testing.c
struct testing_base_s {
int flags; /* flags from testing_new(); r/o after init */
int parallelism; /* max parallelism to use; r/o after init */
FILE *fp; /* where to send output; pointer is r/o after init */
int argn; /* first arg not processed by testing_new(); r/o after init */
int argc; /* argc passed to testing_new(); r/o after init */
char **argv; /* argv passed to testing_new(); r/o after init */
char *prog; /* name of programme, from argv[0] */
int suppress_header; /* supress hreader on benchmarks */
int run_tests; /* whether to run tests */
int run_benchmarks; /* whether to run benchmarks */
int benchmarks_running; /* and benchmarks are now running */
char *include_pat; /* ,- or |-separated substrings of tests to include */
char *exclude_pat; /* ,- or |-separated substrings of tests to exclude */
int longshort; /* 0 normal, -1 short, 1 long */
int verbose; /* 0 normal; 1 verbose output */
nsync_mu testing_mu; /* protects fields below */
int is_uniprocessor; /* whether the system is a uniprocessor */
nsync_dll_list_ children; /* list of testing_s structs whose base is this testing_base_s */
int child_count; /* count of testing_s structs whose base is this testing_base_s */
int exit_status; /* final exit status */
};
struct testing_s {
struct testing_base_s *base; /* r/o after init */
int test_status; /* status; merged into common->exit_status */
int n; /* benchmark iteration count */
nsync_atomic_uint32_ partial_line; /* whether partial test banner emitted last*/
FILE *fp; /* where to output; merged into common->fp if != to it */
nsync_time start_time; /* timer start time; for benchmarks */
nsync_time stop_time; /* when the timer was stopped; for benchmarks */
void (*f) (testing); /* test function to run */
const char *name; /* name of test */
nsync_dll_element_ siblings; /* part of list of siblings */
};
/* Output the header for benchmarks. */
static void output_header (FILE *fp, const char *prog) {
int i;
int hdrlen = fprintf (fp, "%-10s%-40s %9s %8s %8s %8s\n", "Benchmark", prog, "ops", "time",
"ops/sec", "time/op");
for (i = 1; i < hdrlen; i++) {
putc ('-', fp);
}
putc ('\n', fp);
fflush (fp);
}
/* Process a single flag. *pargn is main's argn */
static void process_flag (testing_base tb, int *pargn, int argc, char *argv[], int flag,
const char *arg) {
switch (flag) {
case 'b':
tb->run_benchmarks = 1;
break;
case 'B':
tb->run_benchmarks = 1;
tb->run_tests = 0;
break;
case 'H':
output_header (stdout, "");
exit (0);
case 'h':
tb->suppress_header = 1;
break;
case 'l':
tb->longshort++;
break;
case 'm':
if (*pargn + 1 == argc) {
fprintf (stderr, "%s: -m flag expects ,- or |-separated strings\n",
argv[0]);
exit (2);
}
tb->include_pat = argv[++*pargn];
break;
case 'n':
if (*pargn + 1 == argc || atoi (argv[1 + *pargn]) < 1) {
fprintf (stderr, "%s: -n flag expects parallelism value >= 1\n", argv[0]);
exit (2);
}
tb->parallelism = atoi (argv[++*pargn]);
break;
case 's':
tb->longshort--;
break;
case 'v':
tb->verbose = 1;
break;
case 'x':
if (*pargn + 1 == argc) {
fprintf (stderr, "%s: -x flag expects ,- or |-separated strings\n",
argv[0]);
exit (2);
}
tb->exclude_pat = argv[++*pargn];
break;
default:
fprintf (stderr, "%s: unrecognized flag '%c' in arg %d: \"%s\"\n", argv[0], flag,
*pargn, arg);
exit (2);
}
}
testing_base testing_new (int argc, char *argv[], int flags) {
static const char sep[] = { '/', '\\' };
int i;
int argn;
testing_base tb = (testing_base)malloc (sizeof (*tb));
memset ((void *) tb, 0, sizeof (*tb));
tb->flags = flags;
tb->fp = stderr;
tb->argc = argc;
tb->argv = argv;
tb->parallelism = 1;
tb->run_tests = 1;
tb->is_uniprocessor = -1;
tb->prog = tb->argv[0];
for (i = 0; i != sizeof (sep) / sizeof (sep[0]); i++) {
char *last = strrchr (tb->prog, sep[i]);
if (last != NULL) {
tb->prog = last + 1;
}
}
for (argn = 1; argn != argc && argv[argn][0] == '-' &&
strcmp (argv[argn], "--") != 0; argn++) {
const char *arg = argv[argn];
const char *f;
for (f = &arg[1]; *f != 0; f++) {
process_flag (tb, &argn, argc, argv, *f, arg);
}
}
tb->argn = argn + (argn != argc && strcmp (argv[argn], "--") == 0);
return (tb);
}
int testing_verbose (testing t) {
return (t->base->verbose);
}
int testing_longshort (testing t) {
return (t->base->longshort);
}
int testing_n (testing t) {
return (t->n);
}
int testing_base_argn (testing_base tb) {
return (tb->argn);
}
/* Return whether *(int *)v is zero. Used with nsync_mu_wait(). */
static int int_is_zero (const void *v) {
return (*(const int *)v == 0);
}
int testing_base_exit (testing_base tb) {
int exit_status;
nsync_mu_lock (&tb->testing_mu);
nsync_mu_wait (&tb->testing_mu, &int_is_zero, &tb->child_count, NULL);
exit_status = tb->exit_status;
nsync_mu_unlock (&tb->testing_mu);
free (tb);
exit (exit_status);
return (exit_status);
}
/* Cleanup code used after running either a test or a benchmark,
called at the end of run_test() and run_benchmark(). */
static void finish_run (testing t) {
testing_base tb = t->base;
fflush (t->fp);
nsync_mu_lock (&tb->testing_mu);
if (t->fp != tb->fp) {
int c;
rewind (t->fp);
while ((c = getc (t->fp)) != EOF) {
putc (c, tb->fp);
}
fclose (t->fp);
fflush (tb->fp);
}
if (tb->exit_status < t->test_status) {
tb->exit_status = t->test_status;
}
tb->children = nsync_dll_remove_ (tb->children, &t->siblings);
tb->child_count--;
nsync_mu_unlock (&tb->testing_mu);
free (t);
}
/* Run the test (*t->f)(t), and report on t->fp how long it took and its final
status, which is set to non-zero if the test reported errors. */
static void run_test (testing t) {
testing_base tb = t->base;
char *elapsed_str = 0;
fprintf (t->fp, "%-25s %-45s ", tb->prog, t->name);
fflush (t->fp);
ATM_STORE (&t->partial_line, 1);
t->test_status = 0;
t->n = 0;
t->stop_time = nsync_time_zero;
t->start_time = nsync_time_now ();
(*t->f) (t);
elapsed_str = nsync_time_str (nsync_time_sub (nsync_time_now (), t->start_time), 2);
if (!ATM_LOAD (&t->partial_line)) {
fprintf (t->fp, "%-25s %-45s %s %8s\n", tb->prog, t->name,
t->test_status != 0? "failed": "passed", elapsed_str);
} else {
fprintf (t->fp, "%s %8s\n", t->test_status != 0? "failed": "passed", elapsed_str);
}
ATM_STORE (&t->partial_line, 0);
fflush (t->fp);
free (elapsed_str);
finish_run (t);
}
/* Run the benchmark (*t->f)(t) repeatedly, specifying successively greater
numbers of iterations, measuring how long it takes each time. Eventually,
it takes long enough to get a reasonable estimate of how long each iteration
takes, which is reported on t->fp. */
static void run_benchmark (testing t) {
char *elapsed_str = 0;
char *time_per_op_str = 0;
double elapsed;
int n = 1;
double target = 2.0;
int longshort = testing_longshort (t);
if (longshort < 0) {
target = 1e-3 * (2000 >> -longshort);
} else if (longshort > 0) {
target = 1e-3 * (2000 << longshort);
}
do {
int32_t mul;
t->test_status = 0;
t->n = n;
t->stop_time = nsync_time_zero;
t->start_time = nsync_time_now ();
(*t->f) (t);
elapsed = nsync_time_to_dbl (nsync_time_sub (nsync_time_now (), t->start_time));
if (elapsed < 1e-1) {
elapsed = 1e-1;
}
mul = (int32_t) (target / elapsed);
while (elapsed * mul * 4 < target * 5) {
mul++;
}
if (mul > 1 && elapsed * mul * 2 < target * 3 && n < INT_MAX / mul) {
n *= mul;
} else if (n < INT_MAX / 2) {
n *= 2;
}
} while (t->test_status == 0 && elapsed < target && n != t->n);
elapsed_str = nsync_time_str (nsync_time_from_dbl (elapsed), 2);
time_per_op_str = nsync_time_str (nsync_time_from_dbl (elapsed / t->n), 2);
fprintf (t->fp, "%-50s %9d %8s %8.2g %8s%s\n", t->name, t->n, elapsed_str,
((double)t->n) / elapsed, time_per_op_str,
t->test_status != 0 ? " *** failed ***" : "");
free (elapsed_str);
free (time_per_op_str);
finish_run (t);
}
CLOSURE_DECL_BODY1 (testing, testing)
/* Return whether there's a "spare thread"; that is, whether the current count
of child threads is less than the allowed parallelism. */
static int spare_thread (const void *v) {
const_testing_base tb = (const_testing_base) v;
return (tb->child_count < tb->parallelism);
}
/* Return whether nul-terminated string str[] contains a string listed in
comma-separated (or vertical bar-separted) strings in nul-terminated string
pat[]. A dollar at the end of a string in pat[] matches the end of
string in str[]. */
static int match (const char *pat, const char *str) {
static const char seps[] = ",|";
int found = 0;
char Xbuf[128];
int m = sizeof (Xbuf) - 1;
char *mbuf = NULL;
char *buf = Xbuf;
int i = 0;
while (!found && pat[i] != '\0') {
int blen = strcspn (&pat[i], seps);
int e = i + blen;
if (blen > m) {
m = blen + 128;
buf = mbuf = (char *) realloc (mbuf, m + 1);
}
memcpy (buf, &pat[i], blen);
buf[blen] = '\0';
if (blen > 0 && buf[blen - 1] == '$') {
int slen = strlen (str);
buf[--blen] = 0;
found = (slen >= blen &&
strcmp (&str[slen-blen], buf) == 0);
} else {
found = (strstr (str, buf) != NULL);
}
i = e + strspn (&pat[e], seps);
}
free (mbuf);
return (found);
}
void testing_run_ (testing_base tb, void (*f) (testing t), const char *name, int is_benchmark) {
int exit_status;
nsync_mu_lock (&tb->testing_mu);
exit_status = tb->exit_status;
nsync_mu_unlock (&tb->testing_mu);
if (exit_status < 2 &&
(!is_benchmark || tb->run_benchmarks) &&
(is_benchmark || tb->run_tests) &&
(tb->include_pat == NULL || match (tb->include_pat, name)) &&
(tb->exclude_pat == NULL || !match (tb->exclude_pat, name))) {
testing t = (testing) malloc (sizeof (*t));
memset ((void *) t, 0, sizeof (*t));
nsync_dll_init_ (&t->siblings, t);
t->base = tb;
t->f = f;
t->name = name;
if (tb->parallelism == 1) {
t->fp = tb->fp;
} else {
t->fp = tmpfile ();
}
if (!is_benchmark) {
if (tb->benchmarks_running) {
nsync_mu_lock (&tb->testing_mu);
nsync_mu_wait (&tb->testing_mu, &int_is_zero, &tb->child_count, NULL);
nsync_mu_unlock (&tb->testing_mu);
tb->benchmarks_running = 0;
}
nsync_mu_lock (&tb->testing_mu);
nsync_mu_wait (&tb->testing_mu, &spare_thread, tb, NULL);
tb->child_count++;
tb->children = nsync_dll_make_last_in_list_ (tb->children, &t->siblings);
nsync_mu_unlock (&tb->testing_mu);
closure_fork (closure_testing (&run_test, t));
} else {
if (!tb->benchmarks_running) {
nsync_mu_lock (&tb->testing_mu);
nsync_mu_wait (&tb->testing_mu, &int_is_zero, &tb->child_count, NULL);
nsync_mu_unlock (&tb->testing_mu);
if (!tb->suppress_header) {
output_header (tb->fp, tb->prog);
}
tb->benchmarks_running = 1;
}
nsync_mu_lock (&tb->testing_mu);
nsync_mu_wait (&tb->testing_mu, &spare_thread, tb, NULL);
tb->child_count++;
tb->children = nsync_dll_make_last_in_list_ (tb->children, &t->siblings);
nsync_mu_unlock (&tb->testing_mu);
closure_fork (closure_testing (&run_benchmark, t));
}
}
}
/* Used to decide whether the test is running on a uniprocessor. */
struct is_uniprocessor_s {
double count; /* count of iterations while *state==1 */
nsync_atomic_uint32_ done; /* set to 1 when thread finishes */
char dummy[256]; /* so structs don't share cache line */
};
/* An anciliary thread that waits until *state is 1, then increments s->count
while *state stays 1, and then sets s->done to 1 before exiting. */
static void uniprocessor_check (nsync_atomic_uint32_ *state, struct is_uniprocessor_s *s) {
IGNORE_RACES_START ();
while (ATM_LOAD_ACQ (state) != 1) {
}
while (ATM_LOAD_ACQ (state) == 1) {
s->count++;
}
ATM_STORE_REL (&s->done, 1);
IGNORE_RACES_END ();
}
CLOSURE_DECL_BODY2 (uniprocessor_check, nsync_atomic_uint32_ *, struct is_uniprocessor_s *)
/* Return whether the test is running on a uniprocessor.
Some of the tests rely on interleaving of actions between threads.
Particular interleavings are much less likely on uniprocessors, so the tests
do not run, or do not declare an error if the system is a uniprocessor.
Operating systems vary significantly in how one may ask how many procerssors
are present, so we use a heuristic based on comparing the timing of a single
thread, and two concurrent threads. */
int testing_is_uniprocessor (testing t) {
int is_uniprocessor;
nsync_mu_lock (&t->base->testing_mu);
is_uniprocessor = t->base->is_uniprocessor;
if (is_uniprocessor == -1) {
int i;
struct is_uniprocessor_s s[3];
nsync_atomic_uint32_ state;
for (i = 0; i != 3; i++) {
s[i].count = 0.0;
s[i].done = 0;
}
ATM_STORE_REL (&state, 0);
closure_fork (closure_uniprocessor_check (&uniprocessor_check, &state, &s[0]));
nsync_time_sleep (nsync_time_ms (100));
ATM_STORE_REL (&state, 1);
nsync_time_sleep (nsync_time_ms (400));
ATM_STORE_REL (&state, 2);
while (!ATM_LOAD_ACQ (&s[0].done)) {
}
ATM_STORE_REL (&state, 0);
closure_fork (closure_uniprocessor_check (&uniprocessor_check, &state, &s[1]));
closure_fork (closure_uniprocessor_check (&uniprocessor_check, &state, &s[2]));
nsync_time_sleep (nsync_time_ms (100));
ATM_STORE_REL (&state, 1);
nsync_time_sleep (nsync_time_ms (400));
ATM_STORE_REL (&state, 2);
while (!ATM_LOAD_ACQ (&s[1].done) || !ATM_LOAD_ACQ (&s[2].done)) {
}
t->base->is_uniprocessor = ((s[1].count + s[2].count) / s[0].count) < 1.7;
is_uniprocessor = t->base->is_uniprocessor;
}
nsync_mu_unlock (&t->base->testing_mu);
return (is_uniprocessor);
}
void testing_stop_timer (testing t) {
if (nsync_time_cmp (t->stop_time, nsync_time_zero) != 0) {
abort ();
}
t->stop_time = nsync_time_now ();
}
void testing_start_timer (testing t) {
if (nsync_time_cmp (t->stop_time, nsync_time_zero) == 0) {
abort ();
}
t->start_time = nsync_time_add (t->start_time,
nsync_time_sub (nsync_time_now (), t->stop_time));
t->stop_time = nsync_time_zero;
}
void testing_error_ (testing t, int test_status, const char *file, int line, char *msg) {
int len = strlen (msg);
int addnl = (len == 0 || msg[len - 1] != '\n');
if (t->test_status < test_status) {
t->test_status = test_status;
}
if (ATM_LOAD (&t->partial_line)) {
ATM_STORE (&t->partial_line, 0);
fprintf (t->fp, "\n%s: %s:%d: %s%s",
test_status == 2? "fatal": test_status == 1? "error": "info", file, line, msg,
addnl? "\n": "");
} else {
fprintf (t->fp, "%s: %s:%d: %s%s",
test_status == 2? "fatal": test_status == 1? "error": "info", file, line, msg,
addnl? "\n": "");
}
free (msg);
}
void nsync_panic_(const char *);
/* Abort after printing the nul-terminated string s[]. */
void testing_panic (const char *s) {
nsync_atm_log_print_ ();
nsync_panic_ (s);
}
////////////////////////////////////////////////////////////////////////////////
// mu_test.c
/* The state shared between the threads in each of the tests below. */
typedef struct test_data_s {
testing t;
-521
View File
@@ -1,521 +0,0 @@
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│
│vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright (c) 2010, 2012 David E. O'Brien │
│ Copyright (c) 1980, 1992, 1993 │
│ The Regents of the University of California. All rights reserved. │
│ │
│ Redistribution and use in source and binary forms, with or without │
│ modification, are permitted provided that the following conditions │
│ are met: │
│ 1. Redistributions of source code must retain the above copyright │
│ notice, this list of conditions and the following disclaimer. │
│ 2. Redistributions in binary form must reproduce the above copyright │
│ notice, this list of conditions and the following disclaimer in the │
│ documentation and/or other materials provided with the distribution. │
│ 3. Neither the name of the University nor the names of its contributors │
│ may be used to endorse or promote products derived from this software │
│ without specific prior written permission. │
│ │
│ THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND │
│ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE │
│ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE │
│ ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE │
│ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL │
│ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS │
│ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) │
│ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT │
│ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY │
│ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF │
│ SUCH DAMAGE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/stat.h"
#include "libc/calls/struct/termios.h"
#include "libc/calls/struct/timeval.h"
#include "libc/calls/struct/winsize.h"
#include "libc/calls/termios.h"
#include "libc/calls/weirdtypes.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/bswap.h"
#include "libc/log/bsd.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/paths.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/select.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/fileno.h"
#include "libc/sysv/consts/s.h"
#include "libc/sysv/consts/termios.h"
#include "libc/time/time.h"
#include "third_party/getopt/getopt.h"
// clang-format off
/**
* @fileoverview Terminal Screencast Recorder / Player, e.g.
*
* make o//examples/script.com
* o//examples/script.com -r
* # type stuff..
* # CTRL-D
* o//examples/script.com -p typescript
*
* @note works on Linux, OpenBSD, NetBSD, FreeBSD, MacOS
* @see https://asciinema.org/
*/
asm(".ident\t\"\\n\\n\
FreeBSD Script (BSD-3 License)\\n\
Copyright (c) 2010, 2012 David E. O'Brien\\n\
Copyright (c) 1980, 1992, 1993\\n\
\tThe Regents of the University of California.\\n\
\tAll rights reserved.\"");
asm(".include \"libc/disclaimer.inc\"");
#define DEF_BUF 65536
struct stamp {
uint64_t scr_len; /* amount of data */
uint64_t scr_sec; /* time it arrived in seconds... */
uint32_t scr_usec; /* ...and microseconds */
uint32_t scr_direction; /* 'i', 'o', etc (also indicates endianness) */
};
static FILE *fscript;
static int master, slave;
static int child;
static const char *fname;
static char *fmfname;
static int qflg, ttyflg;
static int usesleep, rawout, showexit;
static struct termios tt;
static void done(int) wontreturn;
static void doshell(char **);
static void finish(void);
static void record(FILE *, char *, size_t, int);
static void consume(FILE *, off_t, char *, int);
static void playback(FILE *) wontreturn;
static void usage(void);
int
main(int argc, char *argv[])
{
int cc;
struct termios rtt, stt;
struct winsize win;
struct timeval tv, *tvp;
time_t tvec, start;
static char obuf[BUFSIZ];
static char ibuf[BUFSIZ];
fd_set rfd;
int aflg, Fflg, kflg, pflg, ch, k, n;
int flushtime, readstdin;
int fm_fd, fm_log;
aflg = Fflg = kflg = pflg = 0;
usesleep = 1;
rawout = 0;
flushtime = 30;
fm_fd = -1; /* Shut up stupid "may be used uninitialized" GCC
warning. (not needed w/clang) */
showexit = 0;
while ((ch = getopt(argc, argv, "adeFfkpqrt:")) != -1)
switch(ch) {
case 'a':
aflg = 1;
break;
case 'd':
usesleep = 0;
break;
case 'e': /* Default behavior, accepted for linux compat */
break;
case 'F':
Fflg = 1;
break;
case 'k':
kflg = 1;
break;
case 'p':
pflg = 1;
break;
case 'q':
qflg = 1;
break;
case 'r':
rawout = 1;
break;
case 't':
flushtime = atoi(optarg);
if (flushtime < 0)
err(1, "invalid flush time %d", flushtime);
break;
case '?':
default:
usage();
}
argc -= optind;
argv += optind;
if (argc > 0) {
fname = argv[0];
argv++;
argc--;
} else
fname = "typescript";
if ((fscript = fopen(fname, pflg ? "r" : aflg ? "a" : "w")) == NULL)
err(1, "%s", fname);
if (pflg)
playback(fscript);
if (tcgetattr(STDIN_FILENO, &tt) == -1 ||
ioctl(STDIN_FILENO, TIOCGWINSZ, &win) == -1) {
if (errno != ENOTTY) /* For debugger. */
err(1, "tcgetattr/ioctl");
if (openpty(&master, &slave, NULL, NULL, NULL) == -1)
err(1, "openpty");
} else {
if (openpty(&master, &slave, NULL, &tt, &win) == -1)
err(1, "openpty");
ttyflg = 1;
}
if (rawout)
record(fscript, NULL, 0, 's');
if (!qflg) {
tvec = time(NULL);
printf("Script started, output file is %s\n", fname);
if (!rawout) {
fprintf(fscript, "Script started on %s",
ctime(&tvec));
if (argv[0]) {
showexit = 1;
fprintf(fscript, "Command: ");
for (k = 0 ; argv[k] ; ++k)
fprintf(fscript, "%s%s", k ? " " : "",
argv[k]);
fprintf(fscript, "\n");
}
}
fflush(fscript);
}
if (ttyflg) {
rtt = tt;
cfmakeraw(&rtt);
rtt.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &rtt);
}
child = fork();
if (child < 0) {
warn("fork");
done(1);
}
if (child == 0) {
doshell(argv);
}
close(slave);
start = tvec = time(0);
readstdin = 1;
for (;;) {
FD_ZERO(&rfd);
FD_SET(master, &rfd);
if (readstdin)
FD_SET(STDIN_FILENO, &rfd);
if (!readstdin && ttyflg) {
tv.tv_sec = 1;
tv.tv_usec = 0;
tvp = &tv;
readstdin = 1;
} else if (flushtime > 0) {
tv.tv_sec = flushtime - (tvec - start);
tv.tv_usec = 0;
tvp = &tv;
} else {
tvp = NULL;
}
n = select(master + 1, &rfd, 0, 0, tvp);
if (n < 0 && errno != EINTR)
break;
if (n > 0 && FD_ISSET(STDIN_FILENO, &rfd)) {
cc = read(STDIN_FILENO, ibuf, BUFSIZ);
if (cc < 0)
break;
if (cc == 0) {
if (tcgetattr(master, &stt) == 0 &&
(stt.c_lflag & ICANON) != 0) {
write(master, &stt.c_cc[VEOF], 1);
}
readstdin = 0;
}
if (cc > 0) {
if (rawout)
record(fscript, ibuf, cc, 'i');
write(master, ibuf, cc);
if (kflg && tcgetattr(master, &stt) >= 0 &&
((stt.c_lflag & ECHO) == 0)) {
fwrite(ibuf, 1, cc, fscript);
}
}
}
if (n > 0 && FD_ISSET(master, &rfd)) {
cc = read(master, obuf, sizeof (obuf));
if (cc <= 0)
break;
write(STDOUT_FILENO, obuf, cc);
if (rawout)
record(fscript, obuf, cc, 'o');
else
fwrite(obuf, 1, cc, fscript);
}
tvec = time(0);
if (tvec - start >= flushtime) {
fflush(fscript);
start = tvec;
}
if (Fflg)
fflush(fscript);
}
finish();
done(0);
}
static void
usage(void)
{
fprintf(stderr,
"usage: script [-adfkpqr] [-t time] [file [command ...]]\n");
exit(1);
}
static void
finish(void)
{
int e, status;
if (waitpid(child, &status, 0) == child) {
if (WIFEXITED(status))
e = WEXITSTATUS(status);
else if (WIFSIGNALED(status))
e = WTERMSIG(status);
else /* can't happen */
e = 1;
done(e);
}
}
static void
doshell(char **av)
{
const char *shell;
shell = getenv("SHELL");
if (shell == NULL)
shell = _PATH_BSHELL;
close(master);
fclose(fscript);
free(fmfname);
login_tty(slave);
setenv("SCRIPT", fname, 1);
if (av[0]) {
execvp(av[0], av);
warn("%s", av[0]);
} else {
execl(shell, shell, "-i", 0);
warn("%s", shell);
}
exit(1);
}
static void
done(int eno)
{
time_t tvec;
if (ttyflg)
tcsetattr(STDIN_FILENO, TCSAFLUSH, &tt);
tvec = time(NULL);
if (rawout)
record(fscript, NULL, 0, 'e');
if (!qflg) {
if (!rawout) {
if (showexit)
fprintf(fscript, "\nCommand exit status:"
" %d", eno);
fprintf(fscript,"\nScript done on %s",
ctime(&tvec));
}
printf("\nScript done, output file is %s\n", fname);
}
fclose(fscript);
close(master);
exit(eno);
}
static void
record(FILE *fp, char *buf, size_t cc, int direction)
{
struct iovec iov[2];
struct stamp stamp;
struct timeval tv;
gettimeofday(&tv, NULL);
stamp.scr_len = cc;
stamp.scr_sec = tv.tv_sec;
stamp.scr_usec = tv.tv_usec;
stamp.scr_direction = direction;
iov[0].iov_len = sizeof(stamp);
iov[0].iov_base = &stamp;
iov[1].iov_len = cc;
iov[1].iov_base = buf;
if (writev(fileno(fp), &iov[0], 2) == -1)
err(1, "writev");
}
static void
consume(FILE *fp, off_t len, char *buf, int reg)
{
size_t l;
if (reg) {
if (fseeko(fp, len, SEEK_CUR) == -1)
err(1, NULL);
}
else {
while (len > 0) {
l = MIN(DEF_BUF, len);
if (fread(buf, sizeof(char), l, fp) != l)
err(1, "cannot read buffer");
len -= l;
}
}
}
#define swapstamp(stamp) do { \
if (stamp.scr_direction > 0xff) { \
stamp.scr_len = bswap_64(stamp.scr_len); \
stamp.scr_sec = bswap_64(stamp.scr_sec); \
stamp.scr_usec = bswap_32(stamp.scr_usec); \
stamp.scr_direction = bswap_32(stamp.scr_direction); \
} \
} while (0/*CONSTCOND*/)
static void
termset(void)
{
struct termios traw;
if (tcgetattr(STDOUT_FILENO, &tt) == -1) {
if (errno != ENOTTY) /* For debugger. */
err(1, "tcgetattr");
return;
}
ttyflg = 1;
traw = tt;
cfmakeraw(&traw);
traw.c_lflag |= ISIG;
tcsetattr(STDOUT_FILENO, TCSANOW, &traw);
}
static void
termreset(void)
{
if (ttyflg) {
tcsetattr(STDOUT_FILENO, TCSADRAIN, &tt);
ttyflg = 0;
}
}
static void
playback(FILE *fp)
{
struct timespec tsi, tso;
struct stamp stamp;
struct stat pst;
static char buf[DEF_BUF];
off_t nread, save_len;
size_t l;
time_t tclock;
int reg;
if (fstat(fileno(fp), &pst) == -1)
err(1, "fstat failed");
reg = S_ISREG(pst.st_mode);
for (nread = 0; !reg || nread < pst.st_size; nread += save_len) {
if (fread(&stamp, sizeof(stamp), 1, fp) != 1) {
if (reg)
err(1, "reading playback header");
else
break;
}
swapstamp(stamp);
save_len = sizeof(stamp);
if (reg && stamp.scr_len >
(uint64_t)(pst.st_size - save_len) - nread)
errx(1, "invalid stamp");
save_len += stamp.scr_len;
tclock = stamp.scr_sec;
tso.tv_sec = stamp.scr_sec;
tso.tv_nsec = stamp.scr_usec * 1000;
switch (stamp.scr_direction) {
case 's':
if (!qflg)
printf("Script started on %s",
ctime(&tclock));
tsi = tso;
consume(fp, stamp.scr_len, buf, reg);
termset();
atexit(termreset);
break;
case 'e':
termreset();
if (!qflg)
printf("\nScript done on %s",
ctime(&tclock));
consume(fp, stamp.scr_len, buf, reg);
break;
case 'i':
/* throw input away */
consume(fp, stamp.scr_len, buf, reg);
break;
case 'o':
tsi.tv_sec = tso.tv_sec - tsi.tv_sec;
tsi.tv_nsec = tso.tv_nsec - tsi.tv_nsec;
if (tsi.tv_nsec < 0) {
tsi.tv_sec -= 1;
tsi.tv_nsec += 1000000000;
}
if (usesleep)
nanosleep(&tsi, NULL);
tsi = tso;
while (stamp.scr_len > 0) {
l = MIN(DEF_BUF, stamp.scr_len);
if (fread(buf, sizeof(char), l, fp) != l)
err(1, "cannot read buffer");
write(STDOUT_FILENO, buf, l);
stamp.scr_len -= l;
}
break;
default:
errx(1, "invalid direction");
}
}
fclose(fp);
exit(0);
}
-100
View File
@@ -1,100 +0,0 @@
SCRIPT(1) Cosmopolitan General Commands Manual SCRIPT(1)
𝐍𝐀𝐌𝐄
𝘀𝗰𝗿𝗶𝗽𝘁 — make typescript of terminal session
𝐒𝐘𝐍𝐎𝐏𝐒𝐈𝐒
𝘀𝗰𝗿𝗶𝗽𝘁 [-𝗮𝗱𝗲𝗳𝗸𝗽𝗾𝗿] [-𝐅 p̲i̲p̲e̲] [-𝘁 t̲i̲m̲e̲] [f̲i̲l̲e̲ [c̲o̲m̲m̲a̲n̲d̲ .̲.̲.̲]]
𝐃𝐄𝐒𝐂𝐑𝐈𝐏𝐓𝐈𝐎𝐍
The 𝘀𝗰𝗿𝗶𝗽𝘁 utility makes a typescript of everything printed on your termi‐
nal. It is useful for students who need a hardcopy record of an interac‐
tive session as proof of an assignment, as the typescript file can be
printed out later with lpr(1).
If the argument f̲i̲l̲e̲ is given, 𝘀𝗰𝗿𝗶𝗽𝘁 saves all dialogue in f̲i̲l̲e̲. If no
file name is given, the typescript is saved in the file t̲y̲p̲e̲s̲c̲r̲i̲p̲t̲.
If the argument c̲o̲m̲m̲a̲n̲d̲ is given, 𝘀𝗰𝗿𝗶𝗽𝘁 will run the specified command
with an optional argument vector instead of an interactive shell.
The following options are available:
-𝗮 Append the output to f̲i̲l̲e̲ or t̲y̲p̲e̲s̲c̲r̲i̲p̲t̲, retaining the prior con‐
tents.
-𝗱 When playing back a session with the -𝗽 flag, do not sleep between
records when playing back a timestamped session.
-𝗲 Accepted for compatibility with u̲t̲i̲l̲-̲l̲i̲n̲u̲x̲ 𝘀𝗰𝗿𝗶𝗽𝘁. The child com‐
mand exit status is always the exit status of 𝘀𝗰𝗿𝗶𝗽𝘁.
-𝐅 p̲i̲p̲e̲
Immediately flush output after each write. This will allow a user
to create a named pipe using mkfifo(1) and another user may watch
the live session using a utility like cat(1).
-𝗸 Log keys sent to the program as well as output.
-𝗽 Play back a session recorded with the -𝗿 flag in real time.
-𝗾 Run in quiet mode, omit the start, stop and command status mes‐
sages.
-𝗿 Record a session with input, output, and timestamping.
-𝘁 t̲i̲m̲e̲
Specify the interval at which the script output file will be
flushed to disk, in seconds. A value of 0 causes 𝘀𝗰𝗿𝗶𝗽𝘁 to flush
after every character I/O event. The default interval is 30 sec‐
onds.
The script ends when the forked shell (or command) exits (a c̲o̲n̲t̲r̲o̲l̲-̲D̲ to
exit the Bourne shell (sh(1)), and e̲x̲i̲t̲, l̲o̲g̲o̲u̲t̲ or c̲o̲n̲t̲r̲o̲l̲-̲D̲ (if i̲g̲n̲o̲r̲e̲e̲o̲f̲
is not set) for the C-shell, csh(1)).
Certain interactive commands, such as vi(1), create garbage in the type‐
script file. The 𝘀𝗰𝗿𝗶𝗽𝘁 utility works best with commands that do not ma‐
nipulate the screen. The results are meant to emulate a hardcopy terminal,
not an addressable one.
𝐄𝐍𝐕𝐈𝐑𝐎𝐍𝐌𝐄𝐍𝐓
The following environment variables are utilized by 𝘀𝗰𝗿𝗶𝗽𝘁:
SCRIPT
The SCRIPT environment variable is added to the sub-shell. If
SCRIPT already existed in the users environment, its value is over‐
written within the sub-shell. The value of SCRIPT is the name of
the t̲y̲p̲e̲s̲c̲r̲i̲p̲t̲ file.
SHELL If the variable SHELL exists, the shell forked by 𝘀𝗰𝗿𝗶𝗽𝘁 will be
that shell. If SHELL is not set, the Bourne shell is assumed.
(Most shells set this variable automatically).
𝐒𝐄𝐄 𝐀𝐋𝐒𝐎
csh(1) (for the h̲i̲s̲t̲o̲r̲y̲ mechanism)
𝐇𝐈𝐒𝐓𝐎𝐑𝐘
The 𝘀𝗰𝗿𝗶𝗽𝘁 command appeared in 3.0BSD.
The -𝗱, -𝗽 and -𝗿 options first appeared in NetBSD 2.0 and were ported to
FreeBSD 9.2.
𝐁𝐔𝐆𝐒
The 𝘀𝗰𝗿𝗶𝗽𝘁 utility places 𝗲𝘃𝗲𝗿𝘆𝘁𝗵𝗶𝗻𝗴 in the log file, including linefeeds
and backspaces. This is not what the naive user expects.
It is not possible to specify a command without also naming the script file
because of argument parsing compatibility issues.
When running in -𝗸 mode, echo cancelling is far from ideal. The slave ter‐
minal mode is checked for ECHO mode to check when to avoid manual echo log‐
ging. This does not work when the terminal is in a raw mode where the pro‐
gram being run is doing manual echo.
If 𝘀𝗰𝗿𝗶𝗽𝘁 reads zero bytes from the terminal, it switches to a mode when it
only attempts to read once a second until there is data to read. This pre‐
vents 𝘀𝗰𝗿𝗶𝗽𝘁 from spinning on zero-byte reads, but might cause a 1-second
delay in processing of user input.
BSD September 1, 2020 BSD
+358 -437
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -49,12 +49,12 @@ int main(int argc, char *argv[]) {
printf("res = %d?\n", res);
return -1;
}
printf("\e[92;44mHello World!\e[0m %.19Lg\n", atan2l(x, y));
printf("Hello World! %.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 \e[97m%`'.*s\e[0m\r\n", res, buf);
printf("got %`'.*s\r\n", res, buf);
}
}
}
-33
View File
@@ -1,33 +0,0 @@
#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 (;;);
}
-148
View File
@@ -1,148 +0,0 @@
#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/struct/timespec.h"
#include "libc/calls/termios.h"
#include "libc/errno.h"
#include "libc/fmt/fmt.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/append.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/o.h"
#include "libc/time/struct/tm.h"
#include "third_party/getopt/getopt.h"
#include "third_party/musl/passwd.h"
/**
* @fileoverview program for broadcasting message to all terminals, e.g.
*
* o//examples/wall.com hello friends
*
* Will place some bold text into the top left corners of all terminals:
*
* Broadcast message from jart@host (pts/4) (Tue Oct 11 03:52:24 2022):
* hello friends
*
* It's useful for having one terminal tab notify your other ones when
* something like a long running job completes. In the old days back
* when unix systems had multiple users, the wall command provided the
* ultimate lulz especially if it's a setuid binary with root privs.
*/
#define GETOPTS "v"
#define USAGE \
"\
Usage: wall.com [-v] [TEXTMSG] [<TEXTMSG]\n\
-v increase verbosity\n\
Examples:\n\
wall.com 'hello my friends'\n\
echo hello my friends | wall.com\n\
"
int g_verbose;
static void GetOpts(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, GETOPTS)) != -1) {
switch (opt) {
case 'v':
g_verbose++;
break;
case '?':
write(1, USAGE, sizeof(USAGE) - 1);
exit(0);
default:
write(2, USAGE, sizeof(USAGE) - 1);
exit(64);
}
}
}
char *GetHost(void) {
static char host[254];
if (gethostname(host, sizeof(host))) {
strcpy(host, "localhost");
}
return host;
}
char *GetTime(void) {
int64_t t;
struct tm tm;
struct timespec ts;
clock_gettime(0, &ts);
localtime_r(&ts.tv_sec, &tm);
return _chomp(asctime(&tm));
}
int main(int argc, char *argv[]) {
GetOpts(argc, argv);
// create broadcast banner
// we use \e[1m so the text is strong & visually distinct
// we use \e[K so it doesn't get lost in a forest of text
// we map \n → \r\n because teletype might be in raw mode
char *msg = 0;
const char *s;
appends(&msg, "\e7"); // save cursor position
appends(&msg, "\e[H"); // goto top left corne
appends(&msg, "\e[K"); // clear line forward
appends(&msg, "\e[1m"); // bold text
appendf(&msg, "Broadcast message from %s@%s", getpwuid(getuid())->pw_name,
GetHost());
if (isatty(0) && (s = ttyname(0))) appendf(&msg, " (%s)", s);
appendf(&msg, " (%s):\r\n", GetTime());
appends(&msg, "\e[K");
// append broadcast message
if (optind < argc) {
// use cli arguments as message if they exist
for (int i = 0; optind + i < argc; ++i) {
if (i) appends(&msg, " ");
for (s = argv[optind + i]; *s; ++s) {
if (*s == '\n') {
appends(&msg, "\r\n\e[K");
} else {
appendw(&msg, *s & 255);
}
}
}
} else {
// otherwise use stdin as message
ssize_t i, rc;
char buf[512];
while ((rc = read(0, buf, sizeof(buf))) > 0) {
for (i = 0; i < rc; ++i) {
if (buf[i] == '\n') {
appends(&msg, "\r\n\e[K"); // clear line forward
} else {
appendw(&msg, buf[i] & 255);
}
}
}
}
appends(&msg, "\r\n\e[K\e[0m\e8"); // restore
// try to send message to all pseudoteletypewriters
for (int i = 0;; ++i) {
int fd;
char pts[32];
snprintf(pts, sizeof(pts), "/dev/pts/%d", i);
if ((fd = open(pts, O_WRONLY | O_NOCTTY)) == -1) {
if (errno == ENOENT) break;
if (g_verbose) perror(pts);
}
write(fd, msg, appendz(msg).i);
close(fd);
}
return 0;
}
-617
View File
@@ -1,617 +0,0 @@
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│
│vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright (c) 1980, 1993 │
│ The Regents of the University of California. All rights reserved. │
│ │
│ Redistribution and use in source and binary forms, with or without │
│ modification, are permitted provided that the following conditions │
│ are met: │
│ 1. Redistributions of source code must retain the above copyright │
│ notice, this list of conditions and the following disclaimer. │
│ 2. Redistributions in binary form must reproduce the above copyright │
│ notice, this list of conditions and the following disclaimer in the │
│ documentation and/or other materials provided with the distribution. │
│ 3. Neither the name of the University nor the names of its contributors │
│ may be used to endorse or promote products derived from this software │
│ without specific prior written permission. │
│ │
│ THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND │
│ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE │
│ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE │
│ ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE │
│ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL │
│ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS │
│ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) │
│ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT │
│ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY │
│ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF │
│ SUCH DAMAGE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/dns/dns.h"
#include "libc/errno.h"
#include "libc/log/bsd.h"
#include "libc/mem/fmt.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/struct/pollfd.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/ex.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/poll.h"
#include "libc/sysv/consts/sock.h"
#include "third_party/getopt/getopt.h"
// clang-format off
asm(".ident\t\"\\n\\n\
FreeBSD Whois (BSD-3 License)\\n\
Copyright (c) 1980, 1993\\n\
\tThe Regents of the University of California.\\n\
\tAll rights reserved.\"");
asm(".include \"libc/disclaimer.inc\"");
#define ABUSEHOST "whois.abuse.net"
#define ANICHOST "whois.arin.net"
#define DENICHOST "whois.denic.de"
#define DKNICHOST "whois.dk-hostmaster.dk"
#define FNICHOST "whois.afrinic.net"
#define GNICHOST "whois.nic.gov"
#define IANAHOST "whois.iana.org"
#define INICHOST "whois.internic.net"
#define KNICHOST "whois.krnic.net"
#define LNICHOST "whois.lacnic.net"
#define MNICHOST "whois.ra.net"
#define PDBHOST "whois.peeringdb.com"
#define PNICHOST "whois.apnic.net"
#define QNICHOST_TAIL ".whois-servers.net"
#define RNICHOST "whois.ripe.net"
#define VNICHOST "whois.verisign-grs.com"
#define DEFAULT_PORT "whois"
#define WHOIS_RECURSE 0x01
#define WHOIS_QUICK 0x02
#define WHOIS_SPAM_ME 0x04
#define CHOPSPAM ">>> Last update of WHOIS database:"
#define ishost(h) (isalnum((unsigned char)h) || h == '.' || h == '-')
#define SCAN(p, end, check) \
while ((p) < (end)) \
if (check) ++(p); \
else break
static struct {
const char *suffix, *server;
} whoiswhere[] = {
/* Various handles */
{ "-ARIN", ANICHOST },
{ "-NICAT", "at" QNICHOST_TAIL },
{ "-NORID", "no" QNICHOST_TAIL },
{ "-RIPE", RNICHOST },
/* Nominet's whois server doesn't return referrals to JANET */
{ ".ac.uk", "ac.uk" QNICHOST_TAIL },
{ ".gov.uk", "ac.uk" QNICHOST_TAIL },
{ "", IANAHOST }, /* default */
{ NULL, NULL } /* safety belt */
};
#define WHOIS_REFERRAL(s) { s, sizeof(s) - 1 }
static struct {
const char *prefix;
size_t len;
} whois_referral[] = {
WHOIS_REFERRAL("whois:"), /* IANA */
WHOIS_REFERRAL("Whois Server:"),
WHOIS_REFERRAL("Registrar WHOIS Server:"), /* corporatedomains.com */
WHOIS_REFERRAL("ReferralServer: whois://"), /* ARIN */
WHOIS_REFERRAL("ReferralServer: rwhois://"), /* ARIN */
WHOIS_REFERRAL("descr: region. Please query"), /* AfriNIC */
{ NULL, 0 }
};
/*
* We have a list of patterns for RIRs that assert ignorance rather than
* providing referrals. If that happens, we guess that ARIN will be more
* helpful. But, before following a referral to an RIR, we check if we have
* asked that RIR already, and if so we make another guess.
*/
static const char *actually_arin[] = {
"netname: ERX-NETBLOCK\n", /* APNIC */
"netname: NON-RIPE-NCC-MANAGED-ADDRESS-BLOCK\n",
NULL
};
static struct {
int loop;
const char *host;
} try_rir[] = {
{ 0, ANICHOST },
{ 0, RNICHOST },
{ 0, PNICHOST },
{ 0, FNICHOST },
{ 0, LNICHOST },
{ 0, NULL }
};
static void
reset_rir(void) {
int i;
for (i = 0; try_rir[i].host != NULL; i++)
try_rir[i].loop = 0;
}
static const char *port = DEFAULT_PORT;
static const char *choose_server(char *);
static struct addrinfo *gethostinfo(const char *, const char *, int);
static void s_asprintf(char **ret, const char *format, ...);
static void usage(void);
static void whois(const char *, const char *, const char *, int);
int
main(int argc, char *argv[])
{
const char *country, *host;
int ch, flags;
#ifdef SOCKS
SOCKSinit(argv[0]);
#endif
country = host = NULL;
flags = 0;
while ((ch = getopt(argc, argv, "aAbc:fgh:iIklmp:PQrRS")) != -1) {
switch (ch) {
case 'a':
host = ANICHOST;
break;
case 'A':
host = PNICHOST;
break;
case 'b':
host = ABUSEHOST;
break;
case 'c':
country = optarg;
break;
case 'f':
host = FNICHOST;
break;
case 'g':
host = GNICHOST;
break;
case 'h':
host = optarg;
break;
case 'i':
host = INICHOST;
break;
case 'I':
host = IANAHOST;
break;
case 'k':
host = KNICHOST;
break;
case 'l':
host = LNICHOST;
break;
case 'm':
host = MNICHOST;
break;
case 'p':
port = optarg;
break;
case 'P':
host = PDBHOST;
break;
case 'Q':
flags |= WHOIS_QUICK;
break;
case 'r':
host = RNICHOST;
break;
case 'R':
flags |= WHOIS_RECURSE;
break;
case 'S':
flags |= WHOIS_SPAM_ME;
break;
case '?':
default:
usage();
/* NOTREACHED */
}
}
argc -= optind;
argv += optind;
if (!argc || (country != NULL && host != NULL))
usage();
/*
* If no host or country is specified, rely on referrals from IANA.
*/
if (host == NULL && country == NULL) {
if ((host = getenv("WHOIS_SERVER")) == NULL &&
(host = getenv("RA_SERVER")) == NULL) {
if (!(flags & WHOIS_QUICK))
flags |= WHOIS_RECURSE;
}
}
while (argc-- > 0) {
if (country != NULL) {
char *qnichost;
s_asprintf(&qnichost, "%s%s", country, QNICHOST_TAIL);
whois(*argv, qnichost, port, flags);
free(qnichost);
} else
whois(*argv, host != NULL ? host :
choose_server(*argv), port, flags);
reset_rir();
argv++;
}
exit(0);
}
static const char *
choose_server(char *domain)
{
size_t len = strlen(domain);
int i;
for (i = 0; whoiswhere[i].suffix != NULL; i++) {
size_t suffix_len = strlen(whoiswhere[i].suffix);
if (len > suffix_len &&
strcasecmp(domain + len - suffix_len,
whoiswhere[i].suffix) == 0)
return (whoiswhere[i].server);
}
errx(EX_SOFTWARE, "no default whois server");
}
static struct addrinfo *
gethostinfo(const char *host, const char *hport, int exit_on_noname)
{
struct addrinfo hints, *res;
int error;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_CANONNAME;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
res = NULL;
error = getaddrinfo(host, hport, &hints, &res);
if (error && (exit_on_noname || error != EAI_NONAME))
err(EX_NOHOST, "%s: %s", host, gai_strerror(error));
return (res);
}
/*
* Wrapper for asprintf(3) that exits on error.
*/
static void
s_asprintf(char **ret, const char *format, ...)
{
va_list ap;
va_start(ap, format);
if (vasprintf(ret, format, ap) == -1) {
va_end(ap);
err(EX_OSERR, "vasprintf()");
}
va_end(ap);
}
static int
connect_to_any_host(struct addrinfo *hostres)
{
struct addrinfo *res;
nfds_t i, j;
size_t count;
struct pollfd *fds;
int timeout = 180, s = -1;
for (res = hostres, count = 0; res; res = res->ai_next)
count++;
fds = calloc(count, sizeof(*fds));
if (fds == NULL)
err(EX_OSERR, "calloc()");
/*
* Traverse the result list elements and make non-block
* connection attempts.
*/
count = i = 0;
for (res = hostres; res != NULL; res = res->ai_next) {
s = socket(res->ai_family, res->ai_socktype | SOCK_NONBLOCK,
res->ai_protocol);
if (s < 0)
continue;
if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
if (errno == EINPROGRESS) {
/* Add the socket to poll list */
fds[i].fd = s;
fds[i].events = POLLERR | POLLHUP |
POLLIN | POLLOUT;
/*
* From here until a socket connects, the
* socket fd is owned by the fds[] poll array.
*/
s = -1;
count++;
i++;
} else {
close(s);
s = -1;
/*
* Poll only if we have something to poll,
* otherwise just go ahead and try next
* address
*/
if (count == 0)
continue;
}
} else
goto done;
/*
* If we are at the last address, poll until a connection is
* established or we failed all connection attempts.
*/
if (res->ai_next == NULL)
timeout = INFTIM;
/*
* Poll the watched descriptors for successful connections:
* if we still have more untried resolved addresses, poll only
* once; otherwise, poll until all descriptors have errors,
* which will be considered as ETIMEDOUT later.
*/
do {
int n;
n = poll(fds, i, timeout);
if (n == 0) {
/*
* No event reported in time. Try with a
* smaller timeout (but cap at 2-3ms)
* after a new host have been added.
*/
if (timeout >= 3)
timeout >>= 1;
break;
} else if (n < 0) {
/*
* errno here can only be EINTR which we would
* want to clean up and bail out.
*/
s = -1;
goto done;
}
/*
* Check for the event(s) we have seen.
*/
for (j = 0; j < i; j++) {
if (fds[j].fd == -1 || fds[j].events == 0 ||
fds[j].revents == 0)
continue;
if (fds[j].revents & ~(POLLIN | POLLOUT)) {
close(fds[j].fd);
fds[j].fd = -1;
fds[j].events = 0;
count--;
continue;
} else if (fds[j].revents & (POLLIN | POLLOUT)) {
/* Connect succeeded. */
s = fds[j].fd;
fds[j].fd = -1;
goto done;
}
}
} while (timeout == INFTIM && count != 0);
}
/* All attempts were failed */
s = -1;
if (count == 0)
errno = ETIMEDOUT;
done:
/* Close all watched fds except the succeeded one */
for (j = 0; j < i; j++)
if (fds[j].fd != -1)
close(fds[j].fd);
free(fds);
return (s);
}
static void
whois(const char *query, const char *hostname, const char *hostport, int flags)
{
FILE *fp;
struct addrinfo *hostres;
char *buf, *host, *nhost, *nport, *p;
int comment, s, f;
size_t len, i;
hostres = gethostinfo(hostname, hostport, 1);
s = connect_to_any_host(hostres);
if (s == -1)
err(EX_OSERR, "connect()");
/* Restore default blocking behavior. */
if ((f = fcntl(s, F_GETFL)) == -1)
err(EX_OSERR, "fcntl()");
f &= ~O_NONBLOCK;
if (fcntl(s, F_SETFL, f) == -1)
err(EX_OSERR, "fcntl()");
fp = fdopen(s, "r+");
if (fp == NULL)
err(EX_OSERR, "fdopen()");
if (!(flags & WHOIS_SPAM_ME) &&
(strcasecmp(hostname, DENICHOST) == 0 ||
strcasecmp(hostname, "de" QNICHOST_TAIL) == 0)) {
const char *q;
int idn = 0;
for (q = query; *q != '\0'; q++)
if (!isascii(*q))
idn = 1;
fprintf(fp, "-T dn%s %s\r\n", idn ? "" : ",ace", query);
} else if (!(flags & WHOIS_SPAM_ME) &&
(strcasecmp(hostname, DKNICHOST) == 0 ||
strcasecmp(hostname, "dk" QNICHOST_TAIL) == 0))
fprintf(fp, "--show-handles %s\r\n", query);
else if ((flags & WHOIS_SPAM_ME) ||
strchr(query, ' ') != NULL)
fprintf(fp, "%s\r\n", query);
else if (strcasecmp(hostname, ANICHOST) == 0) {
if (strncasecmp(query, "AS", 2) == 0 &&
strspn(query+2, "0123456789") == strlen(query+2))
fprintf(fp, "+ a %s\r\n", query+2);
else
fprintf(fp, "+ %s\r\n", query);
} else if (strcasecmp(hostres->ai_canonname, VNICHOST) == 0)
fprintf(fp, "domain %s\r\n", query);
else
fprintf(fp, "%s\r\n", query);
fflush(fp);
comment = 0;
if (!(flags & WHOIS_SPAM_ME) &&
(strcasecmp(hostname, ANICHOST) == 0 ||
strcasecmp(hostname, RNICHOST) == 0)) {
comment = 2;
}
nhost = NULL;
while ((buf = fgetln(fp, &len)) != NULL) {
/* Nominet */
if (!(flags & WHOIS_SPAM_ME) &&
len == 5 && strncmp(buf, "-- \r\n", 5) == 0)
break;
/* RIRs */
if (comment == 1 && buf[0] == '#')
break;
else if (comment == 2) {
if (strchr("#%\r\n", buf[0]) != NULL)
continue;
else
comment = 1;
}
printf("%.*s", (int)len, buf);
if ((flags & WHOIS_RECURSE) && nhost == NULL) {
for (i = 0; whois_referral[i].prefix != NULL; i++) {
p = buf;
SCAN(p, buf+len, *p == ' ');
if (strncasecmp(p, whois_referral[i].prefix,
whois_referral[i].len) != 0)
continue;
p += whois_referral[i].len;
SCAN(p, buf+len, *p == ' ');
host = p;
SCAN(p, buf+len, ishost(*p));
if (p > host) {
char *pstr;
s_asprintf(&nhost, "%.*s",
(int)(p - host), host);
if (*p != ':') {
s_asprintf(&nport, "%s", port);
break;
}
pstr = ++p;
SCAN(p, buf+len, isdigit(*p));
if (p > pstr && (p - pstr) < 6) {
s_asprintf(&nport, "%.*s",
(int)(p - pstr), pstr);
break;
}
/* Invalid port; don't recurse */
free(nhost);
nhost = NULL;
}
break;
}
for (i = 0; actually_arin[i] != NULL; i++) {
if (strncmp(buf, actually_arin[i], len) == 0) {
s_asprintf(&nhost, "%s", ANICHOST);
s_asprintf(&nport, "%s", port);
break;
}
}
}
/* Verisign etc. */
if (!(flags & WHOIS_SPAM_ME) &&
len >= sizeof(CHOPSPAM)-1 &&
(strncasecmp(buf, CHOPSPAM, sizeof(CHOPSPAM)-1) == 0 ||
strncasecmp(buf, CHOPSPAM+4, sizeof(CHOPSPAM)-5) == 0)) {
printf("\n");
break;
}
}
fclose(fp);
freeaddrinfo(hostres);
f = 0;
for (i = 0; try_rir[i].host != NULL; i++) {
/* Remember visits to RIRs */
if (try_rir[i].loop == 0 &&
strcasecmp(try_rir[i].host, hostname) == 0)
try_rir[i].loop = 1;
/* Do we need to find an alternative RIR? */
if (try_rir[i].loop != 0 && nhost != NULL &&
strcasecmp(try_rir[i].host, nhost) == 0) {
free(nhost);
nhost = NULL;
free(nport);
nport = NULL;
f = 1;
}
}
if (f) {
/* Find a replacement RIR */
for (i = 0; try_rir[i].host != NULL; i++) {
if (try_rir[i].loop == 0) {
s_asprintf(&nhost, "%s", try_rir[i].host);
s_asprintf(&nport, "%s", port);
break;
}
}
}
if (nhost != NULL) {
/* Ignore self-referrals */
if (strcasecmp(hostname, nhost) != 0) {
printf("# %s\n\n", nhost);
whois(query, nhost, nport, flags);
}
free(nhost);
free(nport);
}
}
static void
usage(void)
{
fprintf(stderr,
"usage: whois [-aAbfgiIklmPQrRS] [-c country-code | -h hostname] "
"[-p port] name ...\n");
exit(EX_USAGE);
}
+12 -52
View File
@@ -7,69 +7,29 @@ extern bool __assert_disable;
void __assert_fail(const char *, const char *, int) hidden relegated;
#ifdef NDEBUG
#define assert(x) ((void)0)
#define assert(EXPR) ((void)0)
#else
#define assert(x) ((void)((x) || (__assert_fail(#x, __FILE__, __LINE__), 0)))
#define assert(EXPR) \
((void)((EXPR) || (__assert_fail(#EXPR, __FILE__, __LINE__), 0)))
#endif
#ifndef __cplusplus
#define static_assert _Static_assert
#endif
#ifdef __GNUC__
#ifndef TINY
/**
* Specifies expression can't possibly be false.
*
* This macro uses the `notpossible` keyword and is intended for things
* like systems integration, where we know for a fact that something is
* never going to happen, but there's no proof. So we don't want to add
* extra bloat for filenames and line numbers, since `ShowCrashReports`
* can print a backtrace if we just embed the UD2 instruction to crash.
* That's useful for systems code, for the following reason. Invariants
* make sense with _unassert() since they usually get placed at the top
* of functions. But if you used _unassert() to test a system call does
* not fail, then check happens at the end of your function usually and
* is therefore likely to result in a failure condition where execution
* falls through into a different function, which is shocking to debug.
*
* In `MODE=tiny` these assertions are redefined as undefined behavior.
*/
#define _npassert(x) \
({ \
if (__builtin_expect(!(x), 0)) { \
notpossible; \
} \
(void)0; \
})
#else
#define _npassert(x) _unassert(x)
#endif
#endif
#ifdef __GNUC__
/**
* Specifies expression being false is undefined behavior.
*
* This is a good way to tell the compiler about your invariants, which
* leads to smaller faster programs. The expression is never removed by
* the preprocessor so it's recommended that it be free of side-effects
* if you intend for it to be removed. At the same time, this guarantee
* makes this assertion useful for things like system calls, since they
* won't be removed by `NDEBUG` mode.
*
* If this assertion fails, the worst possible things can happen unless
* you've built your binary in `MODE=dbg` since UBSAN is the only thing
* that's capable of debugging this macro.
*/
#define _unassert(x) \
({ \
do { \
if (__builtin_expect(!(x), 0)) { \
unreachable; \
} \
(void)0; \
})
#endif
} while (0)
#define _npassert(x) \
do { \
if (__builtin_expect(!(x), 0)) { \
notpossible; \
} \
} while (0)
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
-43
View File
@@ -1,43 +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 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/sig.internal.h"
#include "libc/calls/state.internal.h"
#include "libc/calls/struct/sigset.h"
/**
* Determines the pending signals on New Technology.
*
* @param pending is to hold the pending signals
* @threadsafe
*/
textwindows void __sig_pending(sigset_t *pending) {
struct Signal *s;
sigemptyset(pending);
if (__sig.queue) {
__sig_lock();
for (s = __sig.queue; s; s = s->next) {
if (__sig_is_applicable(s) &&
__sighandrvas[s->sig] != (unsigned)(intptr_t)SIG_IGN) {
sigaddset(pending, s->sig);
}
}
__sig_unlock();
}
}
-93
View File
@@ -1,93 +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 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/syscall-sysv.internal.h"
#include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/fmt/itoa.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/termios.h"
#include "libc/sysv/errfuns.h"
extern const unsigned FIODGNAME;
extern const unsigned TIOCPTSNAME;
extern const unsigned TIOCPTYGNAME;
struct fiodgname_arg {
int len;
void *buf;
};
struct ptmget {
int cfd;
int sfd;
char cn[1024];
char sn[1024];
};
int _ptsname(int fd, char *buf, size_t size) {
int pty;
size_t n;
struct ptmget t;
if (_isptmaster(fd)) {
return -1;
}
t.sn[0] = '/';
t.sn[1] = 'd';
t.sn[2] = 'e';
t.sn[3] = 'v';
t.sn[4] = '/';
t.sn[5] = 0;
if (IsLinux()) {
if (sys_ioctl(fd, TIOCGPTN, &pty)) return -1;
t.sn[5] = 'p';
t.sn[6] = 't';
t.sn[7] = 's';
t.sn[8] = '/';
FormatInt32(t.sn + 9, pty);
} else if (IsXnu()) {
if (sys_ioctl(fd, TIOCPTYGNAME, t.sn)) {
return -1;
}
} else if (IsFreebsd()) {
struct fiodgname_arg fgn = {sizeof(t.sn) - 5, t.sn + 5};
if (sys_ioctl(fd, FIODGNAME, &fgn) == -1) {
if (errno == EINVAL) {
errno = ERANGE;
}
return -1;
}
} else if (IsNetbsd()) {
if (sys_ioctl(fd, TIOCPTSNAME, &t)) {
return -1;
}
} else {
return enosys();
}
if ((n = strlen(t.sn)) < size) {
memcpy(buf, t.sn, n + 1);
return 0;
} else {
return erange();
}
}
+1 -1
View File
@@ -19,7 +19,7 @@
#include "libc/calls/struct/timespec.h"
/**
* Compares nanosecond timestamps.
* Compares two nanosecond timestamps.
*/
int _timespec_cmp(struct timespec a, struct timespec b) {
int cmp;
-1
View File
@@ -26,7 +26,6 @@
* @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)) {
+5 -8
View File
@@ -19,16 +19,13 @@
#include "libc/assert.h"
#include "libc/calls/struct/timespec.h"
#include "libc/sysv/consts/clock.h"
#include "libc/sysv/consts/nr.h"
#include "libc/time/time.h"
/**
* Returns current monotonic time.
*
* This function uses a `CLOCK_MONOTONIC` clock and never fails.
*
* @see _timespec_real()
*/
struct timespec _timespec_mono(void) {
int ax, dx;
struct timespec ts;
_npassert(!clock_gettime(CLOCK_MONOTONIC_FAST, &ts));
ax = clock_gettime(CLOCK_MONOTONIC_FAST, &ts);
assert(!ax);
return ts;
}
+5 -11
View File
@@ -16,21 +16,15 @@
│ 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/sysv/consts/clock.h"
#include "libc/sysv/consts/nr.h"
#include "libc/time/time.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) {
int ax, dx;
struct timespec ts;
_npassert(!clock_gettime(CLOCK_REALTIME_FAST, &ts));
ax = clock_gettime(CLOCK_REALTIME_FAST, &ts);
if (ax) notpossible;
return ts;
}
-38
View File
@@ -1,38 +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 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/assert.h"
#include "libc/calls/struct/timespec.h"
#include "libc/errno.h"
#include "libc/sysv/consts/clock.h"
/**
* 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 {
_npassert(rc == EINTR);
return remain;
}
}
-35
View File
@@ -1,35 +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 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/assert.h"
#include "libc/calls/struct/timespec.h"
#include "libc/errno.h"
#include "libc/sysv/consts/clock.h"
#include "libc/sysv/consts/timer.h"
/**
* 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;
}
+4 -27
View File
@@ -20,36 +20,13 @@
#include "libc/limits.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.
*
* 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()
* Converts timespec interval to microseconds.
*/
int64_t _timespec_tomicros(struct timespec ts) {
int64_t _timespec_tomicros(struct timespec x) {
int64_t 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)) {
if (!__builtin_mul_overflow(x.tv_sec, 1000000ul, &us) &&
!__builtin_add_overflow(us, x.tv_nsec / 1000, &us)) {
return us;
} else if (ts.tv_sec < 0) {
return INT64_MIN;
} else {
return INT64_MAX;
}
+4 -26
View File
@@ -20,35 +20,13 @@
#include "libc/limits.h"
/**
* 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
* Converts timespec interval to milliseconds.
*/
int64_t _timespec_tomillis(struct timespec ts) {
int64_t _timespec_tomillis(struct timespec x) {
int64_t 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)) {
if (!__builtin_mul_overflow(x.tv_sec, 1000ul, &ms) &&
!__builtin_add_overflow(ms, x.tv_nsec / 1000000, &ms)) {
return ms;
} else if (ts.tv_sec < 0) {
return INT64_MIN;
} else {
return INT64_MAX;
}
+1 -8
View File
@@ -20,20 +20,13 @@
#include "libc/limits.h"
/**
* 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
* Converts timespec interval to nanoseconds.
*/
int64_t _timespec_tonanos(struct timespec x) {
int64_t ns;
if (!__builtin_mul_overflow(x.tv_sec, 1000000000ul, &ns) &&
!__builtin_add_overflow(ns, x.tv_nsec, &ns)) {
return ns;
} else if (x.tv_sec < 0) {
return INT64_MIN;
} else {
return INT64_MAX;
}
+1 -16
View File
@@ -18,21 +18,6 @@
╚─────────────────────────────────────────────────────────────────────────────*/
#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) {
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};
}
return (struct timeval){ts.tv_sec, ts.tv_nsec / 1000};
}
-30
View File
@@ -1,30 +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 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;
}
-34
View File
@@ -1,34 +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 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;
}
-32
View File
@@ -1,32 +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 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;
}
-3
View File
@@ -18,9 +18,6 @@
╚─────────────────────────────────────────────────────────────────────────────*/
#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};
}
+1 -6
View File
@@ -22,14 +22,9 @@
/**
* 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 w/ errno
* @see faccessat() for further documentation
* @return 0 if ok, or -1 and sets errno
* @asyncsignalsafe
*/
int access(const char *path, int mode) {
+3 -1
View File
@@ -32,10 +32,12 @@
* @asyncsignalsafe
*/
unsigned alarm(unsigned seconds) {
int rc;
struct itimerval it;
bzero(&it, sizeof(it));
it.it_value.tv_sec = seconds;
_npassert(!setitimer(ITIMER_REAL, &it, &it));
rc = setitimer(ITIMER_REAL, &it, &it);
assert(rc != -1);
if (!it.it_value.tv_sec && !it.it_value.tv_usec) {
return 0;
} else {
+1 -6
View File
@@ -1,8 +1,7 @@
#ifndef COSMOPOLITAN_LIBC_CALLS_ASAN_INTERNAL_H_
#define COSMOPOLITAN_LIBC_CALLS_ASAN_INTERNAL_H_
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timeval.h"
#include "libc/intrin/asmflag.h"
#include "libc/calls/struct/timespec.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
@@ -15,10 +14,6 @@ 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_ */
+12 -14
View File
@@ -84,8 +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, int);
int faccessat(int, const char *, int, uint32_t);
int fadvise(int, uint64_t, uint64_t, int);
int fchdir(int);
int fchmod(int, uint32_t) dontthrow;
@@ -128,9 +127,8 @@ int linkat(int, const char *, int, const char *, int);
int madvise(void *, uint64_t, int);
int memfd_create(const char *, unsigned int);
int mincore(void *, size_t, unsigned char *);
int mkdir(const char *, unsigned);
int mkdirat(int, const char *, unsigned);
int makedirs(const char *, unsigned);
int mkdir(const char *, uint32_t);
int mkdirat(int, const char *, uint32_t);
int mkfifo(const char *, uint32_t);
int mkfifoat(int, const char *, uint32_t);
int mknod(const char *, uint32_t, uint64_t);
@@ -149,7 +147,7 @@ int pipe(int[hasatleast 2]);
int pipe2(int[hasatleast 2], int);
int pivot_root(const char *, const char *);
int pledge(const char *, const char *);
int posix_fadvise(int, int64_t, int64_t, int);
int posix_fadvise(int, uint64_t, uint64_t, int);
int posix_madvise(void *, uint64_t, int);
int prctl(int, ...);
int raise(int);
@@ -163,10 +161,10 @@ int sched_yield(void);
int seccomp(unsigned, unsigned, void *);
int setegid(uint32_t);
int seteuid(uint32_t);
int setfsgid(unsigned);
int setfsuid(unsigned);
int setgid(unsigned);
int setgroups(size_t, const uint32_t[]);
int setfsgid(int);
int setfsuid(int);
int setgid(int);
int setgroups(size_t size, const uint32_t list[]);
int setpgid(int, int);
int setpgrp(void);
int setpriority(int, unsigned, int);
@@ -175,7 +173,7 @@ int setresgid(uint32_t, uint32_t, uint32_t);
int setresuid(uint32_t, uint32_t, uint32_t);
int setreuid(uint32_t, uint32_t);
int setsid(void);
int setuid(unsigned);
int setuid(int);
int sigignore(int);
int siginterrupt(int, int);
int symlink(const char *, const char *);
@@ -188,9 +186,9 @@ int tgkill(int, int, int);
int tkill(int, int);
int tmpfd(void);
int touch(const char *, uint32_t);
int truncate(const char *, int64_t);
int truncate(const char *, uint64_t);
int ttyname_r(int, char *, size_t);
unsigned umask(unsigned);
int umask(int);
int unlink(const char *);
int unlink_s(const char **);
int unlinkat(int, const char *, int);
@@ -205,7 +203,7 @@ long ptrace(int, ...);
ssize_t copy_file_range(int, long *, int, long *, size_t, uint32_t);
ssize_t copyfd(int, int64_t *, int, int64_t *, size_t, uint32_t);
ssize_t getfiledescriptorsize(int);
ssize_t lseek(int, int64_t, int);
ssize_t lseek(int, int64_t, unsigned);
ssize_t pread(int, void *, size_t, int64_t);
ssize_t pwrite(int, const void *, size_t, int64_t);
ssize_t read(int, void *, size_t);
-8
View File
@@ -65,13 +65,6 @@ $(LIBC_CALLS_A).pkg: \
$(LIBC_CALLS_A_OBJS) \
$(foreach x,$(LIBC_CALLS_A_DIRECTDEPS),$($(x)_A).pkg)
# we can't use asan because:
# siginfo_t memory is owned by kernels
o/$(MODE)/libc/calls/siginfo2cosmo.o: private \
OVERRIDE_COPTS += \
-ffreestanding \
-fno-sanitize=address
# we can't use asan because:
# ucontext_t memory is owned by xnu kernel
o/$(MODE)/libc/calls/sigenter-xnu.o: private \
@@ -104,7 +97,6 @@ o/$(MODE)/libc/calls/ntcontext2linux.o: private \
# we always want -O3 because:
# it makes the code size smaller too
o/$(MODE)/libc/calls/termios2host.o \
o/$(MODE)/libc/calls/sigenter-freebsd.o \
o/$(MODE)/libc/calls/sigenter-netbsd.o \
o/$(MODE)/libc/calls/sigenter-openbsd.o \
+1 -1
View File
@@ -19,7 +19,7 @@
#include "libc/calls/termios.h"
#include "libc/sysv/errfuns.h"
int cfsetispeed(struct termios *t, unsigned speed) {
int cfsetispeed(struct termios *t, int speed) {
if (speed) {
if (CBAUD) {
if (speed & ~CBAUD) return einval();
+1 -1
View File
@@ -20,7 +20,7 @@
#include "libc/sysv/consts/termios.h"
#include "libc/sysv/errfuns.h"
int cfsetospeed(struct termios *t, unsigned speed) {
int cfsetospeed(struct termios *t, int speed) {
if (CBAUD) {
if (!(speed & ~CBAUD)) {
t->c_cflag &= ~CBAUD;
+16 -25
View File
@@ -26,36 +26,35 @@
#include "libc/nt/synchronization.h"
#include "libc/sysv/errfuns.h"
textwindows int sys_chdir_nt_impl(char16_t path[hasatleast PATH_MAX],
uint32_t len) {
textwindows int sys_chdir_nt(const char *path) {
uint32_t n;
int e, ms, err;
char16_t var[4];
if (len && path[len - 1] != u'\\') {
int e, ms, err, len;
char16_t path16[PATH_MAX], var[4];
if ((len = __mkntpath(path, path16)) == -1) return -1;
if (!len) return enoent();
if (len && path16[len - 1] != u'\\') {
if (len + 2 > PATH_MAX) return enametoolong();
path[len + 0] = u'\\';
path[len + 1] = u'\0';
path16[len + 0] = u'\\';
path16[len + 1] = u'\0';
}
/*
* chdir() seems flaky on windows 7
* in a similar way to rmdir() sigh
*/
for (err = errno, ms = 1;; ms *= 2) {
if (SetCurrentDirectory(path)) {
if (SetCurrentDirectory(path16)) {
/*
* Now we need to set a magic environment variable.
*/
if ((n = GetCurrentDirectory(PATH_MAX, path))) {
if (n < PATH_MAX) {
if (!((path[0] == '/' && path[1] == '/') ||
(path[0] == '\\' && path[1] == '\\'))) {
if ((n = GetCurrentDirectory(ARRAYLEN(path16), path16))) {
if (n < ARRAYLEN(path16)) {
if (!((path16[0] == '/' && path16[1] == '/') ||
(path16[0] == '\\' && path16[1] == '\\'))) {
var[0] = '=';
var[1] = path[0];
var[1] = path16[0];
var[2] = ':';
var[3] = 0;
if (!SetEnvironmentVariable(var, path)) {
if (!SetEnvironmentVariable(var, path16)) {
return __winerr();
}
}
@@ -78,13 +77,5 @@ textwindows int sys_chdir_nt_impl(char16_t path[hasatleast PATH_MAX],
}
}
}
return __fix_enotdir(-1, path);
}
textwindows int sys_chdir_nt(const char *path) {
int len;
char16_t path16[PATH_MAX];
if ((len = __mkntpath(path, path16)) == -1) return -1;
if (!len) return enoent();
return sys_chdir_nt_impl(path16, len);
return __fix_enotdir(-1, path16);
}
+1 -3
View File
@@ -16,12 +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/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"
/**
@@ -35,7 +34,6 @@
*/
int chdir(const char *path) {
int rc;
GetProgramExecutableName(); // XXX: ugly workaround
if (!path || (IsAsan() && !__asan_is_valid(path, 1))) {
rc = efault();
} else if (!IsWindows()) {
+2 -28
View File
@@ -17,43 +17,17 @@
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.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"
#include "libc/calls/syscall-sysv.internal.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;
if (!path || (IsAsan() && !__asan_is_valid(path, 1))) {
rc = efault();
} else {
rc = sys_chroot(path);
}
rc = sys_chroot(path);
STRACE("chroot(%s) → %d% m", path, rc);
return rc;
}
+1 -7
View File
@@ -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,12 +49,6 @@ 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;
+4 -23
View File
@@ -20,6 +20,7 @@
#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"
@@ -29,11 +30,9 @@
#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.
@@ -49,30 +48,12 @@
* __clock_gettime l: 35𝑐 11𝑛𝑠
* sys_clock_gettime l: 220𝑐 71𝑛𝑠
*
* @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 clock can be CLOCK_REALTIME, CLOCK_MONOTONIC, etc.
* @param ts is where the result is stored
* @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
* @error EINVAL if clock isn't supported on this system
* @see strftime(), gettimeofday()
* @asyncsignalsafe
* @threadsafe
* @vforksafe
*/
int clock_gettime(int clock, struct timespec *ts) {
int rc;
@@ -84,7 +65,7 @@ int clock_gettime(int clock, struct timespec *ts) {
rc = __clock_gettime(clock, ts);
}
#if SYSDEBUG
if (!(__get_tls()->tib_flags & TIB_FLAG_TIME_CRITICAL)) {
if (!__time_critical) {
STRACE("clock_gettime(%s, [%s]) → %d% m", DescribeClockName(clock),
DescribeTimespec(rc, ts), rc);
}
-49
View File
@@ -1,49 +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 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.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"
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 {
res = sys_nanosleep_xnu(req, rem);
}
} else {
res = enotsup();
}
return res;
}
-124
View File
@@ -1,124 +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 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 EFAULT if `req` or null or bad memory was passed
* @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 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;
}
+9 -17
View File
@@ -32,25 +32,17 @@
/**
* Closes file descriptor.
*
* This function releases resources returned by functions such as:
* This function may be used for file descriptors returned by functions
* like open, socket, accept, epoll_create, and landlock_create_ruleset.
*
* - 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`.
* 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.
*
* @return 0 on success, or -1 w/ errno
* @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
* @error EINTR means a signal was received while closing in which case
* close() does not need to be called again, since the fd will close
* in the background
* @asyncsignalsafe
* @vforksafe
*/
@@ -59,7 +51,7 @@ int close(int fd) {
if (fd == -1) {
rc = 0;
} else if (fd < 0) {
rc = ebadf();
rc = einval();
} else {
// for performance reasons we want to avoid holding __fds_lock()
// while sys_close() is happening. this leaves the kernel / libc
+21 -15
View File
@@ -17,10 +17,10 @@
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sysv/errfuns.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/errno.h"
#include "libc/limits.h"
/**
* Closes inclusive range of file descriptors, e.g.
@@ -32,27 +32,33 @@
* }
* }
*
* The following flags are available:
* This is supported on Linux 5.9+, FreeBSD, and OpenBSD. On FreeBSD,
* `flags` must be zero. On OpenBSD, we call closefrom(int) so `last`
* should be `-1` in order to get OpenBSD support, otherwise `ENOSYS`
* will be returned. We also polyfill closefrom on FreeBSD since it's
* available on older kernels.
*
* - `CLOSE_RANGE_UNSHARE` (Linux-only)
* - `CLOSE_RANGE_CLOEXEC` (Linux-only)
* On Linux, the following flags are supported:
*
* This is only supported on Linux 5.9+ and FreeBSD 13+. Consider using
* closefrom() which will work on OpenBSD too.
* - CLOSE_RANGE_UNSHARE
* - CLOSE_RANGE_CLOEXEC
*
* @return 0 on success, or -1 w/ errno
* @error ENOSYS if not Linux 5.9+ / FreeBSD / OpenBSD
* @error EBADF on OpenBSD if `first` is greater than highest fd
* @error EINVAL if flags are bad or first is greater than last
* @error EMFILE if a weird race condition happens on Linux
* @error ENOSYS if not Linux 5.9+ or FreeBSD 13+
* @error EINTR possibly on OpenBSD
* @error ENOMEM on Linux maybe
* @see closefrom()
*/
int close_range(unsigned int first, unsigned int last, unsigned int flags) {
int rc;
if (IsLinux() || IsFreebsd()) {
rc = sys_close_range(first, last, flags);
} else {
rc = enosys();
int rc, err;
err = errno;
if ((rc = sys_close_range(first, last, flags)) == -1) {
if (errno == ENOSYS && first <= INT_MAX && last == UINT_MAX && !flags) {
errno = err;
rc = sys_closefrom(first);
}
}
STRACE("close_range(%d, %d, %#x) → %d% m", first, last, flags, rc);
return rc;
+18 -22
View File
@@ -17,10 +17,9 @@
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/strace.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/errno.h"
#include "libc/limits.h"
#include "libc/sysv/errfuns.h"
@@ -35,29 +34,26 @@
* }
*
* @return 0 on success, or -1 w/ errno
* @raise EBADF if `first` is negative
* @raise ENOSYS if not Linux 5.9+, FreeBSD 8+, OpenBSD, or NetBSD
* @raise EBADF on OpenBSD if `first` is greater than highest fd
* @raise EINVAL if flags are bad or first is greater than last
* @raise EMFILE if a weird race condition happens on Linux
* @raise EINTR possibly on OpenBSD
* @raise ENOMEM on Linux maybe
* @error ENOSYS if not Linux 5.9+ / FreeBSD / OpenBSD
* @error EBADF on OpenBSD if `first` is greater than highest fd
* @error EINVAL if flags are bad or first is greater than last
* @error EMFILE if a weird race condition happens on Linux
* @error EINTR possibly on OpenBSD
* @error ENOMEM on Linux maybe
* @note supported on Linux 5.9+, FreeBSD 8+, and OpenBSD
*/
int closefrom(int first) {
int rc, err;
if (first < 0) {
// consistent with openbsd
// freebsd allows this but it's dangerous
// necessary on linux due to type signature
rc = ebadf();
} else if (IsFreebsd() || IsOpenbsd()) {
rc = sys_closefrom(first);
} else if (IsLinux()) {
rc = sys_close_range(first, 0xffffffffu, 0);
} else if (IsNetbsd()) {
rc = __sys_fcntl(first, 10 /*F_CLOSEM*/, first);
if (first >= 0) {
err = errno;
if ((rc = sys_close_range(first, -1, 0)) == -1) {
if (errno == ENOSYS) {
errno = err;
rc = sys_closefrom(first);
}
}
} else {
rc = enosys();
rc = ebadf();
}
STRACE("closefrom(%d) → %d% m", first, rc);
return rc;
-119
View File
@@ -1,119 +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 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"
#include "libc/calls/struct/sigset.h"
#include "libc/calls/struct/sigset.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/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/thread.h"
static struct CopyFileRange {
pthread_once_t once;
bool ok;
} g_copy_file_range;
static bool HasCopyFileRange(void) {
bool ok;
int e, rc;
e = errno;
if (IsLinux()) {
// We modernize our detection by a few years for simplicity.
// This system call is chosen since it's listed by pledge().
// https://www.cygwin.com/bugzilla/show_bug.cgi?id=26338
ok = sys_close_range(-1, -2, 0) == -1 && errno == EINVAL;
} else if (IsFreebsd()) {
ok = sys_copy_file_range(-1, 0, -1, 0, 0, 0) == -1 && errno == EBADF;
} else {
ok = false;
}
errno = e;
return ok;
}
static void copy_file_range_init(void) {
g_copy_file_range.ok = HasCopyFileRange();
}
/**
* Transfers data between files.
*
* If this system call is available (Linux c. 2018 or FreeBSD c. 2021)
* and the file system supports it (e.g. ext4) and the source and dest
* files are on the same file system, then this system call shall make
* copies go about 2x faster.
*
* This implementation requires Linux 5.9+ even though the system call
* was introduced in Linux 4.5. That's to ensure ENOSYS works reliably
* due to a faulty backport, that happened in RHEL7. FreeBSD detection
* on the other hand will work fine.
*
* @param infd is source file, which should be on same file system
* @param opt_in_out_inoffset may be specified for pread() behavior
* @param outfd should be a writable file, but not `O_APPEND`
* @param opt_in_out_outoffset may be specified for pwrite() behavior
* @param uptobytes is maximum number of bytes to transfer
* @param flags is reserved for future use and must be zero
* @return number of bytes transferred, or -1 w/ errno
* @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
* @raise ERANGE if overflow happens computing ranges
* @raise ENOSPC if file system has run out of space
* @raise ETXTBSY if source or dest is a swap file
* @raise EINTR if a signal was delivered instead
* @raise EISDIR if source or dest is a directory
* @raise ENOSYS if not Linux 5.9+ or FreeBSD 13+
* @raise EIO if a low-level i/o error happens
* @see sendfile() for seekable → socket
* @see splice() for fd ↔ pipe
*/
ssize_t copy_file_range(int infd, int64_t *opt_in_out_inoffset, int outfd,
int64_t *opt_in_out_outoffset, size_t uptobytes,
uint32_t flags) {
ssize_t rc;
pthread_once(&g_copy_file_range.once, copy_file_range_init);
if (!g_copy_file_range.ok) {
rc = enosys();
} else if (IsAsan() && ((opt_in_out_inoffset &&
!__asan_is_valid(opt_in_out_inoffset, 8)) ||
(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);
}
STRACE("copy_file_range(%d, %s, %d, %s, %'zu, %#x) → %'ld% m", infd,
DescribeInOutInt64(rc, opt_in_out_inoffset), outfd,
DescribeInOutInt64(rc, opt_in_out_outoffset), uptobytes, flags);
return rc;
}
+66
View File
@@ -0,0 +1,66 @@
/*-*- 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/calls.h"
#include "libc/errno.h"
#include "libc/macros.internal.h"
/**
* Copies data between file descriptors the slow way.
*
* @return -1 on error/interrupt, 0 on eof, or [1..size] on success
* @see copy_file_range() for file ↔ file
* @see sendfile() for seekable → socket
* @see splice() for fd ↔ pipe
*/
ssize_t copyfd(int infd, int64_t *inoutopt_inoffset, int outfd,
int64_t *inoutopt_outoffset, size_t size, uint32_t flags) {
ssize_t rc;
char buf[2048];
size_t i, j, n;
for (i = 0; i < size; i += j) {
n = MIN(size - i, sizeof(buf));
if (inoutopt_inoffset) {
rc = pread(infd, buf, n, *inoutopt_inoffset);
} else {
rc = read(infd, buf, n);
}
if (!rc) return i;
if (rc == -1) {
if (i) return i;
return -1;
}
n = rc;
for (j = 0; j < n; j += rc) {
TryAgain:
if (inoutopt_outoffset) {
rc = pwrite(outfd, buf + j, n - j, *inoutopt_outoffset);
} else {
rc = write(outfd, buf + j, n - j);
}
if (rc == -1) {
if (errno == EINTR) goto TryAgain;
if (errno == EWOULDBLOCK) goto TryAgain; /* suboptimal */
return -1;
}
if (inoutopt_inoffset) *inoutopt_inoffset += rc;
if (inoutopt_outoffset) *inoutopt_outoffset += rc;
}
}
return i;
}
File renamed without changes.
+10 -11
View File
@@ -21,21 +21,20 @@
#include "libc/sysv/consts/o.h"
/**
* Creates file.
* Creates new file, returning open()'d file descriptor.
*
* This is equivalent to saying:
* This function is shorthand for:
*
* int fd = openat(AT_FDCWD, file, O_CREAT | O_WRONLY | O_TRUNC, mode);
* open(file, O_CREAT | O_WRONLY | O_TRUNC, mode)
*
* @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
* @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()
* @asyncsignalsafe
* @restartable
* @threadsafe
* @vforksafe
*/
int creat(const char *file, uint32_t mode) {
dontdiscard int creat(const char *file, uint32_t mode) {
return openat(AT_FDCWD, file, O_CREAT | O_WRONLY | O_TRUNC, mode);
}
+7 -5
View File
@@ -16,7 +16,6 @@
│ 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/internal.h"
#include "libc/calls/state.internal.h"
@@ -28,12 +27,15 @@
#include "libc/sysv/consts/o.h"
#include "libc/sysv/errfuns.h"
// Implements dup(), dup2(), dup3(), and F_DUPFD for Windows.
/**
* Implements dup(), dup2(), dup3(), and F_DUPFD for Windows.
*/
textwindows int sys_dup_nt(int oldfd, int newfd, int flags, int start) {
int64_t rc, proc, handle;
_unassert(oldfd >= 0);
_unassert(newfd >= -1);
_unassert(!(flags & ~O_CLOEXEC));
// validate the api usage
if (oldfd < 0) return ebadf();
if (flags & ~O_CLOEXEC) return einval();
__fds_lock();
+4 -5
View File
@@ -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"
/**
@@ -32,16 +32,15 @@
*
* @param fd remains open afterwards
* @return some arbitrary new number for fd
* @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
* @raise EOPNOTSUPP if zipos file
* @raise EBADF if fd isn't open
* @asyncsignalsafe
* @vforksafe
*/
int dup(int fd) {
int rc;
if (__isfdkind(fd, kFdZip)) {
rc = enotsup();
rc = eopnotsupp();
} else if (!IsWindows()) {
rc = sys_dup(fd);
} else {
+4 -7
View File
@@ -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,19 +38,16 @@
* @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 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 EBADF is oldfd isn't open
* @raise EBADF is newfd negative or too big
* @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 = enotsup();
rc = eopnotsupp();
} else if (!IsWindows()) {
rc = sys_dup2(oldfd, newfd);
} else if (newfd < 0) {
+21 -32
View File
@@ -16,52 +16,41 @@
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/assert.h"
#include "libc/intrin/strace.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/thread.h"
#define F_DUP2FD 10
#define F_DUP2FD_CLOEXEC 18
static struct Dup3 {
pthread_once_t once;
bool demodernize;
} g_dup3;
static void sys_dup3_test(void) {
int e = errno;
__sys_dup3(-1, -1, 0);
if ((g_dup3.demodernize = errno == ENOSYS)) {
STRACE("demodernizing %s() due to %s", "dup3", "ENOSYS");
}
errno = e;
}
int32_t sys_dup3(int32_t oldfd, int32_t newfd, int flags) {
int how;
_unassert(oldfd >= 0);
_unassert(newfd >= 0);
_unassert(!(flags & ~O_CLOEXEC));
if (IsFreebsd()) {
if (flags & O_CLOEXEC) {
how = F_DUP2FD_CLOEXEC;
static bool once;
static bool demodernize;
int olderr, how, fd;
if (!once) {
olderr = errno;
fd = __sys_dup3(oldfd, newfd, flags);
if (fd == -1 && errno == ENOSYS) {
STRACE("demodernizing %s() due to %s", "dup3", "RHEL5:CVE-2010-3301");
demodernize = true;
once = true;
errno = olderr;
} else {
how = F_DUP2FD;
once = true;
return fd;
}
return __sys_fcntl(oldfd, how, newfd);
}
pthread_once(&g_dup3.once, sys_dup3_test);
if (!g_dup3.demodernize) {
} else if (!demodernize) {
return __sys_dup3(oldfd, newfd, flags);
}
if (oldfd == newfd) return einval();
if (flags & ~O_CLOEXEC) return einval();
if (IsFreebsd()) {
how = flags & O_CLOEXEC ? F_DUP2FD_CLOEXEC : F_DUP2FD;
return __sys_fcntl(oldfd, how, newfd);
} else {
return __fixupnewfd(sys_dup2(oldfd, newfd), flags);
}
+11 -14
View File
@@ -18,11 +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/consts/o.h"
#include "libc/sysv/errfuns.h"
/**
@@ -38,25 +37,23 @@
* @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 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 EINVAL if flags has unsupported bits
* @raise EINVAL if newfd equals oldfd
* @raise EBADF is oldfd isn't open
* @raise EBADF is newfd negative or too big
* @raise EINTR if a signal handler was called
* @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) {
int rc;
if (oldfd == newfd || (flags & ~O_CLOEXEC)) {
rc = einval(); // NetBSD doesn't do this
} else if (oldfd < 0 || newfd < 0) {
rc = ebadf();
} else if (__isfdkind(oldfd, kFdZip)) {
rc = enotsup();
if (__isfdkind(oldfd, kFdZip)) {
rc = eopnotsupp();
} else if (oldfd == newfd) {
rc = einval();
} else if (!IsWindows()) {
rc = sys_dup3(oldfd, newfd, flags);
} else if (newfd < 0) {
rc = ebadf();
} else {
rc = sys_dup_nt(oldfd, newfd, flags, -1);
}
+1 -1
View File
@@ -99,7 +99,7 @@ textwindows int sys_execve_nt(const char *program, char *const argv[],
startinfo.hStdError = __getfdhandleactual(2);
// spawn the process
rc = ntspawn(program, argv, envp, 0, 0, 0, true, 0, 0, &startinfo, &procinfo);
rc = ntspawn(program, argv, envp, 0, 0, 0, 1, 0, 0, &startinfo, &procinfo);
if (rc == -1) {
STRACE("panic: unrecoverable ntspawn(%#s) error: %m", program);
__imp_ExitProcess(6543);
+12 -22
View File
@@ -17,7 +17,6 @@
│ 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"
@@ -36,42 +35,33 @@
* @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 amode can be `R_OK`, `W_OK`, `X_OK`, or `F_OK`
* @param flags can have `AT_EACCESS` and/or `AT_SYMLINK_NOFOLLOW`
* @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+
* @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 amode, int flags) {
int faccessat(int dirfd, const char *path, int mode, uint32_t flags) {
int e, rc;
struct ZiposUri zipname;
if (!path || (IsAsan() && !__asan_is_valid(path, 1))) {
if (IsAsan() && !__asan_is_valid(path, 1)) {
rc = efault();
} 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 (_weaken(__zipos_notat) &&
_weaken(__zipos_notat)(dirfd, path) == -1) {
rc = -1; /* TODO(jart): implement me */
} else if (!IsWindows()) {
e = errno;
if (!flags) goto NoFlags;
if ((rc = sys_faccessat2(dirfd, path, amode, flags)) == -1) {
if ((rc = sys_faccessat2(dirfd, path, mode, flags)) == -1) {
if (errno == ENOSYS) {
errno = e;
NoFlags:
rc = sys_faccessat(dirfd, path, amode, flags);
rc = sys_faccessat(dirfd, path, mode, flags);
}
}
} else {
rc = sys_faccessat_nt(dirfd, path, amode, flags);
rc = sys_faccessat_nt(dirfd, path, mode, flags);
}
STRACE("faccessat(%s, %#s, %#o, %#x) → %d% m", DescribeDirfd(dirfd), path,
amode, flags, rc);
mode, flags, rc);
return rc;
}
-6
View File
@@ -21,7 +21,6 @@
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/nt/createfile.h"
#include "libc/nt/enum/fileflagandattributes.h"
#include "libc/nt/enum/filetype.h"
#include "libc/nt/files.h"
#include "libc/nt/runtime.h"
#include "libc/sysv/consts/madv.h"
@@ -34,7 +33,6 @@ textwindows int sys_fadvise_nt(int fd, uint64_t offset, uint64_t len,
int rc, flags, mode;
uint32_t perm, share, attr;
if ((int64_t)len < 0) return einval();
if (!__isfdkind(fd, kFdFile)) return ebadf();
h1 = g_fds.p[fd].handle;
mode = g_fds.p[fd].mode;
@@ -59,10 +57,6 @@ textwindows int sys_fadvise_nt(int fd, uint64_t offset, uint64_t len,
return -1;
}
if (GetFileType(h1) == kNtFileTypePipe) {
return espipe();
}
// MSDN says only these are allowed, otherwise it returns EINVAL.
attr &= kNtFileFlagBackupSemantics | kNtFileFlagDeleteOnClose |
kNtFileFlagNoBuffering | kNtFileFlagOpenNoRecall |
+7 -30
View File
@@ -16,17 +16,11 @@
│ 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/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/str/str.h"
#include "libc/sysv/errfuns.h"
int sys_fadvise_netbsd(int, int, int64_t, int64_t, int) asm("sys_fadvise");
/**
* Drops hints to O/S about intended I/O behavior.
@@ -34,33 +28,16 @@ int sys_fadvise_netbsd(int, int, int64_t, int64_t, int) asm("sys_fadvise");
* It makes a huge difference. For example, when copying a large file,
* it can stop the system from persisting GBs of useless memory content.
*
* @param len 0 means until end of file
* @param len 0 means ‘til end of file
* @param advice can be MADV_SEQUENTIAL, MADV_RANDOM, etc.
* @return 0 on success, or -1 w/ errno
* @raise EBADF if `fd` isn't a valid file descriptor
* @raise ESPIPE if `fd` refers to a pipe
* @raise EINVAL if `advice` was invalid
* @raise ENOSYS on XNU and OpenBSD
* @return -1 on error
*/
int fadvise(int fd, uint64_t offset, uint64_t len, int advice) {
int rc, e = errno;
if (IsLinux()) {
rc = sys_fadvise(fd, offset, len, advice);
} else if (IsFreebsd() || IsNetbsd()) {
if (IsFreebsd()) {
rc = sys_fadvise(fd, offset, len, advice);
} else {
rc = sys_fadvise_netbsd(fd, offset, offset, len, advice);
}
_npassert(rc >= 0);
if (rc) {
errno = rc;
rc = -1;
}
} else if (IsWindows()) {
rc = sys_fadvise_nt(fd, offset, len, advice);
int rc;
if (!IsWindows()) {
rc = sys_fadvise(fd, offset, len, advice); /* linux & freebsd */
} else {
rc = enosys();
rc = sys_fadvise_nt(fd, offset, len, advice);
}
STRACE("fadvise(%d, %'lu, %'lu, %d) → %d% m", fd, offset, len, advice, rc);
return rc;
+13 -5
View File
@@ -23,12 +23,20 @@
#include "libc/nt/files.h"
#include "libc/sysv/errfuns.h"
int sys_chdir_nt_impl(char16_t[hasatleast PATH_MAX], uint32_t);
textwindows int sys_fchdir_nt(int dirfd) {
uint32_t len;
char16_t dir[PATH_MAX];
if (!__isfdkind(dirfd, kFdFile)) return ebadf();
return sys_chdir_nt_impl(
dir, GetFinalPathNameByHandle(g_fds.p[dirfd].handle, dir, ARRAYLEN(dir),
kNtFileNameNormalized | kNtVolumeNameDos));
len = GetFinalPathNameByHandle(g_fds.p[dirfd].handle, dir, ARRAYLEN(dir),
kNtFileNameNormalized | kNtVolumeNameDos);
if (len + 1 + 1 > ARRAYLEN(dir)) return enametoolong();
if (dir[len - 1] != u'\\') {
dir[len + 0] = u'\\';
dir[len + 1] = u'\0';
}
if (SetCurrentDirectory(dir)) {
return 0;
} else {
return __winerr();
}
}
+1 -2
View File
@@ -37,7 +37,6 @@
* @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()
@@ -48,7 +47,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 = enotsup();
rc = eopnotsupp();
} else if (!IsWindows()) {
rc = sys_fchmodat(dirfd, path, mode, flags);
} else {
+1 -2
View File
@@ -34,7 +34,6 @@
* @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
@@ -47,7 +46,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) {
rc = enotsup();
STRACE("zipos fchownat not supported yet");
} else {
rc = sys_fchownat(dirfd, path, uid, gid, flags);
}
+20 -3
View File
@@ -24,19 +24,28 @@
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/calls/wincrash.internal.h"
#include "libc/errno.h"
#include "libc/intrin/weaken.h"
#include "libc/log/backtrace.internal.h"
#include "libc/intrin/cmpxchg.h"
#include "libc/macros.internal.h"
#include "libc/nt/createfile.h"
#include "libc/nt/enum/accessmask.h"
#include "libc/nt/enum/fileflagandattributes.h"
#include "libc/nt/enum/filelockflags.h"
#include "libc/nt/enum/filesharemode.h"
#include "libc/nt/enum/formatmessageflags.h"
#include "libc/nt/errors.h"
#include "libc/nt/files.h"
#include "libc/nt/process.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/byhandlefileinformation.h"
#include "libc/nt/struct/overlapped.h"
#include "libc/nt/synchronization.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/fd.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/errfuns.h"
bool __force_sqlite_to_work_until_we_can_fix_it;
static textwindows int sys_fcntl_nt_dupfd(int fd, int cmd, int start) {
if (start < 0) return einval();
return sys_dup_nt(fd, -1, (cmd == F_DUPFD_CLOEXEC ? O_CLOEXEC : 0), start);
@@ -96,6 +105,7 @@ static textwindows int sys_fcntl_nt_lock(struct Fd *f, int cmd, uintptr_t arg) {
if (l->l_type == F_WRLCK) {
flags |= kNtLockfileExclusiveLock;
}
e = errno;
ok = LockFileEx(f->handle, flags, 0, len, len >> 32, &ov);
if (cmd == F_GETLK) {
if (ok) {
@@ -108,7 +118,14 @@ static textwindows int sys_fcntl_nt_lock(struct Fd *f, int cmd, uintptr_t arg) {
ok = true;
}
}
return ok ? 0 : -1;
if (ok) {
return 0;
} else if (__force_sqlite_to_work_until_we_can_fix_it) {
errno = e;
return 0;
} else {
return -1;
}
}
if (l->l_type == F_UNLCK) {
+13 -93
View File
@@ -18,15 +18,11 @@
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/calls/struct/flock.h"
#include "libc/calls/struct/flock.internal.h"
#include "libc/calls/syscall-nt.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/errfuns.h"
#include "libc/zipos/zipos.internal.h"
@@ -41,56 +37,18 @@
* CHECK_GE((newfd = fcntl(oldfd, F_DUPFD, 3)), 3);
* CHECK_GE((newfd = fcntl(oldfd, F_DUPFD_CLOEXEC, 3)), 3);
*
* This function implements POSIX Advisory Locks, which let independent
* processes (and on Windows, threads too!) read/write lock byte ranges
* of files. See `test/libc/calls/lock_test.c` for an example.
* This function implements POSIX Advisory Locks, e.g.
*
* CHECK_NE(-1, fcntl(zfd, F_SETLKW, &(struct flock){F_WRLCK}));
* // ...
* CHECK_NE(-1, fcntl(zfd, F_SETLK, &(struct flock){F_UNLCK}));
*
* Please be warned that locks currently do nothing on Windows since
* figuring out how to polyfill them correctly is a work in progress.
*
* @param fd is the file descriptor
* @param cmd can be one of:
* - `F_GETFD` gets `FD_CLOEXEC` status of `fd
* - `F_SETFD` sets `FD_CLOEXEC` status of `arg` file descriptor
* - `F_GETFL` returns file descriptor status flags
* - `F_SETFL` sets file descriptor status flags
* - `F_DUPFD` is like dup() but `arg` is a minimum result, e.g. 3
* - `F_DUPFD_CLOEXEC` ditto but sets `O_CLOEXEC` on returned fd
* - `F_SETLK` for record locking where `arg` is `struct flock`
* - `F_SETLKW` ditto but waits (i.e. blocks) for lock
* - `F_GETLK` to retrieve information about a record lock
* - `F_OFD_SETLK` for better locks on Linux and XNU
* - `F_OFD_SETLKW` for better locks on Linux and XNU
* - `F_OFD_GETLK` for better locks on Linux and XNU
* - `F_FULLFSYNC` on MacOS for fsync() with release barrier
* - `F_BARRIERFSYNC` on MacOS for fsync() with even more barriers
* - `F_SETNOSIGPIPE` on MacOS and NetBSD to control `SIGPIPE`
* - `F_GETNOSIGPIPE` on MacOS and NetBSD to control `SIGPIPE`
* - `F_GETPATH` on MacOS and NetBSD where arg is `char[PATH_MAX]`
* - `F_MAXFD` on NetBSD to get max open file descriptor
* - `F_NOCACHE` on MacOS to toggle data caching
* - `F_GETPIPE_SZ` on Linux to get pipe size
* - `F_SETPIPE_SZ` on Linux to set pipe size
* - `F_NOTIFY` raise `SIGIO` upon `fd` events in `arg` on Linux
* - `DN_ACCESS` for file access
* - `DN_MODIFY` for file modifications
* - `DN_CREATE` for file creations
* - `DN_DELETE` for file deletions
* - `DN_RENAME` for file renames
* - `DN_ATTRIB` for file attribute changes
* - `DN_MULTISHOT` bitwise or for realtime signals (non-coalesced)
* @param cmd can be F_{GET,SET}{FD,FL}, etc.
* @param arg can be FD_CLOEXEC, etc. depending
* @return 0 on success, or -1 w/ errno
* @raise EBADF if `fd` isn't a valid open file descriptor
* @raise EINVAL if `cmd` is unknown or unsupported by os
* @raise EINVAL if `cmd` is invalid or unsupported by os
* @raise EPERM if pledge() is in play w/o `stdio` or `flock` promise
* @raise ENOLCK if `F_SETLKW` would have exceeded `RLIMIT_LOCKS`
* @raise EPERM if `cmd` is `F_SETOWN` and we weren't authorized
* @raise ESRCH if `cmd` is `F_SETOWN` and process group not found
* @raise EDEADLK if `cmd` was `F_SETLKW` and waiting would deadlock
* @raise EMFILE if `cmd` is `F_DUPFD` or `F_DUPFD_CLOEXEC` and
* `RLIMIT_NOFILE` would be exceeded
* @asyncsignalsafe
* @restartable
*/
@@ -98,58 +56,20 @@ int fcntl(int fd, int cmd, ...) {
int rc;
va_list va;
uintptr_t arg;
va_start(va, cmd);
arg = va_arg(va, uintptr_t);
va_end(va);
if (fd >= 0) {
if (cmd >= 0) {
if (fd < g_fds.n && g_fds.p[fd].kind == kFdZip) {
rc = _weaken(__zipos_fcntl)(fd, cmd, arg);
} else if (!IsWindows()) {
rc = sys_fcntl(fd, cmd, arg);
} else {
rc = sys_fcntl_nt(fd, cmd, arg);
}
if (fd < g_fds.n && g_fds.p[fd].kind == kFdZip) {
rc = _weaken(__zipos_fcntl)(fd, cmd, arg);
} else if (!IsWindows()) {
rc = sys_fcntl(fd, cmd, arg);
} else {
rc = einval();
rc = sys_fcntl_nt(fd, cmd, arg);
}
} else {
rc = ebadf();
rc = einval();
}
#ifdef SYSDEBUG
if (cmd == F_GETFD || //
cmd == F_GETOWN || //
cmd == F_FULLFSYNC || //
cmd == F_BARRIERFSYNC || //
cmd == F_MAXFD) {
STRACE("fcntl(%d, %s) → %d% m", fd, DescribeFcntlCmd(cmd), rc);
} else if (cmd == F_GETFL) {
STRACE("fcntl(%d, %s) → %s% m", fd, DescribeFcntlCmd(cmd),
DescribeOpenFlags(rc));
} else if (cmd == F_SETLK || //
cmd == F_SETLKW || //
cmd == F_GETLK || //
((SupportsLinux() || SupportsXnu()) && //
cmd != -1 && //
(cmd == F_OFD_SETLK || //
cmd == F_OFD_SETLKW || //
cmd == F_OFD_GETLK))) {
STRACE("fcntl(%d, %s, %s) → %d% m", fd, DescribeFcntlCmd(cmd),
DescribeFlock(cmd, (struct flock *)arg), rc);
} else if ((SupportsNetbsd() || SupportsXnu()) && cmd != -1 &&
cmd == F_GETPATH) {
STRACE("fcntl(%d, %s, [%s]) → %d% m", fd, DescribeFcntlCmd(cmd),
!rc ? (const char *)arg : "n/a", rc);
} else if (SupportsLinux() && cmd != -1 && cmd == F_NOTIFY) {
STRACE("fcntl(%d, %s, %s) → %d% m", fd, DescribeFcntlCmd(cmd),
DescribeDnotifyFlags(arg), rc);
} else {
STRACE("fcntl(%d, %s, %ld) → %#x% m", fd, DescribeFcntlCmd(cmd), arg, rc);
}
#endif
STRACE("fcntl(%d, %d, %p) → %#x% m", fd, cmd, arg, rc);
return rc;
}
+3 -5
View File
@@ -17,11 +17,10 @@
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.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/runtime/runtime.h"
/**
@@ -34,7 +33,6 @@
*/
int fdatasync(int fd) {
int rc;
struct stat st;
if (__nosync != 0x5453455454534146) {
if (!IsWindows()) {
rc = sys_fdatasync(fd);
@@ -43,8 +41,8 @@ int fdatasync(int fd) {
}
STRACE("fdatasync(%d) → %d% m", fd, rc);
} else {
rc = fstat(fd, &st);
STRACE("fdatasync_fake(%d) → %d% m", fd, rc);
rc = 0;
STRACE("fdatasync(%d) → disabled% m", fd);
}
return rc;
}
-78
View File
@@ -1,78 +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 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;
}
+5 -5
View File
@@ -16,19 +16,19 @@
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/assert.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/fd.h"
#include "libc/sysv/consts/o.h"
// Applies file descriptor fixups on XNU or old Linux.
// See __fixupnewsockfd() for socket file descriptors.
/**
* Applies file descriptor fixups on XNU or old Linux.
* @see __fixupnewsockfd() for socket file descriptors
*/
int __fixupnewfd(int fd, int flags) {
if (fd != -1) {
if (flags & O_CLOEXEC) {
_npassert(!__sys_fcntl(fd, F_SETFD, FD_CLOEXEC));
__sys_fcntl(fd, F_SETFD, FD_CLOEXEC);
}
}
return fd;
+12 -33
View File
@@ -17,49 +17,28 @@
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/internal.h"
#include "libc/calls/struct/fd.internal.h"
#include "libc/calls/syscall-nt.internal.h"
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/nt/enum/filelockflags.h"
#include "libc/nt/files.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/byhandlefileinformation.h"
#include "libc/nt/struct/overlapped.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/lock.h"
#include "libc/sysv/errfuns.h"
#define _LOCK_SH 0
#define _LOCK_EX kNtLockfileExclusiveLock
#define _LOCK_NB kNtLockfileFailImmediately
#define _LOCK_UN 8
textwindows int sys_flock_nt(int fd, int op) {
int64_t h;
struct NtOverlapped ov;
struct NtByHandleFileInformation info;
if (!__isfdkind(fd, kFdFile)) return ebadf();
h = g_fds.p[fd].handle;
struct NtOverlapped ov = {.hEvent = h};
if (!GetFileInformationByHandle(h, &info)) {
return __winerr();
}
if (op & _LOCK_UN) {
if (op & ~_LOCK_UN) {
return einval();
}
if (UnlockFileEx(h, 0, info.nFileSizeLow, info.nFileSizeHigh, &ov)) {
return 0;
} else {
return -1;
}
}
if (op & ~(_LOCK_SH | _LOCK_EX | _LOCK_NB)) {
return einval();
}
if (LockFileEx(h, op, 0, info.nFileSizeLow, info.nFileSizeHigh, &ov)) {
bzero(&ov, sizeof(ov));
if (GetFileInformationByHandle(g_fds.p[fd].handle, &info) &&
((!(op & LOCK_UN) &&
LockFileEx(g_fds.p[fd].handle, op, 0, info.nFileSizeLow,
info.nFileSizeHigh, &ov)) ||
((op & LOCK_UN) && UnlockFileEx(g_fds.p[fd].handle, 0, info.nFileSizeLow,
info.nFileSizeHigh, &ov)))) {
return 0;
} else {
return -1;
return __winerr();
}
}
+1 -1
View File
@@ -24,7 +24,7 @@
#include "libc/sysv/errfuns.h"
/**
* Forms fstat() on System Five.
* Supports fstat(), etc. implementations.
* @asyncsignalsafe
*/
int32_t sys_fstat(int32_t fd, struct stat *st) {
+1 -1
View File
@@ -23,7 +23,7 @@
#include "libc/sysv/errfuns.h"
/**
* Performs fstatat() on System Five.
* Supports stat(), lstat(), fstatat(), etc. implementations.
* @asyncsignalsafe
*/
int32_t sys_fstatat(int32_t dirfd, const char *path, struct stat *st,
+3 -5
View File
@@ -17,11 +17,10 @@
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.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/runtime/runtime.h"
/**
@@ -34,7 +33,6 @@
*/
int fsync(int fd) {
int rc;
struct stat st;
if (__nosync != 0x5453455454534146) {
if (!IsWindows()) {
rc = sys_fsync(fd);
@@ -43,8 +41,8 @@ int fsync(int fd) {
}
STRACE("fysnc(%d) → %d% m", fd, rc);
} else {
rc = fstat(fd, &st);
STRACE("fsync_fake(%d) → %d% m", fd, rc);
rc = 0;
STRACE("fsync(%d) → disabled% m", fd);
}
return rc;
}
+2 -11
View File
@@ -16,12 +16,9 @@
│ 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) {
@@ -31,13 +28,7 @@ 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);
_npassert(SetFilePointerEx(handle, tell, NULL, kNtFileBegin));
}
if (ok) {
return 0;
} else if (GetLastError() == kNtErrorAccessDenied) {
return einval(); // ftruncate() doesn't raise EACCES
} else {
return __winerr();
SetFilePointerEx(handle, tell, NULL, kNtFileBegin);
}
return ok ? 0 : __winerr();
}
+8 -42
View File
@@ -18,65 +18,31 @@
╚─────────────────────────────────────────────────────────────────────────────*/
#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 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.
* Changes size of file.
*
* @param fd must be open for writing
* @param length may be greater than current current file size
* @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
* @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 = ebadf();
} else if (__isfdkind(fd, kFdZip)) {
rc = enotsup();
} else if (IsMetal()) {
rc = enosys();
rc = einval();
} else if (!IsWindows()) {
rc = sys_ftruncate(fd, length, length);
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();
if (fd >= g_fds.n) rc = ebadf();
rc = sys_ftruncate_nt(g_fds.p[fd].handle, length);
}
STRACE("ftruncate(%d, %'ld) → %d% m", fd, length, rc);
return rc;
+5 -25
View File
@@ -16,36 +16,16 @@
│ 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"
/**
* Changes access/modified time on open file, the modern way.
* Sets atime/mtime on file descriptor.
*
* XNU only has microsecond (1e-6) accuracy. Windows only has
* hectonanosecond (1e-7) accuracy. RHEL5 (Linux c. 2007) doesn't
* support this system call.
* This function is the same as `utimensat(fd, 0, ts, 0)`.
*
* @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
* @param ts is atime/mtime, or null for current time
* @raise ENOSYS on RHEL5
*/
int futimens(int fd, const struct timespec ts[2]) {
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;
return utimensat(fd, 0, ts, 0);
}
-60
View File
@@ -1,60 +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 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;
}
+2
View File
@@ -19,5 +19,7 @@
#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];
+21 -16
View File
@@ -22,7 +22,6 @@
#include "libc/calls/weirdtypes.h"
#include "libc/dce.h"
#include "libc/macros.internal.h"
#include "libc/nt/accounting.h"
#include "libc/nt/dll.h"
#include "libc/nt/struct/systeminfo.h"
#include "libc/nt/systeminfo.h"
@@ -34,7 +33,7 @@
#define HW_NCPUONLINE_NETBSD 16
#define ALL_PROCESSOR_GROUPS 0xffff
static unsigned _getcpucount_linux(void) {
static unsigned GetCpuCountLinux(void) {
cpu_set_t s = {0};
if (sys_sched_getaffinity(0, sizeof(s), &s) != -1) {
return CPU_COUNT(&s);
@@ -43,7 +42,7 @@ static unsigned _getcpucount_linux(void) {
}
}
static unsigned _getcpucount_bsd(void) {
static unsigned GetCpuCountBsd(void) {
size_t n;
int c, cmd[2];
n = sizeof(c);
@@ -62,39 +61,45 @@ static unsigned _getcpucount_bsd(void) {
}
}
static unsigned _getcpucount_impl(void) {
static textwindows unsigned GetCpuCountWindows(void) {
struct NtSystemInfo si;
uint32_t (*f)(uint16_t);
if ((f = GetProcAddress(GetModuleHandle("KERNEL32"),
"GetMaximumProcessorCount"))) {
return f(ALL_PROCESSOR_GROUPS);
} else {
GetSystemInfo(&si);
return si.dwNumberOfProcessors;
}
}
static unsigned GetCpuCountImpl(void) {
if (!IsWindows()) {
if (!IsBsd()) {
return _getcpucount_linux();
return GetCpuCountLinux();
} else {
return _getcpucount_bsd();
return GetCpuCountBsd();
}
} else {
return GetMaximumProcessorCount(ALL_PROCESSOR_GROUPS);
return GetCpuCountWindows();
}
}
static int g_cpucount;
// precompute because process affinity on linux may change later
__attribute__((__constructor__)) static void _getcpucount_init(void) {
g_cpucount = _getcpucount_impl();
__attribute__((__constructor__)) static void init(void) {
g_cpucount = GetCpuCountImpl();
}
/**
* Returns number of CPUs in system.
*
* This is the same as the standard interface:
*
* sysconf(_SC_NPROCESSORS_ONLN);
*
* Except this function isn't a bloated diamond dependency.
*
* On Intel systems with HyperThreading this will return the number of
* cores multiplied by two.
*
* @return cpu count or 0 if it couldn't be determined
*/
unsigned _getcpucount(void) {
unsigned GetCpuCount(void) {
return g_cpucount;
}
+1 -1
View File
@@ -52,7 +52,7 @@ char *getcwd(char *buf, size_t size) {
return 0;
}
} else if (_weaken(malloc)) {
_unassert(!__vforked);
assert(!__vforked);
if (!size) size = PATH_MAX;
if (!(p = _weaken(malloc)(size))) {
STRACE("getcwd(%p, %'zu) %m", buf, size);
+1 -1
View File
@@ -17,9 +17,9 @@
│ 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/strace.internal.h"
#include "libc/runtime/runtime.h"
/**
+1 -1
View File
@@ -17,9 +17,9 @@
│ 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/strace.internal.h"
/**
* Returns effective user ID of calling process.
Loaded 100 of 1246 files, more files were not shown because too many files have changed in this diff. Show more