path
stringlengths 14
112
| content
stringlengths 0
6.32M
| size
int64 0
6.32M
| max_lines
int64 1
100k
| repo_name
stringclasses 2
values | autogenerated
bool 1
class |
---|---|---|---|---|---|
pledge/LICENSE | ISC License
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.
| 759 | 17 | jart/plegde | false |
pledge/.gitignore | # -*- conf -*-
/o
# TODO: Find some way to have Python write to o/
__pycache__
*.tmp
/.bochs.log
/HTAGS
/TAGS
/bx_enh_dbg.ini
/tool/emacs/*.elc
/perf.data
/perf.data.old
| 173 | 16 | jart/plegde | false |
pledge/Makefile | # Makefiles are prettier like this
ifeq ($(origin .RECIPEPREFIX), undefined)
$(error This Make does not support .RECIPEPREFIX. \
Please use GNU Make 3.82 or later)
endif
.RECIPEPREFIX = >
# Use bash as the shell
SHELL := bash
# ...And use strict flags with it to make sure things fail if a step in there
# fails
.SHELLFLAGS := -eu -o pipefail -c
# Delete the target file of a Make rule if it fails - this guards against
# broken files
.DELETE_ON_ERROR:
# --no-builtin-rules: I'd rather make my own rules myself, make, thanks :)
MAKEFLAGS += --no-builtin-rules
# We use `override` to enable setting part of CFLAGS on the command line
# This makes the compiler generate dependency files, which will solve any
# header-related dependency problems we could have had
override CFLAGS += -MMD -MP -MF [email protected]
# Make it simpler to include library include files
override CFLAGS += -I.
# We need functions provided by defining _GNU_SOURCE
override CFLAGS += -D_GNU_SOURCE
# We need to compile as PIC code since we're making shared libraries here
override CFLAGS += -fPIC
# LDFLAGS should contain CFLAGS (seperate so command-line can add to it, and
# to correspond to usual practice)
override LDFLAGS += $(CFLAGS)
OUTPUT_FOLDER = o/$(MODE)
.PHONY: all clean
all: $(OUTPUT_FOLDER)/pledge $(OUTPUT_FOLDER)/sandbox.so
# Note: we cannot merge the source file list for pledge and the sandbox as this may otherwise result in constructors calling forbidden syscalls in the sandbox
PLEDGE_SOURCE_FILES := cmd/pledge
PLEDGE_SOURCE_FILES += libc/calls/commandv libc/calls/getcpucount libc/calls/islinux
PLEDGE_SOURCE_FILES += libc/calls/landlock_add_rule libc/calls/landlock_create_ruleset
PLEDGE_SOURCE_FILES += libc/calls/landlock_restrict_self libc/calls/parsepromises
PLEDGE_SOURCE_FILES += libc/calls/pledge libc/calls/pledge-linux libc/calls/unveil
PLEDGE_SOURCE_FILES += libc/x/xdie libc/x/xjoinpaths libc/x/xmalloc libc/x/xrealloc
PLEDGE_SOURCE_FILES += libc/x/xstrcat libc/x/xstrdup
PLEDGE_SOURCE_FILES += libc/elf/checkelfaddress libc/elf/getelfsegmentheaderaddress
PLEDGE_SOURCE_FILES += libc/str/classifypath libc/str/endswith libc/str/isabspath
PLEDGE_SOURCE_FILES += libc/intrin/promises libc/intrin/pthread_setcancelstate
PLEDGE_SOURCE_FILES += libc/fmt/joinpaths libc/fmt/sizetol
PLEDGE_SOURCE_FILES += libc/runtime/isdynamicexecutable
PLEDGE_SOURCE_FILES += libc/sysv/calls/ioprio_set
SANDBOX_SOURCE_FILES := cmd/sandbox
SANDBOX_SOURCE_FILES += libc/calls/pledge-linux
SANDBOX_OBJECT_FILES := $(addprefix $(OUTPUT_FOLDER)/, $(addsuffix .o, $(SANDBOX_SOURCE_FILES)))
PLEDGE_OBJECT_FILES := $(addprefix $(OUTPUT_FOLDER)/, $(addsuffix .o, $(PLEDGE_SOURCE_FILES)))
# First we need to have a shared object for the sandbox
$(OUTPUT_FOLDER)/sandbox.so: $(SANDBOX_OBJECT_FILES)
> $(CC) $(LDFLAGS) -shared -o $@ $^
# Next we need to make an object file out of that shared object containing the shared object as a symbol
$(OUTPUT_FOLDER)/embedded-sandbox.o: $(OUTPUT_FOLDER)/sandbox.so
> ld -r -b binary -o $@ $^
# Finally we need to embed the sandbox into our executable so it can copy it out when needed
$(OUTPUT_FOLDER)/pledge: $(PLEDGE_OBJECT_FILES) $(OUTPUT_FOLDER)/embedded-sandbox.o
> $(CC) $(LDFLAGS) -o $@ $^
$(OUTPUT_FOLDER)/%.o: %.c
> @mkdir --parents $(OUTPUT_FOLDER)/cmd
> @mkdir --parents $(OUTPUT_FOLDER)/libc/calls
> @mkdir --parents $(OUTPUT_FOLDER)/libc/sysv/calls
> @mkdir --parents $(OUTPUT_FOLDER)/libc/str
> @mkdir --parents $(OUTPUT_FOLDER)/libc/mem
> @mkdir --parents $(OUTPUT_FOLDER)/libc/fmt
> @mkdir --parents $(OUTPUT_FOLDER)/libc/intrin
> @mkdir --parents $(OUTPUT_FOLDER)/libc/x
> @mkdir --parents $(OUTPUT_FOLDER)/libc/runtime
> @mkdir --parents $(OUTPUT_FOLDER)/libc/elf
> $(CC) -c $< -o $@ $(CFLAGS)
# Include dependencies for the object files
include $(shell [ -d $(OUTPUT_FOLDER)/obj ] && find $(OUTPUT_FOLDER)/ -type f -name '*.d')
# Remove all object, binary and other produced files
clean:
> rm -rf ./o/
| 3,966 | 108 | jart/plegde | false |
pledge/.clang-format | ---
BasedOnStyle: Google
StatementMacros:
- INITIALIZER
AlignConsecutiveMacros: true
AlignConsecutiveDeclarations: false
AlwaysBreakBeforeMultilineStrings: false
AllowShortFunctionsOnASingleLine: false
KeepEmptyLinesAtTheStartOfBlocks: true
ConstructorInitializerAllOnOneLineOrOnePerLine: true
IncludeBlocks: Merge
---
Language: Cpp
AllowShortFunctionsOnASingleLine: false
---
Language: Proto
...
| 399 | 18 | jart/plegde | false |
pledge/README.md | # pledge for linux
OpenBSD is an operating system that's famous for its focus on security.
Unfortunately, OpenBSD leader Theo states that there are only 7000 users
of OpenBSD. So it's a very small but elite group, that wields a
disproportionate influence; since we hear all the time about the awesome
security features these guys get to use, even though we usually can't
use them ourselves, *until now*.
Pledge was like the forbidden fruit we'd all covet when the boss says we
must use things like Linux. Why does it matter? It's because pledge()
actually makes security comprehensible. Linux has never really had a
security layer that mere mortals can understand. For example, let's say
you want to do something on Linux like control whether or not some
program you downloaded from the web is allowed to have telemetry. You'd
need to write stuff like this:
```c
static const struct sock_filter kFilter[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, syscall, 0, 14 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 2, 4 - 3, 0),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 10, 0, 13 - 4),
/* L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~0x80800),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 1, 8 - 7, 0),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 2, 0, 13 - 8),
/* L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 12 - 10, 0),
/*L10*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 6, 12 - 11, 0),
/*L11*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 17, 0, 13 - 11),
/*L12*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L13*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L14*/ /* next filter */
};
```
Oh my gosh. It's like we traded one form of security privilege for
another. OpenBSD limits security to a small pond, but makes it easy.
Linux is a big tent, but makes it impossibly hard. SECCOMP BPF might as
well be the Traditional Chinese of programming languages, since only a
small number of people who've devoted the oodles of time it takes to
understand code like what you see above have actually been able to
benefit from it. But if you've got OpenBSD privilege, then doing the
same thing becomes easy:
```c
pledge("stdio rpath", 0);
```
That's really all OpenBSD users have to do to prevent things like leaks
of confidential information. So how do we get it that simple on Linux?
The answer is to find someone with enough free time to figure out how to
use SECCOMP BPF to implement pledge. The latest volunteers are us, so
look upon our code ye mighty and despair.
| 2,697 | 56 | jart/plegde | false |
pledge/libc/macros.internal.h | #ifndef PLEDGE_LIBC_MACROS_INTERNAL_H_
#define PLEDGE_LIBC_MACROS_INTERNAL_H_
#define ROUNDUP(X, K) (((X) + (K)-1) & -(K))
#define ARRAYLEN(A) \
((sizeof(A) / sizeof(*(A))) / ((unsigned)!(sizeof(A) % sizeof(*(A)))))
#endif
| 227 | 9 | jart/plegde | false |
pledge/libc/dce.h | #ifndef PLEDGE_LIBC_DCE_H_
#define PLEDGE_LIBC_DCE_H_
#ifndef __linux__
#error "This program is extremely likely to only work properly on Linux !"
#endif
#define IsLinux() 1
#define IsWindows() 0
#define IsOpenbsd() 0
#endif
| 228 | 13 | jart/plegde | false |
pledge/libc/x/xdie.c | /*-*- 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 <stdlib.h>
#include "libc/x/x.h"
void xdie(void) {
abort();
}
| 1,910 | 25 | jart/plegde | false |
pledge/libc/x/xstrcat.c | /*-*- 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/str/str.h"
#include "libc/x/x.h"
/**
* Concatenates strings / chars to newly allocated memory, e.g.
*
* xstrcat("hi", ' ', "there")
*
* Or without the C99 helper macro:
*
* (xstrcat)("hi", ' ', "there", NULL)
*
* This goes twice as fast as the more powerful xasprintf(). It's not
* quadratic like strcat(). It's much slower than high-effort stpcpy(),
* particularly with string literals.
*
* @see gc()
*/
char *(xstrcat)(const char *s, ...) {
va_list va;
intptr_t q;
char *p, b[2];
size_t n, m, c;
n = 0;
c = 32;
p = xmalloc(c);
va_start(va, s);
do {
q = (intptr_t)s;
if (q > 0 && q <= 255) {
b[0] = q;
b[1] = '\0';
s = b;
m = 1;
} else {
m = strlen(s);
}
if (n + m + 1 > c) {
do {
c += c >> 1;
} while (n + m + 1 > c);
p = xrealloc(p, c);
}
memcpy(p + n, s, m + 1);
n += m;
} while ((s = va_arg(va, const char *)));
va_end(va);
return p;
}
| 2,827 | 68 | jart/plegde | false |
pledge/libc/x/xmalloc.c | /*-*- 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/x/x.h"
/**
* Allocates uninitialized memory, or dies.
*/
void *xmalloc(size_t bytes) {
void *res = malloc(bytes);
if (!res) xdie();
return res;
}
| 2,006 | 29 | jart/plegde | false |
pledge/libc/x/xstrdup.c | /*-*- 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/intrin/likely.h"
#include "libc/str/str.h"
#include "libc/x/x.h"
/**
* Allocates new copy of string, or dies.
*/
char *xstrdup(const char *s) {
size_t len = strlen(s);
char *s2 = malloc(len + 1);
if (UNLIKELY(!s2)) xdie();
return memcpy(s2, s, len + 1);
}
| 2,118 | 32 | jart/plegde | false |
pledge/libc/x/xjoinpaths.c | /*-*- 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/intrin/safemacros.internal.h"
#include "libc/str/path.h"
#include "libc/str/str.h"
#include "libc/x/x.h"
/**
* Joins paths, e.g.
*
* "a" + "b" â "a/b"
* "a/" + "b" â "a/b"
* "a" + "b/" â "a/b/"
* "a" + "/b" â "/b"
* "." + "b" â "b"
* "" + "b" â "b"
*
* @return newly allocated string of resulting path
*/
char *xjoinpaths(const char *path, const char *other) {
if (!*other) {
return xstrdup(path);
} else if (!*path) {
return xstrdup(other);
} else if (isabspath(other) || !strcmp(path, ".")) {
return xstrdup(other);
} else if (endswith(path, "/")) {
return xstrcat(path, other);
} else {
return xstrcat(path, (uintptr_t)'/', other);
}
}
| 2,580 | 49 | jart/plegde | false |
pledge/libc/x/xrealloc.c | /*-*- 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/x/x.h"
/**
* Allocates/expands/shrinks/frees memory, or die.
*
* This API enables you to do the following:
*
* p = xrealloc(p, n)
*
* The standard behaviors for realloc() still apply:
*
* - `!p` means xmalloc (returns non-NULL)
* - `p && n` means resize (returns non-NULL)
* - `p && !n` means free (returns NULL)
*
* The complexity of resizing is guaranteed to be amortized.
*/
void *xrealloc(void *p, size_t n) {
void *q;
q = realloc(p, n);
if (!q && !(p && !n)) xdie();
return q;
}
| 2,362 | 42 | jart/plegde | false |
pledge/libc/x/x.h | #ifndef PLEDGE_LIBC_X_X_H_
#define PLEDGE_LIBC_X_X_H_
#include "libc/integral/c.h"
_Noreturn void xdie(void);
void *xmalloc(size_t);
void *xrealloc(void *, size_t);
char *xstrdup(const char *);
char *xstrcat(const char *, ...);
#define xstrcat(...) (xstrcat)(__VA_ARGS__, NULL)
char *xjoinpaths(const char *, const char *);
#endif
| 334 | 15 | jart/plegde | false |
pledge/libc/fmt/conv.h | #ifndef PLEDGE_LIBC_SIZETOL_H_
#define PLEDGE_LIBC_SIZETOL_H_
#include "libc/integral/c.h"
long sizetol(const char *, long) paramsnonnull() libcesque;
#endif
| 161 | 9 | jart/plegde | false |
pledge/libc/fmt/sizetol.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/fmt/conv.h"
// #include "libc/fmt/fmt.h"
#include "libc/str/str.h"
// #include "libc/sysv/errfuns.h"
#include <errno.h>
static int GetExponent(int c) {
switch (c) {
case '\0':
case ' ':
case '\t':
return 0;
case 'k':
case 'K':
return 1;
case 'm':
case 'M':
return 2;
case 'g':
case 'G':
return 3;
case 't':
case 'T':
return 4;
case 'p':
case 'P':
return 5;
case 'e':
case 'E':
return 6;
default:
return -1;
}
}
/**
* Converts size string to long.
*
* The following unit suffixes may be used
*
* - `k` or `K` for kilo (multiply by ð¹)
* - `m` or `M` for mega (multiply by ð²)
* - `g` or `G` for giga (multiply by ð³)
* - `t` or `T` for tera (multiply by ðâ´)
* - `p` or `P` for peta (multiply by ðâµ)
* - `e` or `E` for exa (multiply by ðâ¶)
*
* If a permitted alpha character is supplied, then any additional
* characters after it (e.g. kbit, Mibit, TiB) are ignored. Spaces
* before the integer are ignored, and overflows will be detected.
*
* Negative numbers are permissible, as well as a leading `+` sign. To
* tell the difference between an error return and `-1` you must clear
* `errno` before calling and test whether it changed.
*
* @param s is non-null nul-terminated input string
* @param b is multiplier which should be 1000 or 1024
* @return size greater than or equal 0 or -1 on error
* @error EINVAL if error is due to bad syntax
* @error EOVERFLOW if error is due to overflow
*/
long sizetol(const char *s, long b) {
long x;
int c, e, d;
do {
c = *s++;
} while (c == ' ' || c == '\t');
d = c == '-' ? -1 : 1;
if (c == '-' || c == '+') c = *s++;
if (!isdigit(c)) {
errno = EINVAL;
return -1;
}
x = 0;
do {
if (__builtin_mul_overflow(x, 10, &x) ||
__builtin_add_overflow(x, (c - '0') * d, &x)) {
errno = EOVERFLOW;
return -1;
}
} while (isdigit((c = *s++)));
if ((e = GetExponent(c)) == -1) {
errno = EINVAL;
return -1;
}
while (e--) {
if (__builtin_mul_overflow(x, b, &x)) {
errno = EOVERFLOW;
return -1;
}
}
return x;
}
| 4,055 | 113 | jart/plegde | false |
pledge/libc/fmt/joinpaths.c | /*-*- 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/intrin/bits.h"
#include "libc/str/path.h"
#include "libc/str/str.h"
// #include "libc/sysv/errfuns.h"
/**
* Joins paths, e.g.
*
* 0 + 0 â 0
* "" + "" â ""
* "a" + 0 â "a"
* "a" + "" â "a/"
* 0 + "b" â "b"
* "" + "b" â "b"
* "." + "b" â "./b"
* "b" + "." â "b/."
* "a" + "b" â "a/b"
* "a/" + "b" â "a/b"
* "a" + "b/" â "a/b/"
* "a" + "/b" â "/b"
*
* @return joined path, which may be `buf`, `path`, or `other`, or null
* if (1) `buf` didn't have enough space, or (2) both `path` and
* `other` were null
*/
char *joinpaths(char *buf, size_t size, const char *path, const char *other) {
size_t pathlen, otherlen;
if (!other) return (char *)path;
if (!path) return (char *)other;
pathlen = strlen(path);
if (!pathlen || *other == '/') {
return (/*unconst*/ char *)other;
}
otherlen = strlen(other);
if (path[pathlen - 1] == '/') {
if (pathlen + otherlen + 1 <= size) {
memmove(buf, path, pathlen);
memmove(buf + pathlen, other, otherlen + 1);
return buf;
} else {
return 0;
}
} else {
if (pathlen + 1 + otherlen + 1 <= size) {
memmove(buf, path, pathlen);
buf[pathlen] = '/';
memmove(buf + pathlen + 1, other, otherlen + 1);
return buf;
} else {
return 0;
}
}
}
| 3,244 | 72 | jart/plegde | false |
pledge/libc/elf/getelfsegmentheaderaddress.c | /*-*- 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/elf/elf.h"
Elf64_Phdr *GetElfSegmentHeaderAddress(const Elf64_Ehdr *elf, size_t mapsize,
unsigned i) {
intptr_t addr =
((intptr_t)elf + (intptr_t)elf->e_phoff + (intptr_t)elf->e_phentsize * i);
CheckElfAddress(elf, mapsize, addr, elf->e_phentsize);
return (Elf64_Phdr *)addr;
}
| 2,181 | 28 | jart/plegde | false |
pledge/libc/elf/checkelfaddress.c | /*-*- 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/elf/elf.h"
#include "libc/runtime/runtime.h"
void CheckElfAddress(const Elf64_Ehdr *elf, size_t mapsize, intptr_t addr,
size_t addrsize) {
#if 1//!(TRUSTWORTHY + ELF_TRUSTWORTHY + 0) || ELF_UNTRUSTWORTHY + 0
if (addr < (intptr_t)elf || addr + addrsize > (intptr_t)elf + mapsize) {
/* kprintf("%p-%p falls outside interval %p-%p", // */
/* addr, addr + addrsize, // */
/* elf, (char *)elf + mapsize); // */
abort();
}
#endif
}
| 2,362 | 33 | jart/plegde | false |
pledge/libc/elf/elf.h | #ifndef PLEDGE_LIBC_ELF_ELF_H_
#define PLEDGE_LIBC_ELF_ELF_H_
#include <elf.h>
#include <stddef.h>
void CheckElfAddress(const Elf64_Ehdr *, size_t, intptr_t, size_t);
Elf64_Phdr *GetElfSegmentHeaderAddress(const Elf64_Ehdr *, size_t, unsigned);
#endif
| 255 | 11 | jart/plegde | false |
pledge/libc/calls/blockcancel.internal.h | #ifndef PLEDGE_LIBC_CALLS_BLOCKCANCEL_INTERNAL_H_
#define PLEDGE_LIBC_CALLS_BLOCKCANCEL_INTERNAL_H_
#define ALLOW_CANCELLATIONS \
pthread_allow_cancellations(_cancelState); \
} \
while (0)
void pthread_allow_cancellations(int);
#define BLOCK_CANCELLATIONS \
do { \
int _cancelState; \
_cancelState = pthread_block_cancellations()
int pthread_block_cancellations(void);
#endif
| 483 | 19 | jart/plegde | false |
pledge/libc/calls/getcpucount.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include <sched.h>
#include "libc/calls/calls.h"
#include "libc/runtime/runtime.h"
static unsigned _getcpucount_linux(void) {
cpu_set_t s = {0};
if (sched_getaffinity(0, sizeof(s), &s) != -1) {
return CPU_COUNT(&s);
} else {
return 0;
}
}
static unsigned _getcpucount_impl(void) {
return _getcpucount_linux();
}
static int g_cpucount;
// precompute because process affinity on linux may change later
__attribute__((__constructor__)) static void _getcpucount_init(void) {
g_cpucount = _getcpucount_impl();
}
/**
* 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) {
return g_cpucount;
}
| 2,779 | 60 | jart/plegde | false |
pledge/libc/calls/islinux.c | /*-*- 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 <errno.h>
#include <stdbool.h>
#include <sys/prctl.h>
#include "libc/dce.h"
#include "libc/runtime/runtime.h"
privileged bool is_linux_2_6_23(void) {
return prctl(PR_GET_SECCOMP) >= 0 || errno != EINVAL;
}
| 2,054 | 28 | jart/plegde | false |
pledge/libc/calls/parsepromises.c | /*-*- 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/pledge.internal.h"
#include "libc/macros.internal.h"
#include "libc/str/str.h"
static int FindPromise(const char *name) {
int i;
for (i = 0; i < ARRAYLEN(kPledge); ++i) {
if (!strcasecmp(name, kPledge[i].name)) {
return i;
}
}
return -1;
}
/**
* Parses the arguments to pledge() into a bitmask.
*
* @return 0 on success, or -1 if invalid
*/
int ParsePromises(const char *promises, unsigned long *out) {
int rc = 0;
int promise;
unsigned long ipromises;
char *tok, *state, *start, buf[256];
if (promises) {
ipromises = -1;
if (memccpy(buf, promises, 0, sizeof(buf))) {
start = buf;
while ((tok = strtok_r(start, " \t\r\n", &state))) {
if ((promise = FindPromise(tok)) != -1) {
ipromises &= ~(1ULL << promise);
} else {
rc = -1;
break;
}
start = 0;
}
} else {
rc = -1;
}
} else {
ipromises = 0;
}
if (!rc) {
*out = ipromises;
}
return rc;
}
| 2,854 | 67 | jart/plegde | false |
pledge/libc/calls/commandv.c | /*-*- 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/calls/struct/stat.h"
#include "libc/dce.h"
// #include "libc/errno.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/safemacros.internal.h"
// #include "libc/intrin/strace.internal.h"
// #include "libc/log/libfatal.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
/*
#include "libc/sysv/consts/ok.h"
#include "libc/sysv/consts/s.h"
#include "libc/sysv/errfuns.h"
*/
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
static bool IsExePath(const char *s, size_t n) {
return n >= 4 && (READ32LE(s + n - 4) == READ32LE(".exe") ||
READ32LE(s + n - 4) == READ32LE(".EXE"));
}
static bool IsComPath(const char *s, size_t n) {
return n >= 4 && (READ32LE(s + n - 4) == READ32LE(".com") ||
READ32LE(s + n - 4) == READ32LE(".COM"));
}
static bool IsComDbgPath(const char *s, size_t n) {
return n >= 8 && (READ64LE(s + n - 8) == READ64LE(".com.dbg") ||
READ64LE(s + n - 8) == READ64LE(".COM.DBG"));
}
static bool AccessCommand(const char *name, char *path, size_t pathsz,
size_t namelen, int *err, const char *suffix,
size_t pathlen) {
size_t suffixlen;
suffixlen = strlen(suffix);
if (IsWindows() && suffixlen == 0 && !IsExePath(name, namelen) &&
!IsComPath(name, namelen))
return false;
if (pathlen + 1 + namelen + suffixlen + 1 > pathsz) return false;
if (pathlen && (path[pathlen - 1] != '/' && path[pathlen - 1] != '\\')) {
path[pathlen] = !IsWindows() ? '/'
: memchr(path, '\\', pathlen) ? '\\'
: '/';
pathlen++;
}
memcpy(path + pathlen, name, namelen);
memcpy(path + pathlen + namelen, suffix, suffixlen + 1);
if (!access(path, X_OK)) {
struct stat st;
if (!stat(path, &st)) {
if (S_ISREG(st.st_mode)) {
return true;
} else {
errno = EACCES;
}
}
}
if (errno == EACCES || *err != EACCES) *err = errno;
return false;
}
static bool SearchPath(const char *name, char *path, size_t pathsz,
size_t namelen, int *err, const char *suffix) {
char sep;
size_t i;
const char *p;
if (!(p = getenv("PATH"))) p = "/bin:/usr/local/bin:/usr/bin";
sep = IsWindows() && strchr(p, ';') ? ';' : ':';
for (;;) {
for (i = 0; p[i] && p[i] != sep; ++i) {
if (i < pathsz) {
path[i] = p[i];
}
}
if (AccessCommand(name, path, pathsz, namelen, err, suffix, i)) {
return true;
}
if (p[i] == sep) {
p += i + 1;
} else {
break;
}
}
return false;
}
static bool FindCommand(const char *name, char *pb, size_t pbsz, size_t namelen,
bool pri, const char *suffix, int *err) {
if (pri && (memchr(name, '/', namelen) || memchr(name, '\\', namelen))) {
pb[0] = 0;
return AccessCommand(name, pb, pbsz, namelen, err, suffix, 0);
}
return SearchPath(name, pb, pbsz, namelen, err, suffix);
}
static bool FindVerbatim(const char *name, char *pb, size_t pbsz,
size_t namelen, bool pri, int *err) {
return FindCommand(name, pb, pbsz, namelen, pri, "", err);
}
static bool FindSuffixed(const char *name, char *pb, size_t pbsz,
size_t namelen, bool pri, int *err) {
return !IsExePath(name, namelen) && !IsComPath(name, namelen) &&
!IsComDbgPath(name, namelen) &&
(FindCommand(name, pb, pbsz, namelen, pri, ".com", err) ||
FindCommand(name, pb, pbsz, namelen, pri, ".exe", err));
}
/**
* Resolves full pathname of executable.
*
* @return execve()'able path, or NULL w/ errno
* @errno ENOENT, EACCES, ENOMEM
* @see free(), execvpe()
* @asyncsignalsafe
* @vforksafe
*/
char *commandv(const char *name, char *pathbuf, size_t pathbufsz) {
int e, f;
char *res;
size_t namelen;
res = 0;
if (!name) {
errno = EFAULT;
} else if (!(namelen = strlen(name))) {
errno = ENOENT;
} else if (namelen + 1 > pathbufsz) {
errno = ENAMETOOLONG;
} else {
e = errno;
f = ENOENT;
if ((IsWindows() &&
(FindSuffixed(name, pathbuf, pathbufsz, namelen, true, &f) ||
FindVerbatim(name, pathbuf, pathbufsz, namelen, true, &f) ||
FindSuffixed(name, pathbuf, pathbufsz, namelen, false, &f) ||
FindVerbatim(name, pathbuf, pathbufsz, namelen, false, &f))) ||
(!IsWindows() &&
(FindVerbatim(name, pathbuf, pathbufsz, namelen, true, &f) ||
FindSuffixed(name, pathbuf, pathbufsz, namelen, true, &f) ||
FindVerbatim(name, pathbuf, pathbufsz, namelen, false, &f) ||
FindSuffixed(name, pathbuf, pathbufsz, namelen, false, &f)))) {
errno = e;
res = pathbuf;
} else {
errno = f;
}
}
return res;
}
| 6,718 | 173 | jart/plegde | false |
pledge/libc/calls/unveil.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
/*
#include "libc/assert.h"
*/
#include "libc/calls/blockcancel.internal.h"
#include "libc/calls/calls.h"
#include "libc/calls/landlock.h"
/*
#include "libc/calls/struct/bpf.h"
#include "libc/calls/struct/filter.h"
#include "libc/calls/struct/seccomp.h"
#include "libc/calls/struct/stat.h"
#include "libc/calls/struct/stat.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
*/
#include "libc/calls/syscall_support-sysv.internal.h"
/*
#include "libc/errno.h"
*/
#include "libc/fmt/conv.h"
/*
#include "libc/intrin/strace.internal.h"
*/
#include "libc/macros.internal.h"
/*
#include "libc/nexgen32e/vendor.internal.h"
#include "libc/runtime/internal.h"
*/
#include "libc/runtime/runtime.h"
#include "libc/runtime/stack.h"
#include "libc/str/path.h"
#include "libc/str/str.h"
/*
#include "libc/sysv/consts/at.h"
#include "libc/sysv/consts/audit.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/fd.h"
#include "libc/sysv/consts/nrlinux.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/pr.h"
#include "libc/sysv/consts/s.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/tls.h"
*/
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <limits.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
#define OFF(f) offsetof(struct seccomp_data, f)
#define UNVEIL_READ \
(LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR | \
LANDLOCK_ACCESS_FS_REFER)
#define UNVEIL_WRITE \
(LANDLOCK_ACCESS_FS_WRITE_FILE | LANDLOCK_ACCESS_FS_TRUNCATE)
#define UNVEIL_EXEC (LANDLOCK_ACCESS_FS_EXECUTE)
#define UNVEIL_CREATE \
(LANDLOCK_ACCESS_FS_MAKE_CHAR | LANDLOCK_ACCESS_FS_MAKE_DIR | \
LANDLOCK_ACCESS_FS_MAKE_REG | LANDLOCK_ACCESS_FS_MAKE_SOCK | \
LANDLOCK_ACCESS_FS_MAKE_FIFO | LANDLOCK_ACCESS_FS_MAKE_BLOCK | \
LANDLOCK_ACCESS_FS_MAKE_SYM)
#define FILE_BITS \
(LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_WRITE_FILE | \
LANDLOCK_ACCESS_FS_EXECUTE)
static struct sock_filter kUnveilBlacklistAbiVersionBelow3[] = {
#if 0 // Should we have this ? It certainly means things don't work on other
// architectures than x86-64 as-is... (TODO check this up later when
// relevant)
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(arch)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_X86_64, 1, 0),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
#endif
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_truncate, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_setxattr, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (1 & SECCOMP_RET_DATA)),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
static struct sock_filter kUnveilBlacklistLatestAbi[] = {
#if 0
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(arch)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_X86_64, 1, 0),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
#endif
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_setxattr, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (1 & SECCOMP_RET_DATA)),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
static int landlock_abi_version;
__attribute__((__constructor__)) void init_landlock_version() {
landlock_abi_version =
landlock_create_ruleset(0, 0, LANDLOCK_CREATE_RULESET_VERSION);
}
/**
* Long living state for landlock calls.
* fs_mask is set to use all the access rights from the latest landlock ABI.
* On init, the current supported abi is checked and unavailable rights are
* masked off.
*
* As of 6.2, the latest abi is v3.
*
* TODO:
* - Integrate with pledge and remove the file access?
* - Stuff state into the .protected section?
*/
_Thread_local static struct {
uint64_t fs_mask;
int fd;
} State;
static int unveil_final(void) {
int e, rc;
struct sock_fprog sandbox = {
.filter = kUnveilBlacklistLatestAbi,
.len = ARRAYLEN(kUnveilBlacklistLatestAbi),
};
if (landlock_abi_version < 3) {
sandbox = (struct sock_fprog){
.filter = kUnveilBlacklistAbiVersionBelow3,
.len = ARRAYLEN(kUnveilBlacklistAbiVersionBelow3),
};
}
e = errno;
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
errno = e;
if ((rc = landlock_restrict_self(State.fd, 0)) != -1 &&
(rc = close(State.fd)) != -1 &&
(rc = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &sandbox)) != -1) {
State.fd = 0;
}
return rc;
}
static int err_close(int rc, int fd) {
int serrno = errno;
close(fd);
errno = serrno;
return rc;
}
static int unveil_init(void) {
int rc, fd;
State.fs_mask = UNVEIL_READ | UNVEIL_WRITE | UNVEIL_EXEC | UNVEIL_CREATE;
if (landlock_abi_version == -1) {
if (errno == EOPNOTSUPP) {
errno = ENOSYS;
}
return -1;
}
if (landlock_abi_version < 2) {
State.fs_mask &= ~LANDLOCK_ACCESS_FS_REFER;
}
if (landlock_abi_version < 3) {
State.fs_mask &= ~LANDLOCK_ACCESS_FS_TRUNCATE;
}
const struct landlock_ruleset_attr attr = {
.handled_access_fs = State.fs_mask,
};
// [undocumented] landlock_create_ruleset() always returns o_cloexec
// assert(__sys_fcntl(rc, F_GETFD, 0) == FD_CLOEXEC);
if ((rc = landlock_create_ruleset(&attr, sizeof(attr), 0)) < 0) return -1;
// grant file descriptor a higher number that's less likely to interfere
if ((fd = fcntl(rc, F_DUPFD_CLOEXEC, 100)) == -1) {
return err_close(-1, rc);
}
if (close(rc) == -1) {
return err_close(-1, fd);
}
State.fd = fd;
return 0;
}
int sys_unveil_linux(const char *path, const char *permissions) {
int rc;
const char *dir;
const char *last;
const char *next;
struct {
char lbuf[PATH_MAX];
char buf1[PATH_MAX];
char buf2[PATH_MAX];
char buf3[PATH_MAX];
char buf4[PATH_MAX];
} b;
CheckLargeStackAllocation(&b, sizeof(b));
if (!State.fd && (rc = unveil_init()) == -1) return rc;
if ((path && !permissions) || (!path && permissions)) {
errno = EINVAL;
return -1;
}
if (!path && !permissions) return unveil_final();
struct landlock_path_beneath_attr pb = {0};
for (const char *c = permissions; *c != '\0'; c++) {
switch (*c) {
case 'r':
pb.allowed_access |= UNVEIL_READ;
break;
case 'w':
pb.allowed_access |= UNVEIL_WRITE;
break;
case 'x':
pb.allowed_access |= UNVEIL_EXEC;
break;
case 'c':
pb.allowed_access |= UNVEIL_CREATE;
break;
default:
errno = EINVAL;
return -1;
}
}
pb.allowed_access &= State.fs_mask;
// landlock exposes all metadata, so we only technically need to add
// realpath(path) to the ruleset. however a corner case exists where
// it isn't valid, e.g. /dev/stdin -> /proc/2834/fd/pipe:[51032], so
// we'll need to work around this, by adding the path which is valid
if (strlen(path) + 1 > PATH_MAX) {
errno = ENAMETOOLONG;
return -1;
}
last = path;
next = path;
for (int i = 0;; ++i) {
if (i == 64) {
// give up
errno = ELOOP;
return -1;
}
int err = errno;
if ((rc = readlinkat(AT_FDCWD, next, b.lbuf, PATH_MAX)) != -1) {
if (rc < PATH_MAX) {
// we need to nul-terminate
b.lbuf[rc] = 0;
// last = next
strcpy(b.buf1, next);
last = b.buf1;
// next = join(dirname(next), link)
strcpy(b.buf2, next);
dir = dirname(b.buf2);
if ((next = joinpaths(b.buf3, PATH_MAX, dir, b.lbuf))) {
// next now points to either: buf3, buf2, lbuf, rodata
strcpy(b.buf4, next);
next = b.buf4;
} else {
errno = ENAMETOOLONG;
return -1;
}
} else {
// symbolic link data was too long
errno = ENAMETOOLONG;
return -1;
}
} else if (errno == EINVAL) {
// next wasn't a symbolic link
errno = err;
path = next;
break;
} else if (i && (errno == ENOENT || errno == ENOTDIR)) {
// next is a broken symlink, use last
errno = err;
path = last;
break;
} else {
// readlink failed for some other reason
return -1;
}
}
// now we can open the path
BLOCK_CANCELLATIONS;
rc = open(path, O_PATH | O_NOFOLLOW | O_CLOEXEC, 0);
ALLOW_CANCELLATIONS;
if (rc == -1) return rc;
pb.parent_fd = rc;
struct stat st;
if ((rc = fstat(pb.parent_fd, &st)) == -1) {
return err_close(rc, pb.parent_fd);
}
if (!S_ISDIR(st.st_mode)) {
pb.allowed_access &= FILE_BITS;
}
if ((rc = landlock_add_rule(State.fd, LANDLOCK_RULE_PATH_BENEATH, &pb, 0))) {
return err_close(rc, pb.parent_fd);
}
close(pb.parent_fd);
return rc;
}
/**
* Makes files accessible, e.g.
*
* unveil(".", "r"); // current directory + children are visible
* unveil("/etc", "r"); // make /etc readable too
* unveil(0, 0); // commit and lock policy
*
* Unveiling restricts a view of the filesystem to a set of allowed
* paths with specific privileges.
*
* Once you start using unveil(), the entire file system is considered
* hidden. You then specify, by repeatedly calling unveil(), which paths
* should become unhidden. When you're finished, you call `unveil(0,0)`
* which commits your policy.
*
* This function requires OpenBSD or Linux 5.13+. We don't consider lack
* of system support to be an ENOSYS error, because the files will still
* become unveiled. Therefore we return 0 in such cases.
*
* There are some differences between unveil() on Linux versus OpenBSD.
*
* 1. Build your policy and lock it in one go. On OpenBSD, policies take
* effect immediately and may evolve as you continue to call unveil()
* but only in a more restrictive direction. On Linux, nothing will
* happen until you call `unveil(0,0)` which commits and locks.
*
* 2. Try not to overlap directory trees. On OpenBSD, if directory trees
* overlap, then the most restrictive policy will be used for a given
* file. On Linux overlapping may result in a less restrictive policy
* and possibly even undefined behavior.
*
* 3. OpenBSD and Linux disagree on error codes. On OpenBSD, accessing
* paths outside of the allowed set raises ENOENT, and accessing ones
* with incorrect permissions raises EACCES. On Linux, both these
* cases raise EACCES.
*
* 4. Unlike OpenBSD, Linux does nothing to conceal the existence of
* paths. Even with an unveil() policy in place, it's still possible
* to access the metadata of all files using functions like stat()
* and open(O_PATH), provided you know the path. A sandboxed process
* can always, for example, determine how many bytes of data are in
* /etc/passwd, even if the file isn't readable. But it's still not
* possible to use opendir() and go fishing for paths which weren't
* previously known.
*
* 5. Use ftruncate() rather than truncate() if you wish for portability to
* Linux kernels versions released before February 2022. One issue
* Landlock hadn't addressed as of ABI version 2 was restrictions over
* truncate() and setxattr() which could permit certain kinds of
* modifications to files outside the sandbox. When your policy is
* committed, we install a SECCOMP BPF filter to disable those calls,
* however similar trickery may be possible through other unaddressed
* calls like ioctl(). Using the pledge() function in addition to
* unveil() will solve this, since it installs a strong system call
* access policy. Linux 6.2 has improved this situation with Landlock
* ABI v3, which added the ability to control truncation operations -
* this means the SECCOMP BPF filter will only disable
* truncate() on Linux 6.1 or older
*
* 6. Set your process-wide policy at startup from the main thread. On
* OpenBSD unveil() will apply process-wide even when called from a
* child thread; whereas with Linux, calling unveil() from a thread
* will cause your ruleset to only apply to that thread in addition
* to any descendent threads it creates.
*
* 7. Always specify at least one path. OpenBSD has unclear semantics
* when `unveil(0,0)` is used without any previous calls.
*
* 8. On OpenBSD calling `unveil(0,0)` will prevent unveil() from being
* used again. On Linux this is allowed, because Landlock is able to
* do that securely, i.e. the second ruleset can only be a subset of
* the previous ones.
*
* This system call is supported natively on OpenBSD and polyfilled on
* Linux using the Landlock LSM[1].
*
* @param path is the file or directory to unveil
* @param permissions is a string consisting of zero or more of the
* following characters:
*
* - 'r' makes `path` available for read-only path operations,
* corresponding to the pledge promise "rpath".
*
* - `w` makes `path` available for write operations, corresponding
* to the pledge promise "wpath".
*
* - `x` makes `path` available for execute operations,
* corresponding to the pledge promises "exec" and "execnative".
*
* - `c` allows `path` to be created and removed, corresponding to
* the pledge promise "cpath".
*
* @return 0 on success, or -1 w/ errno
* @raise EINVAL if one argument is set and the other is not
* @raise EINVAL if an invalid character in `permissions` was found
* @raise EPERM if unveil() is called after locking
* @note on Linux this function requires Linux Kernel 5.13+ and version 6.2+
* to properly support truncation operations
* @see [1] https://docs.kernel.org/userspace-api/landlock.html
* @threadsafe
*/
int unveil(const char *path, const char *permissions) {
int e, rc;
e = errno;
/*if (IsGenuineBlink()) {
rc = 0; // blink doesn't support landlock
} else if (IsLinux()) {*/
rc = sys_unveil_linux(path, permissions);
/*} else {
abort();
rc = sys_unveil(path, permissions);
}*/
if (rc == -1 && errno == ENOSYS) {
errno = e;
rc = 0;
}
// STRACE("unveil(%#s, %#s) â %d% m", path, permissions, rc);
return rc;
}
| 16,207 | 446 | jart/plegde | false |
pledge/libc/calls/calls.h | #ifndef PLEDGE_LIBC_CALLS_H_
#define PLEDGE_LIBC_CALLS_H_
#include <stddef.h>
char *commandv(const char *, char *, size_t);
int ioprio_set(int, int, int);
int pledge(const char *, const char *);
int unveil(const char *, const char *);
#endif
| 245 | 12 | jart/plegde | false |
pledge/libc/calls/pledge.h | #ifndef PLEDGE_LIBC_CALLS_PLEDGE_H_
#define PLEDGE_LIBC_CALLS_PLEDGE_H_
#define PLEDGE_PENALTY_KILL_THREAD 0x0000
#define PLEDGE_PENALTY_KILL_PROCESS 0x0001
#define PLEDGE_PENALTY_RETURN_EPERM 0x0002
#define PLEDGE_PENALTY_MASK 0x000f
#define PLEDGE_STDERR_LOGGING 0x0010
extern int __pledge_mode;
#endif
| 324 | 14 | jart/plegde | false |
pledge/libc/calls/pledge-linux.c | /*-*- 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 <errno.h>
#include <fcntl.h>
#include <linux/audit.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <unistd.h>
#include "libc/calls/pledge.internal.h"
#include "libc/intrin/likely.h"
#include "libc/intrin/promises.internal.h"
#include "libc/macros.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/stack.h"
/**
* @fileoverview OpenBSD pledge() Polyfill Payload for GNU/Systemd
*
* This file contains only the minimum amount of Linux-specific code
* that's necessary to get a pledge() policy installed. This file is
* designed to not use static or tls memory or libc depnedencies, so
* it can be transplanted into codebases and injected into programs.
*/
#define SPECIAL 0xf000
#define SELF 0x8000
#define ADDRLESS 0x2000
#define INET 0x2000
#define LOCK 0x4000
#define NOEXEC 0x8000
#define EXEC 0x4000
#define READONLY 0x8000
#define WRITEONLY 0x4000
#define CREATONLY 0x2000
#define STDIO 0x8000
#define THREAD 0x8000
#define TTY 0x8000
#define UNIX 0x4000
#define NOBITS 0x8000
#define RESTRICT 0x1000
#define PLEDGE(pledge) pledge, ARRAYLEN(pledge)
#define OFF(f) offsetof(struct seccomp_data, f)
#define bsr(x) (__builtin_clzll(x) ^ 63)
#ifdef __x86_64__
#define MCONTEXT_SYSCALL_RESULT_REGISTER gregs[REG_RAX]
#define MCONTEXT_INSTRUCTION_POINTER gregs[REG_RIP]
#define ARCHITECTURE AUDIT_ARCH_X86_64
#elif defined(__aarch64__)
#define MCONTEXT_SYSCALL_RESULT_REGISTER regs[0]
#define MCONTEXT_INSTRUCTION_POINTER pc
#define ARCHITECTURE AUDIT_ARCH_AARCH64
#else
#error "unsupported architecture"
#endif
struct Filter {
size_t n;
struct sock_filter p[800];
};
static const struct thatispacked SyscallName {
uint16_t n;
const char *const s;
} kSyscallName[] = {
{__NR_exit, "exit"},
{__NR_exit_group, "exit_group"},
{__NR_read, "read"},
{__NR_write, "write"},
#ifdef __NR_open
{__NR_open, "open"},
#endif
{__NR_close, "close"},
#ifdef __NR_stat
{__NR_stat, "stat"},
#endif
{__NR_fstat, "fstat"},
#ifdef __NR_lstat
{__NR_lstat, "lstat"},
#endif
#ifdef __NR_poll
{__NR_poll, "poll"},
#endif
{__NR_ppoll, "ppoll"},
{__NR_brk, "brk"},
{__NR_rt_sigreturn, "sigreturn"},
{__NR_lseek, "lseek"},
{__NR_mmap, "mmap"},
{__NR_msync, "msync"},
{__NR_mprotect, "mprotect"},
{__NR_munmap, "munmap"},
{__NR_rt_sigaction, "sigaction"},
{__NR_rt_sigprocmask, "sigprocmask"},
{__NR_ioctl, "ioctl"},
{__NR_pread64, "pread"},
{__NR_pwrite64, "pwrite"},
{__NR_readv, "readv"},
{__NR_writev, "writev"},
#ifdef __NR_access
{__NR_access, "access"},
#endif
#ifdef __NR_pipe
{__NR_pipe, "pipe"},
#endif
#ifdef __NR_select
{__NR_select, "select"},
#endif
{__NR_pselect6, "pselect6"},
{__NR_sched_yield, "sched_yield"},
{__NR_mremap, "mremap"},
{__NR_mincore, "mincore"},
{__NR_madvise, "madvise"},
{__NR_shmget, "shmget"},
{__NR_shmat, "shmat"},
{__NR_shmctl, "shmctl"},
{__NR_dup, "dup"},
#ifdef __NR_dup2
{__NR_dup2, "dup2"},
#endif
#ifdef __NR_pause
{__NR_pause, "pause"},
#endif
{__NR_nanosleep, "nanosleep"},
{__NR_getitimer, "getitimer"},
{__NR_setitimer, "setitimer"},
#ifdef __NR_alarm
{__NR_alarm, "alarm"},
#endif
{__NR_getpid, "getpid"},
{__NR_sendfile, "sendfile"},
{__NR_socket, "socket"},
{__NR_connect, "connect"},
{__NR_accept, "accept"},
{__NR_sendto, "sendto"},
{__NR_recvfrom, "recvfrom"},
{__NR_sendmsg, "sendmsg"},
{__NR_recvmsg, "recvmsg"},
{__NR_shutdown, "shutdown"},
{__NR_bind, "bind"},
{__NR_listen, "listen"},
{__NR_getsockname, "getsockname"},
{__NR_getpeername, "getpeername"},
{__NR_socketpair, "socketpair"},
{__NR_setsockopt, "setsockopt"},
{__NR_getsockopt, "getsockopt"},
#ifdef __NR_fork
{__NR_fork, "fork"},
#endif
#ifdef __NR_vfork
{__NR_vfork, "vfork"},
#endif
{__NR_execve, "execve"},
{__NR_wait4, "wait4"},
{__NR_kill, "kill"},
{__NR_clone, "clone"},
{__NR_tkill, "tkill"},
{__NR_futex, "futex"},
{__NR_set_robust_list, "set_robust_list"},
{__NR_get_robust_list, "get_robust_list"},
{__NR_uname, "uname"},
{__NR_semget, "semget"},
{__NR_semop, "semop"},
{__NR_semctl, "semctl"},
{__NR_shmdt, "shmdt"},
{__NR_msgget, "msgget"},
{__NR_msgsnd, "msgsnd"},
{__NR_msgrcv, "msgrcv"},
{__NR_msgctl, "msgctl"},
{__NR_fcntl, "fcntl"},
{__NR_flock, "flock"},
{__NR_fsync, "fsync"},
{__NR_fdatasync, "fdatasync"},
{__NR_truncate, "truncate"},
{__NR_ftruncate, "ftruncate"},
{__NR_getcwd, "getcwd"},
{__NR_chdir, "chdir"},
{__NR_fchdir, "fchdir"},
#ifdef __NR_rename
{__NR_rename, "rename"},
#endif
#ifdef __NR_mkdir
{__NR_mkdir, "mkdir"},
#endif
#ifdef __NR_rmdir
{__NR_rmdir, "rmdir"},
#endif
#ifdef __NR_creat
{__NR_creat, "creat"},
#endif
#ifdef __NR_link
{__NR_link, "link"},
#endif
#ifdef __NR_unlink
{__NR_unlink, "unlink"},
#endif
#ifdef __NR_symlink
{__NR_symlink, "symlink"},
#endif
#ifdef __NR_readlink
{__NR_readlink, "readlink"},
#endif
#ifdef __NR_chmod
{__NR_chmod, "chmod"},
#endif
{__NR_fchmod, "fchmod"},
#ifdef __NR_chown
{__NR_chown, "chown"},
#endif
{__NR_fchown, "fchown"},
#ifdef __NR_lchown
{__NR_lchown, "lchown"},
#endif
{__NR_umask, "umask"},
{__NR_gettimeofday, "gettimeofday"},
{__NR_getrlimit, "getrlimit"},
{__NR_getrusage, "getrusage"},
{__NR_sysinfo, "sysinfo"},
{__NR_times, "times"},
{__NR_ptrace, "ptrace"},
{__NR_syslog, "syslog"},
{__NR_getuid, "getuid"},
{__NR_getgid, "getgid"},
{__NR_getppid, "getppid"},
#ifdef __NR_getpgrp
{__NR_getpgrp, "getpgrp"},
#endif
{__NR_setsid, "setsid"},
{__NR_getsid, "getsid"},
{__NR_getpgid, "getpgid"},
{__NR_setpgid, "setpgid"},
{__NR_geteuid, "geteuid"},
{__NR_getegid, "getegid"},
{__NR_getgroups, "getgroups"},
{__NR_setgroups, "setgroups"},
{__NR_setreuid, "setreuid"},
{__NR_setregid, "setregid"},
{__NR_setuid, "setuid"},
{__NR_setgid, "setgid"},
{__NR_setresuid, "setresuid"},
{__NR_setresgid, "setresgid"},
{__NR_getresuid, "getresuid"},
{__NR_getresgid, "getresgid"},
{__NR_rt_sigpending, "sigpending"},
{__NR_rt_sigsuspend, "sigsuspend"},
{__NR_sigaltstack, "sigaltstack"},
#ifdef __NR_mknod
{__NR_mknod, "mknod"},
#endif
{__NR_mknodat, "mknodat"},
{__NR_statfs, "statfs"},
{__NR_fstatfs, "fstatfs"},
{__NR_getpriority, "getpriority"},
{__NR_setpriority, "setpriority"},
{__NR_mlock, "mlock"},
{__NR_munlock, "munlock"},
{__NR_mlockall, "mlockall"},
{__NR_munlockall, "munlockall"},
{__NR_setrlimit, "setrlimit"},
{__NR_chroot, "chroot"},
{__NR_sync, "sync"},
{__NR_acct, "acct"},
{__NR_settimeofday, "settimeofday"},
{__NR_mount, "mount"},
{__NR_reboot, "reboot"},
{__NR_quotactl, "quotactl"},
{__NR_setfsuid, "setfsuid"},
{__NR_setfsgid, "setfsgid"},
{__NR_capget, "capget"},
{__NR_capset, "capset"},
{__NR_rt_sigtimedwait, "sigtimedwait"},
{__NR_rt_sigqueueinfo, "rt_sigqueueinfo"},
{__NR_personality, "personality"},
#ifdef __NR_ustat
{__NR_ustat, "ustat"},
#endif
#ifdef __NR_sysfs
{__NR_sysfs, "sysfs"},
#endif
{__NR_sched_setparam, "sched_setparam"},
{__NR_sched_getparam, "sched_getparam"},
{__NR_sched_setscheduler, "sched_setscheduler"},
{__NR_sched_getscheduler, "sched_getscheduler"},
{__NR_sched_get_priority_max, "sched_get_priority_max"},
{__NR_sched_get_priority_min, "sched_get_priority_min"},
{__NR_sched_rr_get_interval, "sched_rr_get_interval"},
{__NR_vhangup, "vhangup"},
#ifdef __NR_modify_ldt
{__NR_modify_ldt, "modify_ldt"},
#endif
{__NR_pivot_root, "pivot_root"},
#ifdef __NR__sysctl
{__NR__sysctl, "_sysctl"},
#endif
{__NR_prctl, "prctl"},
#ifdef __NR_arch_prctl
{__NR_arch_prctl, "arch_prctl"},
#endif
{__NR_adjtimex, "adjtimex"},
{__NR_umount2, "umount2"},
{__NR_swapon, "swapon"},
{__NR_swapoff, "swapoff"},
{__NR_sethostname, "sethostname"},
{__NR_setdomainname, "setdomainname"},
#ifdef __NR_iopl
{__NR_iopl, "iopl"},
#endif
#ifdef __NR_ioperm
{__NR_ioperm, "ioperm"},
#endif
{__NR_init_module, "init_module"},
{__NR_delete_module, "delete_module"},
{__NR_gettid, "gettid"},
{__NR_readahead, "readahead"},
{__NR_setxattr, "setxattr"},
{__NR_fsetxattr, "fsetxattr"},
{__NR_getxattr, "getxattr"},
{__NR_fgetxattr, "fgetxattr"},
{__NR_listxattr, "listxattr"},
{__NR_flistxattr, "flistxattr"},
{__NR_removexattr, "removexattr"},
{__NR_fremovexattr, "fremovexattr"},
{__NR_lsetxattr, "lsetxattr"},
{__NR_lgetxattr, "lgetxattr"},
{__NR_llistxattr, "llistxattr"},
{__NR_lremovexattr, "lremovexattr"},
{__NR_sched_setaffinity, "sched_setaffinity"},
{__NR_sched_getaffinity, "sched_getaffinity"},
{__NR_io_setup, "io_setup"},
{__NR_io_destroy, "io_destroy"},
{__NR_io_getevents, "io_getevents"},
{__NR_io_submit, "io_submit"},
{__NR_io_cancel, "io_cancel"},
{__NR_lookup_dcookie, "lookup_dcookie"},
#ifdef __NR_epoll_create
{__NR_epoll_create, "epoll_create"},
#endif
#ifdef __NR_epoll_wait
{__NR_epoll_wait, "epoll_wait"},
#endif
{__NR_epoll_ctl, "epoll_ctl"},
#ifdef __NR_getdents
{__NR_getdents, "getdents"},
#endif
{__NR_getdents64, "getdents64"},
{__NR_set_tid_address, "set_tid_address"},
{__NR_restart_syscall, "restart_syscall"},
{__NR_semtimedop, "semtimedop"},
{__NR_fadvise64, "fadvise"},
{__NR_timer_create, "timer_create"},
{__NR_timer_settime, "timer_settime"},
{__NR_timer_gettime, "timer_gettime"},
{__NR_timer_getoverrun, "timer_getoverrun"},
{__NR_timer_delete, "timer_delete"},
{__NR_clock_settime, "clock_settime"},
{__NR_clock_gettime, "clock_gettime"},
{__NR_clock_getres, "clock_getres"},
{__NR_clock_nanosleep, "clock_nanosleep"},
{__NR_tgkill, "tgkill"},
{__NR_mbind, "mbind"},
{__NR_set_mempolicy, "set_mempolicy"},
{__NR_get_mempolicy, "get_mempolicy"},
{__NR_mq_open, "mq_open"},
{__NR_mq_unlink, "mq_unlink"},
{__NR_mq_timedsend, "mq_timedsend"},
{__NR_mq_timedreceive, "mq_timedreceive"},
{__NR_mq_notify, "mq_notify"},
{__NR_mq_getsetattr, "mq_getsetattr"},
{__NR_kexec_load, "kexec_load"},
{__NR_waitid, "waitid"},
{__NR_add_key, "add_key"},
{__NR_request_key, "request_key"},
{__NR_keyctl, "keyctl"},
{__NR_ioprio_set, "ioprio_set"},
{__NR_ioprio_get, "ioprio_get"},
#ifdef __NR_inotify_init
{__NR_inotify_init, "inotify_init"},
#endif
{__NR_inotify_add_watch, "inotify_add_watch"},
{__NR_inotify_rm_watch, "inotify_rm_watch"},
{__NR_openat, "openat"},
{__NR_mkdirat, "mkdirat"},
{__NR_fchownat, "fchownat"},
#ifdef __NR_utime
{__NR_utime, "utime"},
#endif
#ifdef __NR_utimes
{__NR_utimes, "utimes"},
#endif
#ifdef __NR_futimesat
{__NR_futimesat, "futimesat"},
#endif
{__NR_newfstatat, "fstatat"},
{__NR_unlinkat, "unlinkat"},
{__NR_renameat, "renameat"},
{__NR_linkat, "linkat"},
{__NR_symlinkat, "symlinkat"},
{__NR_readlinkat, "readlinkat"},
{__NR_fchmodat, "fchmodat"},
{__NR_faccessat, "faccessat"},
{__NR_unshare, "unshare"},
{__NR_splice, "splice"},
{__NR_tee, "tee"},
{__NR_sync_file_range, "sync_file_range"},
{__NR_vmsplice, "vmsplice"},
{__NR_migrate_pages, "migrate_pages"},
{__NR_move_pages, "move_pages"},
{__NR_preadv, "preadv"},
{__NR_pwritev, "pwritev"},
{__NR_utimensat, "utimensat"},
{__NR_fallocate, "fallocate"},
{__NR_accept4, "accept4"},
{__NR_dup3, "dup3"},
{__NR_pipe2, "pipe2"},
{__NR_epoll_pwait, "epoll_pwait"},
{__NR_epoll_create1, "epoll_create1"},
{__NR_perf_event_open, "perf_event_open"},
{__NR_inotify_init1, "inotify_init1"},
{__NR_rt_tgsigqueueinfo, "rt_tgsigqueueinfo"},
#ifdef __NR_signalfd
{__NR_signalfd, "signalfd"},
#endif
{__NR_signalfd4, "signalfd4"},
#ifdef __NR_eventfd
{__NR_eventfd, "eventfd"},
#endif
{__NR_eventfd2, "eventfd2"},
{__NR_timerfd_create, "timerfd_create"},
{__NR_timerfd_settime, "timerfd_settime"},
{__NR_timerfd_gettime, "timerfd_gettime"},
{__NR_recvmmsg, "recvmmsg"},
{__NR_fanotify_init, "fanotify_init"},
{__NR_fanotify_mark, "fanotify_mark"},
{__NR_prlimit64, "prlimit"},
{__NR_name_to_handle_at, "name_to_handle_at"},
{__NR_open_by_handle_at, "open_by_handle_at"},
{__NR_clock_adjtime, "clock_adjtime"},
{__NR_syncfs, "syncfs"},
{__NR_sendmmsg, "sendmmsg"},
{__NR_setns, "setns"},
{__NR_getcpu, "getcpu"},
{__NR_process_vm_readv, "process_vm_readv"},
{__NR_process_vm_writev, "process_vm_writev"},
{__NR_kcmp, "kcmp"},
{__NR_finit_module, "finit_module"},
{__NR_sched_setattr, "sched_setattr"},
{__NR_sched_getattr, "sched_getattr"},
{__NR_renameat2, "renameat2"},
{__NR_seccomp, "seccomp"},
{__NR_getrandom, "getrandom"},
{__NR_memfd_create, "memfd_create"},
{__NR_kexec_file_load, "kexec_file_load"},
{__NR_bpf, "bpf"},
{__NR_execveat, "execveat"},
{__NR_userfaultfd, "userfaultfd"},
{__NR_membarrier, "membarrier"},
{__NR_mlock2, "mlock2"},
{__NR_copy_file_range, "copy_file_range"},
{__NR_preadv2, "preadv2"},
{__NR_pwritev2, "pwritev2"},
{__NR_pkey_mprotect, "pkey_mprotect"},
{__NR_pkey_alloc, "pkey_alloc"},
{__NR_pkey_free, "pkey_free"},
{__NR_statx, "statx"},
{__NR_io_pgetevents, "io_pgetevents"},
{__NR_rseq, "rseq"},
{__NR_pidfd_send_signal, "pidfd_send_signal"},
{__NR_io_uring_setup, "io_uring_setup"},
{__NR_io_uring_enter, "io_uring_enter"},
{__NR_io_uring_register, "io_uring_register"},
{__NR_open_tree, "open_tree"},
{__NR_move_mount, "move_mount"},
{__NR_fsopen, "fsopen"},
{__NR_fsconfig, "fsconfig"},
{__NR_fsmount, "fsmount"},
{__NR_fspick, "fspick"},
{__NR_pidfd_open, "pidfd_open"},
{__NR_clone3, "clone3"},
{__NR_close_range, "close_range"},
{__NR_openat2, "openat2"},
{__NR_pidfd_getfd, "pidfd_getfd"},
{__NR_faccessat2, "faccessat2"},
{__NR_process_madvise, "process_madvise"},
{__NR_epoll_pwait2, "epoll_pwait2"},
{__NR_mount_setattr, "mount_setattr"},
#ifdef __NR_quotactl_fd
{__NR_quotactl_fd, "quotactl_fd"},
#endif
{__NR_landlock_create_ruleset, "landlock_create_ruleset"},
{__NR_landlock_add_rule, "landlock_add_rule"},
{__NR_landlock_restrict_self, "landlock_restrict_self"},
#ifdef __NR_memfd_secret
{__NR_memfd_secret, "memfd_secret"},
#endif
#ifdef __NR_process_mrelease
{__NR_process_mrelease, "process_mrelease"},
#endif
#ifdef __NR_futex_waitv
{__NR_futex_waitv, "futex_waitv"},
#endif
#ifdef __NR_set_mempolicy_home_node
{__NR_set_mempolicy_home_node, "set_mempolicy_home_node"},
#endif
};
static const uint16_t kPledgeDefault[] = {
__NR_exit, // thread return / exit()
};
// stdio contains all the benign system calls. openbsd makes the
// assumption that preexisting file descriptors are trustworthy. we
// implement checking for these as a simple linear scan rather than
// binary search, since there doesn't appear to be any measurable
// difference in the latency of sched_yield() if it's at the start of
// the bpf script or the end.
static const uint16_t kPledgeStdio[] = {
__NR_rt_sigreturn,
__NR_restart_syscall,
__NR_exit_group,
__NR_sched_yield,
__NR_sched_getaffinity,
__NR_clock_getres,
__NR_clock_gettime,
__NR_clock_nanosleep,
__NR_close_range,
__NR_close,
__NR_write,
__NR_writev,
__NR_pwrite64,
__NR_pwritev,
__NR_pwritev2,
__NR_read,
__NR_readv,
__NR_pread64,
__NR_preadv,
__NR_preadv2,
__NR_dup,
#ifdef __NR_dup2
__NR_dup2,
#endif
__NR_dup3,
__NR_fchdir,
__NR_fcntl | STDIO,
__NR_fstat,
__NR_fsync,
__NR_sysinfo,
__NR_fdatasync,
__NR_ftruncate,
__NR_getrandom,
__NR_getgroups,
__NR_getpgid,
#ifdef __NR_getpgrp
__NR_getpgrp,
#endif
__NR_getpid,
__NR_gettid,
__NR_getuid,
__NR_getgid,
__NR_getsid,
__NR_getppid,
__NR_geteuid,
__NR_getegid,
__NR_getrlimit,
__NR_getresgid,
__NR_getresuid,
__NR_getitimer,
__NR_setitimer,
__NR_timerfd_create,
__NR_timerfd_settime,
__NR_timerfd_gettime,
__NR_copy_file_range,
__NR_gettimeofday,
__NR_sendfile,
__NR_vmsplice,
__NR_splice,
__NR_lseek,
__NR_tee,
__NR_brk,
__NR_msync,
__NR_mmap | NOEXEC,
__NR_mremap,
__NR_munmap,
__NR_mincore,
__NR_madvise,
__NR_fadvise64,
__NR_mprotect | NOEXEC,
#ifdef __NR_arch_prctl
__NR_arch_prctl,
#endif
__NR_migrate_pages,
__NR_sync_file_range,
__NR_set_tid_address,
__NR_membarrier,
__NR_nanosleep,
#ifdef __NR_pipe
__NR_pipe,
#endif
__NR_pipe2,
#ifdef __NR_poll
__NR_poll,
#endif
__NR_ppoll,
#ifdef __NR_select
__NR_select,
#endif
__NR_pselect6,
#ifdef __NR_epoll_create
__NR_epoll_create,
#endif
__NR_epoll_create1,
__NR_epoll_ctl,
#ifdef __NR_epoll_wait
__NR_epoll_wait,
#endif
__NR_epoll_pwait,
__NR_epoll_pwait2,
__NR_recvfrom,
__NR_sendto | ADDRLESS,
__NR_ioctl | RESTRICT,
#ifdef __NR_alarm
__NR_alarm,
#endif
#ifdef __NR_pause
__NR_pause,
#endif
__NR_shutdown,
#ifdef __NR_eventfd
__NR_eventfd,
#endif
__NR_eventfd2,
#ifdef __NR_signalfd
__NR_signalfd,
#endif
__NR_signalfd4,
__NR_rt_sigaction,
__NR_sigaltstack,
__NR_rt_sigprocmask,
__NR_rt_sigsuspend,
__NR_rt_sigpending,
__NR_kill | SELF,
__NR_tkill,
__NR_tgkill | SELF,
__NR_socketpair,
__NR_getrusage,
__NR_times,
__NR_umask,
__NR_wait4,
__NR_uname,
__NR_prctl | STDIO,
__NR_clone | THREAD,
__NR_futex,
__NR_set_robust_list,
__NR_get_robust_list,
__NR_prlimit64 | STDIO,
__NR_sched_getaffinity,
__NR_sched_setaffinity,
__NR_rt_sigtimedwait,
};
static const uint16_t kPledgeFlock[] = {
__NR_flock,
__NR_fcntl | LOCK,
};
static const uint16_t kPledgeRpath[] = {
__NR_chdir,
__NR_getcwd,
#ifdef __NR_open
__NR_open | READONLY,
#endif
__NR_openat | READONLY,
#ifdef __NR_stat
__NR_stat,
#endif
#ifdef __NR_lstat
__NR_lstat,
#endif
__NR_fstat,
__NR_newfstatat,
#ifdef __NR_access
__NR_access,
#endif
__NR_faccessat,
__NR_faccessat2,
#ifdef __NR_readlink
__NR_readlink,
#endif
__NR_readlinkat,
__NR_statfs,
__NR_fstatfs,
#ifdef __NR_getdents
__NR_getdents,
#endif
__NR_getdents64,
};
static const uint16_t kPledgeWpath[] = {
__NR_getcwd,
#ifdef __NR_open
__NR_open | WRITEONLY,
#endif
__NR_openat | WRITEONLY,
#ifdef __NR_stat
__NR_stat,
#endif
__NR_fstat,
#ifdef __NR_lstat
__NR_lstat,
#endif
__NR_newfstatat,
#ifdef __NR_access
__NR_access,
#endif
__NR_truncate,
__NR_faccessat,
__NR_faccessat2,
__NR_readlinkat,
#ifdef __NR_chmod
__NR_chmod | NOBITS,
#endif
__NR_fchmod | NOBITS,
__NR_fchmodat | NOBITS,
};
static const uint16_t kPledgeCpath[] = {
#ifdef __NR_open
__NR_open | CREATONLY,
#endif
__NR_openat | CREATONLY,
#ifdef __NR_creat
__NR_creat | RESTRICT,
#endif
#ifdef __NR_rename
__NR_rename,
#endif
__NR_renameat,
__NR_renameat2,
#ifdef __NR_link
__NR_link,
#endif
__NR_linkat,
#ifdef __NR_symlink
__NR_symlink,
#endif
__NR_symlinkat,
#ifdef __NR_rmdir
__NR_rmdir,
#endif
#ifdef __NR_unlink
__NR_unlink,
#endif
__NR_unlinkat,
#ifdef __NR_mkdir
__NR_mkdir,
#endif
__NR_mkdirat,
};
static const uint16_t kPledgeDpath[] = {
#ifdef __NR_mknod
__NR_mknod, //
#endif
__NR_mknodat, //
};
static const uint16_t kPledgeFattr[] = {
#ifdef __NR_chmod
__NR_chmod | NOBITS, //
#endif
__NR_fchmod | NOBITS, //
__NR_fchmodat | NOBITS, //
#ifdef __NR_utime
__NR_utime, //
#endif
#ifdef __NR_utimes
__NR_utimes, //
#endif
#ifdef __NR_futimesat
__NR_futimesat, //
#endif
__NR_utimensat, //
};
static const uint16_t kPledgeInet[] = {
__NR_socket | INET, //
__NR_listen, //
__NR_bind, //
__NR_sendto, //
__NR_connect, //
__NR_accept, //
__NR_accept4, //
__NR_ioctl | INET, //
__NR_getsockopt | RESTRICT, //
__NR_setsockopt | RESTRICT, //
__NR_getpeername, //
__NR_getsockname, //
};
static const uint16_t kPledgeUnix[] = {
__NR_socket | UNIX, //
__NR_listen, //
__NR_bind, //
__NR_connect, //
__NR_sendto, //
__NR_accept, //
__NR_accept4, //
__NR_getsockopt | RESTRICT, //
__NR_setsockopt | RESTRICT, //
__NR_getpeername, //
__NR_getsockname, //
};
static const uint16_t kPledgeDns[] = {
__NR_socket | INET, //
__NR_bind, //
__NR_sendto, //
__NR_connect, //
__NR_recvfrom, //
__NR_setsockopt | RESTRICT, //
__NR_newfstatat, //
__NR_openat | READONLY, //
__NR_read, //
__NR_close, //
};
static const uint16_t kPledgeTty[] = {
__NR_ioctl | TTY, //
};
static const uint16_t kPledgeRecvfd[] = {
__NR_recvmsg, //
__NR_recvmmsg, //
};
static const uint16_t kPledgeSendfd[] = {
__NR_sendmsg, //
__NR_sendmmsg, //
};
static const uint16_t kPledgeProc[] = {
#ifdef __NR_fork
__NR_fork, //
#endif
#ifdef __NR_vfork
__NR_vfork, //
#endif
__NR_clone | RESTRICT, //
__NR_kill, //
__NR_tgkill, //
__NR_setsid, //
__NR_setpgid, //
__NR_prlimit64, //
__NR_setrlimit, //
__NR_getpriority, //
__NR_setpriority, //
__NR_ioprio_get, //
__NR_ioprio_set, //
__NR_sched_getscheduler, //
__NR_sched_setscheduler, //
__NR_sched_get_priority_min, //
__NR_sched_get_priority_max, //
__NR_sched_getparam, //
__NR_sched_setparam, //
};
static const uint16_t kPledgeId[] = {
__NR_setuid, //
__NR_setreuid, //
__NR_setresuid, //
__NR_setgid, //
__NR_setregid, //
__NR_setresgid, //
__NR_setgroups, //
__NR_prlimit64, //
__NR_setrlimit, //
__NR_getpriority, //
__NR_setpriority, //
__NR_setfsuid, //
__NR_setfsgid, //
};
static const uint16_t kPledgeChown[] = {
#ifdef __NR_chown
__NR_chown, //
#endif
__NR_fchown, //
#ifdef __NR_lchown
__NR_lchown, //
#endif
__NR_fchownat, //
};
static const uint16_t kPledgeSettime[] = {
__NR_settimeofday, //
__NR_clock_adjtime, //
};
static const uint16_t kPledgeProtExec[] = {
__NR_mmap | EXEC, //
__NR_mprotect, //
};
static const uint16_t kPledgeExec[] = {
__NR_execve, //
__NR_execveat, //
};
static const uint16_t kPledgeUnveil[] = {
__NR_landlock_create_ruleset, //
__NR_landlock_add_rule, //
__NR_landlock_restrict_self, //
};
// placeholder group
//
// pledge.com checks this to do auto-unveiling
static const uint16_t kPledgeVminfo[] = {
__NR_sched_yield, //
};
// placeholder group
//
// pledge.com uses this to auto-unveil /tmp and $TMPPATH with rwc
// permissions. pledge() alone (without unveil() too) offers very
// little security here. consider using them together.
static const uint16_t kPledgeTmppath[] = {
#ifdef __NR_lstat
__NR_lstat, //
#endif
#ifdef __NR_unlink
__NR_unlink, //
#endif
__NR_unlinkat, //
};
const struct Pledges kPledge[PROMISE_LEN_] = {
[PROMISE_STDIO] = {"stdio", PLEDGE(kPledgeStdio)},
[PROMISE_RPATH] = {"rpath", PLEDGE(kPledgeRpath)},
[PROMISE_WPATH] = {"wpath", PLEDGE(kPledgeWpath)},
[PROMISE_CPATH] = {"cpath", PLEDGE(kPledgeCpath)},
[PROMISE_DPATH] = {"dpath", PLEDGE(kPledgeDpath)},
[PROMISE_FLOCK] = {"flock", PLEDGE(kPledgeFlock)},
[PROMISE_FATTR] = {"fattr", PLEDGE(kPledgeFattr)},
[PROMISE_INET] = {"inet", PLEDGE(kPledgeInet)},
[PROMISE_UNIX] = {"unix", PLEDGE(kPledgeUnix)},
[PROMISE_DNS] = {"dns", PLEDGE(kPledgeDns)},
[PROMISE_TTY] = {"tty", PLEDGE(kPledgeTty)},
[PROMISE_RECVFD] = {"recvfd", PLEDGE(kPledgeRecvfd)},
[PROMISE_SENDFD] = {"sendfd", PLEDGE(kPledgeSendfd)},
[PROMISE_PROC] = {"proc", PLEDGE(kPledgeProc)},
[PROMISE_EXEC] = {"exec", PLEDGE(kPledgeExec)},
[PROMISE_ID] = {"id", PLEDGE(kPledgeId)},
[PROMISE_UNVEIL] = {"unveil", PLEDGE(kPledgeUnveil)},
[PROMISE_SETTIME] = {"settime", PLEDGE(kPledgeSettime)},
[PROMISE_PROT_EXEC] = {"prot_exec", PLEDGE(kPledgeProtExec)},
[PROMISE_VMINFO] = {"vminfo", PLEDGE(kPledgeVminfo)},
[PROMISE_TMPPATH] = {"tmppath", PLEDGE(kPledgeTmppath)},
[PROMISE_CHOWN] = {"chown", PLEDGE(kPledgeChown)},
};
static const struct sock_filter kPledgeStart[] = {
// make sure this isn't an i386 binary or something
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(arch)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ARCHITECTURE, 1, 0),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
// each filter assumes ordinal is already loaded into accumulator
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
#ifdef __NR_memfd_secret
// forbid some system calls with ENOSYS (rather than EPERM)
BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, __NR_memfd_secret, 5, 0),
#else
BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, __NR_landlock_restrict_self + 1, 5, 0),
#endif
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_rseq, 4, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_memfd_create, 3, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_openat2, 2, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_clone3, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_statx, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (ENOSYS & SECCOMP_RET_DATA)),
};
static const struct sock_filter kFilterIgnoreExitGroup[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_exit_group, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (EPERM & SECCOMP_RET_DATA)),
};
static char *FixCpy(char p[17], uint64_t x, int k) {
while (k > 0) *p++ = "0123456789abcdef"[(x >> (k -= 4)) & 15];
*p = '\0';
return p;
}
static privileged char *HexCpy(char p[17], uint64_t x) {
return FixCpy(p, x, ROUNDUP(x ? bsr(x) + 1 : 1, 4));
}
static void Log(const char *s, ...) {
int ax;
va_list va;
va_start(va, s);
do ax = write(2, s, strlen(s));
while ((s = va_arg(va, const char *)));
va_end(va);
}
static void KillThisProcess(void) {
abort();
}
static void KillThisThread(void) {
int ax;
sigset_t full, empty;
sigfillset(&full);
sigemptyset(&empty);
sigaction(SIGABRT, &(struct sigaction){0}, 0);
sigprocmask(SIG_SETMASK, &full, 0);
ax = syscall(__NR_tkill, syscall(__NR_gettid), SIGABRT);
sigprocmask(SIG_SETMASK, &empty, 0);
syscall(__NR_exit, 128 + SIGABRT);
}
static const char *GetSyscallName(uint16_t n) {
int i;
for (i = 0; i < ARRAYLEN(kSyscallName); ++i) {
if (kSyscallName[i].n == n) {
return kSyscallName[i].s;
}
}
return "unknown";
}
static int HasSyscall(const struct Pledges *p, uint16_t n) {
int i;
for (i = 0; i < p->len; ++i) {
if (p->syscalls[i] == n) {
return 1;
}
if ((p->syscalls[i] & 0xfff) == n) {
return 2;
}
}
return 0;
}
static void OnSigSys(int sig, siginfo_t *si, void *vctx) {
bool found;
char ord[17], ip[17];
int i, ok, mode = si->si_errno;
ucontext_t *ctx = vctx;
ctx->uc_mcontext.MCONTEXT_SYSCALL_RESULT_REGISTER = -EPERM;
FixCpy(ord, si->si_syscall, 12);
HexCpy(ip, ctx->uc_mcontext.MCONTEXT_INSTRUCTION_POINTER);
for (found = i = 0; i < ARRAYLEN(kPledge); ++i) {
if (HasSyscall(kPledge + i, si->si_syscall)) {
Log("error: pledge ", kPledge[i].name, " for ",
GetSyscallName(si->si_syscall), " (ord=0x", ord, " ip=0x", ip, ")\n",
NULL);
found = true;
}
}
if (!found) {
Log("error: bad syscall (", GetSyscallName(si->si_syscall), " ord=0x", ord,
" ip=0x", ip, ")\n", NULL);
}
switch (mode & PLEDGE_PENALTY_MASK) {
case PLEDGE_PENALTY_KILL_PROCESS:
KillThisProcess();
// fallthrough
case PLEDGE_PENALTY_KILL_THREAD:
KillThisThread();
__builtin_trap();
default:
break;
}
}
static void MonitorSigSys(void) {
int ax;
struct sigaction sa = {
.sa_sigaction = OnSigSys,
.sa_flags = SA_SIGINFO | SA_RESTART,
};
// we block changing sigsys once pledge is installed
// so we aren't terribly concerned if this will fail
if (sigaction(SIGSYS, &sa, 0) == -1) {
__builtin_trap();
}
}
static void AppendFilter(struct Filter *f, const struct sock_filter *p,
size_t n) {
if (UNLIKELY(f->n + n > ARRAYLEN(f->p))) __builtin_trap();
memcpy(f->p + f->n, p, n * sizeof(*f->p));
f->n += n;
}
// The first argument of kill() must be
//
// - getpid()
//
static void AllowKillSelf(struct Filter *f) {
struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_kill, 0, 4),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, getpid(), 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
};
AppendFilter(f, PLEDGE(fragment));
}
// The first argument of tgkill() must be
//
// - getpid()
//
static void AllowTgkillSelf(struct Filter *f) {
struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_tgkill, 0, 4),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, getpid(), 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
};
AppendFilter(f, PLEDGE(fragment));
}
// The following system calls are allowed:
//
// - write(2) to allow logging
// - kill(getpid(), SIGABRT) to abort process
// - tkill(gettid(), SIGABRT) to abort thread
// - sigaction(SIGABRT) to force default signal handler
// - sigreturn() to return from signal handler
// - sigprocmask() to force signal delivery
//
static void AllowMonitor(struct Filter *f) {
struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_write, 0, 4),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 2, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_kill, 0, 6),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, getpid(), 0, 3),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SIGABRT, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_tkill, 0, 6),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, gettid(), 0, 3),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SIGABRT, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_rt_sigaction, 0, 4),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SIGABRT, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_rt_sigreturn, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_rt_sigprocmask, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
AppendFilter(f, PLEDGE(fragment));
}
// The first argument of sys_clone_linux() must NOT have:
//
// - CLONE_NEWNS (0x00020000)
// - CLONE_PTRACE (0x00002000)
// - CLONE_UNTRACED (0x00800000)
//
static void AllowCloneRestrict(struct Filter *f) {
// clang-format off
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_clone, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, CLONE_NEWNS | CLONE_PTRACE | CLONE_UNTRACED),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
// clang-format on
AppendFilter(f, PLEDGE(fragment));
}
// The first argument of sys_clone_linux() must have:
//
// - CLONE_VM (0x00000100)
// - CLONE_FS (0x00000200)
// - CLONE_FILES (0x00000400)
// - CLONE_THREAD (0x00010000)
// - CLONE_SIGHAND (0x00000800)
//
// The first argument of sys_clone_linux() must NOT have:
//
// - CLONE_NEWNS (0x00020000)
// - CLONE_PTRACE (0x00002000)
// - CLONE_UNTRACED (0x00800000)
//
static void AllowCloneThread(struct Filter *f) {
#define NEED (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_THREAD | CLONE_SIGHAND)
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_clone, 0, 9 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, NEED),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, NEED, 0, 8 - 4),
/*L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/*L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, CLONE_NEWNS | CLONE_PTRACE | CLONE_UNTRACED),
/*L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L7*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L9*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
#undef NEED
}
// The second argument of ioctl() must be one of:
//
// - FIONREAD (0x541b)
// - FIONBIO (0x5421)
// - FIOCLEX (0x5451)
// - FIONCLEX (0x5450)
//
static void AllowIoctlStdio(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_ioctl, 0, 7),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, FIONREAD, 3, 0),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, FIONBIO, 2, 0),
/*L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, FIOCLEX, 1, 0),
/*L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, FIONCLEX, 0, 1),
/*L6*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L8*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The second argument of ioctl() must be one of:
//
// - SIOCATMARK (0x8905)
//
static void AllowIoctlInet(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_ioctl, 0, 4),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SIOCATMARK, 0, 1),
/*L6*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L8*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The second argument of ioctl() must be one of:
//
// - TCGETS (0x5401)
// - TCSETS (0x5402)
// - TCSETSW (0x5403)
// - TCSETSF (0x5404)
// - TIOCGWINSZ (0x5413)
// - TIOCSPGRP (0x5410)
// - TIOCGPGRP (0x540f)
// - TIOCSWINSZ (0x5414)
// - TCFLSH (0x540b)
// - TCXONC (0x540a)
// - TCSBRK (0x5409)
// - TIOCSBRK (0x5427)
//
static void AllowIoctlTty(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_ioctl, 0, 15),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCGETS, 11, 0),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCSETS, 10, 0),
/* L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCSETSW, 9, 0),
/* L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCSETSF, 8, 0),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TIOCGWINSZ, 7, 0),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TIOCSPGRP, 6, 0),
/* L8*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TIOCGPGRP, 5, 0),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TIOCSWINSZ, 4, 0),
/*L10*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCFLSH, 3, 0),
/*L11*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCXONC, 2, 0),
/*L12*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCSBRK, 1, 0),
/*L13*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TIOCSBRK, 0, 1),
/*L14*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L15*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L16*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The level argument of getsockopt/setsockopt must be one of:
//
// - IPPROTO_IP (0)
// - SOL_SOCKET (1)
// - IPPROTO_TCP (6)
// - IPPROTO_IPV6 (41)
//
// The optname argument of getsockopt/setsockopt must be one of:
//
// - TCP_NODELAY (0x01)
// - TCP_CORK (0x03)
// - TCP_KEEPIDLE (0x04)
// - TCP_KEEPINTVL (0x05)
// - SO_TYPE (0x03)
// - SO_ERROR (0x04)
// - SO_DONTROUTE (0x05)
// - SO_BROADCAST (0x06)
// - SO_REUSEPORT (0x0f)
// - SO_REUSEADDR (0x02)
// - SO_KEEPALIVE (0x09)
// - SO_RCVTIMEO (0x14)
// - SO_SNDTIMEO (0x15)
// - IP_RECVTTL (0x0c)
// - IP_RECVERR (0x0b)
// - TCP_FASTOPEN (0x17)
// - TCP_FASTOPEN_CONNECT (0x1e)
// - IPV6_V6ONLY (0x1a)
// - TCP_QUICKACK (0x0c)
//
static void AllowSockoptRestrict(struct Filter *f) {
static const struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_getsockopt, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_setsockopt, 0, 29),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SOL_SOCKET, 3, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_TCP, 11, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_IP, 18, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_IPV6, 20, 23),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_TYPE, 7 + 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_ERROR, 6 + 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_BROADCAST, 5 + 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_REUSEPORT, 4 + 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_REUSEADDR, 3 + 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_KEEPALIVE, 2 + 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_RCVTIMEO, 1 + 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_SNDTIMEO, 0 + 13, 14),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCP_QUICKACK, 6 + 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCP_CORK, 5 + 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCP_NODELAY, 4 + 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCP_KEEPIDLE, 3 + 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCP_KEEPINTVL, 2 + 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCP_FASTOPEN, 1 + 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCP_FASTOPEN_CONNECT, 0 + 5, 6),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IP_RECVTTL, 1 + 2, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IP_RECVERR, 0 + 2, 3),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPV6_V6ONLY, 0 + 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
};
AppendFilter(f, PLEDGE(fragment));
}
// The flags parameter of mmap() must not have:
//
// - MAP_LOCKED (0x02000)
// - MAP_NONBLOCK (0x10000)
// - MAP_HUGETLB (0x40000)
//
static void AllowMmapExec(struct Filter *f) {
// long y = (long)__privileged_end;
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_mmap, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[3])), // flags
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, MAP_LOCKED | MAP_NONBLOCK | MAP_HUGETLB),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 5 - 4),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The prot parameter of mmap() may only have:
//
// - PROT_NONE
// - PROT_READ
// - PROT_WRITE
//
// The flags parameter must not have:
//
// - MAP_LOCKED (0x02000)
// - MAP_HUGETLB (0x40000)
//
static void AllowMmapNoexec(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_mmap, 0, 8),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])), // prot
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~(PROT_READ | PROT_WRITE)),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 8 - 4),
/*L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[3])), // flags
/*L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, MAP_LOCKED | MAP_HUGETLB),
/*L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L7*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L9*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The prot parameter of mprotect() may only have:
//
// - PROT_NONE (0)
// - PROT_READ (1)
// - PROT_WRITE (2)
//
static void AllowMprotectNoexec(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_mprotect, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])), // prot
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~(PROT_READ | PROT_WRITE)),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#ifdef __NR_open
// The open() system call is permitted only when
//
// - (flags & O_ACCMODE) == O_RDONLY
//
// The flags parameter of open() must not have:
//
// - O_CREAT (000000100)
// - O_TRUNC (000001000)
// - __O_TMPFILE (020000000)
//
static void AllowOpenReadonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_open, 0, 9 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_ACCMODE),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_RDONLY, 0, 8 - 4),
/*L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, __O_TMPFILE | O_TRUNC | O_CREAT),
/*L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L7*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L9*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#endif
// The open() system call is permitted only when
//
// - (flags & O_ACCMODE) == O_RDONLY
//
// The flags parameter of open() must not have:
//
// - O_CREAT (000000100)
// - O_TRUNC (000001000)
// - __O_TMPFILE (020000000)
//
static void AllowOpenatReadonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_openat, 0, 9 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_ACCMODE),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_RDONLY, 0, 8 - 4),
/*L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/*L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, __O_TMPFILE | O_TRUNC | O_CREAT),
/*L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L7*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L9*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#ifdef __NR_open
// The open() system call is permitted only when
//
// - (flags & O_ACCMODE) == O_WRONLY
// - (flags & O_ACCMODE) == O_RDWR
//
// The open() flags parameter must not contain
//
// - O_CREAT (000000100)
// - __O_TMPFILE (020000000)
//
static void AllowOpenWriteonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_open, 0, 10 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_ACCMODE),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_WRONLY, 1, 0),
/* L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_RDWR, 0, 9 - 5),
/* L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L6*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, __O_TMPFILE | O_CREAT),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/* L8*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/* L9*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L10*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#endif
// The open() system call is permitted only when
//
// - (flags & O_ACCMODE) == O_WRONLY
// - (flags & O_ACCMODE) == O_RDWR
//
// The openat() flags parameter must not contain
//
// - O_CREAT (000000100)
// - __O_TMPFILE (020000000)
//
static void AllowOpenatWriteonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_openat, 0, 10 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_ACCMODE),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_WRONLY, 1, 0),
/* L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_RDWR, 0, 9 - 5),
/* L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L6*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, __O_TMPFILE | O_CREAT),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/* L8*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/* L9*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L10*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#ifdef __NR_open
// If the flags parameter of open() has one of:
//
// - O_CREAT (000000100)
// - __O_TMPFILE (020000000)
//
// Then the mode parameter must not have:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static void AllowOpenCreatonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_open, 0, 12 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_CREAT),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_CREAT, 7 - 4, 0),
/* L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 020200000),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 020200000, 0, 10 - 7),
/* L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L8*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, S_ISVTX | S_ISGID | S_ISUID),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L10*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L11*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L12*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#endif
// If the flags parameter of openat() has one of:
//
// - O_CREAT (000000100)
// - __O_TMPFILE (020000000)
//
// Then the mode parameter must not have:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static void AllowOpenatCreatonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_openat, 0, 12 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_CREAT),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_CREAT, 7 - 4, 0),
/* L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 020200000),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 020200000, 0, 10 - 7),
/* L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[3])),
/* L8*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, S_ISVTX | S_ISGID | S_ISUID),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L10*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L11*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L12*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#ifdef __NR_creat
// Then the mode parameter must not have:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static void AllowCreatRestrict(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_creat, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, S_ISVTX | S_ISGID | S_ISUID),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#endif
// The second argument of fcntl() must be one of:
//
// - F_DUPFD (0)
// - F_DUPFD_CLOEXEC (1030)
// - F_GETFD (1)
// - F_SETFD (2)
// - F_GETFL (3)
// - F_SETFL (4)
//
static void AllowFcntlStdio(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_fcntl, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, F_DUPFD_CLOEXEC, 4 - 3, 0),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, 5, 5 - 4, 0),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
_Static_assert(F_DUPFD == 0 && F_GETFD == 1 && F_SETFD == 2 && F_GETFL == 3 && F_SETFL == 4, "This ensures that the above BPF_JGE statement will work correctly");
AppendFilter(f, PLEDGE(fragment));
}
// The second argument of fcntl() must be one of:
//
// - F_GETLK (0x05)
// - F_SETLK (0x06)
// - F_SETLKW (0x07)
// - F_OFD_GETLK (0x24)
// - F_OFD_SETLK (0x25)
// - F_OFD_SETLKW (0x26)
//
static void AllowFcntlLock(struct Filter *f) {
static const struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_fcntl, 0, 9),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, F_GETLK, 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, F_SETLK, 4, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, F_SETLKW, 3, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, F_OFD_GETLK, 2, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, F_OFD_SETLK, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, F_OFD_SETLKW, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
};
AppendFilter(f, PLEDGE(fragment));
}
// The addr parameter of sendto() must be
//
// - NULL
//
static void AllowSendtoAddrless(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_sendto, 0, 7 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[4]) + 0),
/*L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 6 - 3),
/*L3*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[4]) + 4),
/*L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 6 - 5),
/*L5*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L6*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L7*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The family parameter of socket() must be one of:
//
// - AF_INET (0x02)
// - AF_INET6 (0x0a)
//
// The type parameter of socket() will ignore:
//
// - SOCK_CLOEXEC (0x80000)
// - SOCK_NONBLOCK (0x00800)
//
// The type parameter of socket() must be one of:
//
// - SOCK_STREAM (0x01)
// - SOCK_DGRAM (0x02)
//
// The protocol parameter of socket() must be one of:
//
// - 0
// - IPPROTO_ICMP (0x01)
// - IPPROTO_TCP (0x06)
// - IPPROTO_UDP (0x11)
//
static void AllowSocketInet(struct Filter *f) {
// clang-format off
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_socket, 0, 15 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AF_INET, 1, 0),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AF_INET6, 0, 14 - 4),
/* L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~(SOCK_CLOEXEC | SOCK_NONBLOCK)),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SOCK_STREAM, 1, 0),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SOCK_DGRAM, 0, 14 - 8),
/* L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 3, 0),
/*L10*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_ICMP, 2, 0),
/*L11*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_TCP, 1, 0),
/*L12*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_UDP, 0, 1),
/*L13*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L14*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L15*/ /* next filter */
};
// clang-format on
AppendFilter(f, PLEDGE(fragment));
}
// The family parameter of socket() must be one of:
//
// - AF_UNIX (1)
// - AF_LOCAL (1)
//
// The type parameter of socket() will ignore:
//
// - SOCK_CLOEXEC (0x80000)
// - SOCK_NONBLOCK (0x00800)
//
// The type parameter of socket() must be one of:
//
// - SOCK_STREAM (1)
// - SOCK_DGRAM (2)
//
// The protocol parameter of socket() must be one of:
//
// - 0
//
static void AllowSocketUnix(struct Filter *f) {
// clang-format off
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_socket, 0, 11 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AF_UNIX, 0, 10 - 3),
/* L3*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~(SOCK_CLOEXEC | SOCK_NONBLOCK)),
/* L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SOCK_STREAM, 1, 0),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SOCK_DGRAM, 0, 10 - 7),
/* L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L8*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/* L9*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L10*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L11*/ /* next filter */
};
// clang-format on
AppendFilter(f, PLEDGE(fragment));
}
// The first parameter of prctl() can be any of
//
// - PR_SET_NAME (15)
// - PR_GET_NAME (16)
// - PR_GET_SECCOMP (21)
// - PR_SET_SECCOMP (22)
// - PR_SET_NO_NEW_PRIVS (38)
// - PR_CAPBSET_READ (23)
// - PR_CAPBSET_DROP (24)
//
static void AllowPrctlStdio(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_prctl, 0, 11 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, PR_SET_NAME, 6, 0),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, PR_GET_NAME, 5, 0),
/* L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, PR_GET_SECCOMP, 4, 0),
/* L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, PR_SET_SECCOMP, 3, 0),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, PR_CAPBSET_READ, 2, 0),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, PR_CAPBSET_DROP, 1, 0),
/* L8*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, PR_SET_NO_NEW_PRIVS, 0, 1),
/* L9*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L10*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L11*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#ifdef __NR_chmod
// The mode parameter of chmod() can't have the following:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static void AllowChmodNobits(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_chmod, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, S_ISVTX | S_ISGID | S_ISUID),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#endif
// The mode parameter of fchmod() can't have the following:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static void AllowFchmodNobits(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_fchmod, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 07000),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The mode parameter of fchmodat() can't have the following:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static void AllowFchmodatNobits(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_fchmodat, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, S_ISVTX | S_ISGID | S_ISUID),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The new_limit parameter of prlimit() must be
//
// - NULL (0)
//
static void AllowPrlimitStdio(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_prlimit64, 0, 7 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/*L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 6 - 3),
/*L3*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2]) + 4),
/*L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L5*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L6*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L7*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
static int CountUnspecial(const uint16_t *p, size_t len) {
int i, count;
for (count = i = 0; i < len; ++i) {
if (!(p[i] & SPECIAL)) {
++count;
}
}
return count;
}
static void AppendPledge(struct Filter *f, //
const uint16_t *p, //
size_t len) { //
int i, j, count;
// handle ordinals which allow syscalls regardless of args
// we put in extra effort here to reduce num of bpf instrs
if ((count = CountUnspecial(p, len))) {
if (count < 256) {
for (j = i = 0; i < len; ++i) {
if (p[i] & SPECIAL) continue;
// jump to ALLOW rule below if accumulator equals ordinal
struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, // instruction
p[i], // operand
count - j - 1, // jump if true displacement
j == count - 1), // jump if false displacement
};
AppendFilter(f, PLEDGE(fragment));
++j;
}
struct sock_filter fragment[] = {
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
AppendFilter(f, PLEDGE(fragment));
} else {
__builtin_trap();
}
}
// handle "special" ordinals which use hand-crafted bpf
for (i = 0; i < len; ++i) {
if (!(p[i] & SPECIAL)) continue;
switch (p[i]) {
case __NR_mmap | EXEC:
AllowMmapExec(f);
break;
case __NR_mmap | NOEXEC:
AllowMmapNoexec(f);
break;
case __NR_mprotect | NOEXEC:
AllowMprotectNoexec(f);
break;
#ifdef __NR_chmod
case __NR_chmod | NOBITS:
AllowChmodNobits(f);
break;
#endif
case __NR_fchmod | NOBITS:
AllowFchmodNobits(f);
break;
case __NR_fchmodat | NOBITS:
AllowFchmodatNobits(f);
break;
case __NR_prctl | STDIO:
AllowPrctlStdio(f);
break;
#ifdef __NR_open
case __NR_open | CREATONLY:
AllowOpenCreatonly(f);
break;
#endif
case __NR_openat | CREATONLY:
AllowOpenatCreatonly(f);
break;
#ifdef __NR_open
case __NR_open | READONLY:
AllowOpenReadonly(f);
break;
#endif
case __NR_openat | READONLY:
AllowOpenatReadonly(f);
break;
#ifdef __NR_open
case __NR_open | WRITEONLY:
AllowOpenWriteonly(f);
break;
#endif
case __NR_openat | WRITEONLY:
AllowOpenatWriteonly(f);
break;
case __NR_getsockopt | RESTRICT:
case __NR_setsockopt | RESTRICT:
AllowSockoptRestrict(f);
break;
#ifdef __NR_creat
case __NR_creat | RESTRICT:
AllowCreatRestrict(f);
break;
#endif
case __NR_fcntl | STDIO:
AllowFcntlStdio(f);
break;
case __NR_fcntl | LOCK:
AllowFcntlLock(f);
break;
case __NR_ioctl | RESTRICT:
AllowIoctlStdio(f);
break;
case __NR_ioctl | TTY:
AllowIoctlTty(f);
break;
case __NR_ioctl | INET:
AllowIoctlInet(f);
break;
case __NR_socket | INET:
AllowSocketInet(f);
break;
case __NR_socket | UNIX:
AllowSocketUnix(f);
break;
case __NR_sendto | ADDRLESS:
AllowSendtoAddrless(f);
break;
case __NR_clone | RESTRICT:
AllowCloneRestrict(f);
break;
case __NR_clone | THREAD:
AllowCloneThread(f);
break;
case __NR_prlimit64 | STDIO:
AllowPrlimitStdio(f);
break;
case __NR_kill | SELF:
AllowKillSelf(f);
break;
case __NR_tgkill | SELF:
AllowTgkillSelf(f);
break;
default:
__builtin_trap();
}
}
}
/**
* Installs SECCOMP BPF filter on Linux thread.
*
* @param ipromises is inverted integer bitmask of pledge() promises
* @return 0 on success, or negative error number on error
*/
int sys_pledge_linux(unsigned long ipromises, int mode) {
struct Filter f;
int i, e, rc = -1;
struct sock_filter sf[1] = {BPF_STMT(BPF_RET | BPF_K, 0)};
CheckLargeStackAllocation(&f, sizeof(f));
f.n = 0;
// set up the seccomp filter
AppendFilter(&f, PLEDGE(kPledgeStart));
if (ipromises == -1) {
// if we're pledging empty string, then avoid triggering a sigsys
// when _Exit() gets called since we need to fallback to _Exit1()
AppendFilter(&f, PLEDGE(kFilterIgnoreExitGroup));
}
AppendPledge(&f, PLEDGE(kPledgeDefault));
for (i = 0; i < ARRAYLEN(kPledge); ++i) {
if (~ipromises & (1ul << i)) {
if (kPledge[i].len) {
AppendPledge(&f, kPledge[i].syscalls, kPledge[i].len);
} else {
__builtin_trap();
}
}
}
// now determine what we'll do on sandbox violations
if (mode & PLEDGE_STDERR_LOGGING) {
// trapping mode
//
// if we haven't pledged exec, then we can monitor SIGSYS
// and print a helpful error message when things do break
// to avoid tls / static memory, we embed mode within bpf
MonitorSigSys();
AllowMonitor(&f);
sf[0].k = SECCOMP_RET_TRAP | (mode & SECCOMP_RET_DATA);
AppendFilter(&f, PLEDGE(sf));
} else {
// non-trapping mode
//
// our sigsys error message handler can't be inherited across
// execve() boundaries so if you've pledged exec then that'll
// likely cause a SIGSYS in your child after the exec happens
switch (mode & PLEDGE_PENALTY_MASK) {
case PLEDGE_PENALTY_KILL_THREAD:
sf[0].k = SECCOMP_RET_KILL_THREAD;
break;
case PLEDGE_PENALTY_KILL_PROCESS:
sf[0].k = SECCOMP_RET_KILL_PROCESS;
break;
case PLEDGE_PENALTY_RETURN_EPERM:
sf[0].k = SECCOMP_RET_ERRNO | EPERM;
break;
default:
return -EINVAL;
}
AppendFilter(&f, PLEDGE(sf));
}
// drop privileges
//
// PR_SET_SECCOMP (Linux 2.6.23+) will refuse to work if
// PR_SET_NO_NEW_PRIVS (Linux 3.5+) wasn't called so we punt the error
// detection to the seccomp system call below.
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
// register our seccomp filter with the kernel
struct sock_fprog sandbox = {.len = f.n, .filter = f.p};
rc = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &sandbox, 0, 0);
// the EINVAL error could mean a lot of things. it could mean the bpf
// code is broken. it could also mean we're running on RHEL5 which
// doesn't have SECCOMP support. since we don't consider lack of
// system support for security to be an error, we distinguish these
// two cases by running a simpler SECCOMP operation.
if (rc < 0 && //
errno == EINVAL && //
prctl(PR_GET_SECCOMP, 0, 0, 0, 0) < 0 && //
errno == EINVAL) {
rc = 0; // -ENOSYS
}
return rc;
}
| 69,089 | 2,143 | jart/plegde | false |
pledge/libc/calls/landlock_add_rule.c | /*-*- 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/landlock.h"
/*
#include "libc/intrin/strace.internal.h"
int sys_landlock_add_rule(int, enum landlock_rule_type, const void *, uint32_t);
*/
#include <sys/syscall.h>
#include <unistd.h>
/**
* Adds new rule to Landlock ruleset.
*
* @error ENOSYS if Landlock isn't supported
* @error EPERM if Landlock supported but SECCOMP BPF shut it down
* @error EOPNOTSUPP if Landlock supported but disabled at boot time
* @error EINVAL if flags not 0, or inconsistent access in the rule,
* i.e. landlock_path_beneath_attr::allowed_access is not a subset
* of the ruleset handled accesses
* @error ENOMSG empty allowed_access
* @error EBADF `fd` is not a file descriptor for current thread, or
* member of `rule_attr` is not a file descriptor as expected
* @error EBADFD `fd` is not a ruleset file descriptor, or a member
* of `rule_attr` is not the expected file descriptor type
* @error EPERM `fd` has no write access to the underlying ruleset
* @error EFAULT `rule_attr` inconsistency
*/
int landlock_add_rule(int fd, enum landlock_rule_type rule_type,
const void *rule_attr, uint32_t flags) {
int rc;
rc = syscall(__NR_landlock_add_rule, fd, rule_type, rule_attr, flags);
/*KERNTRACE("landlock_add_rule(%d, %d, %p, %#x) â %d% m", fd, rule_type,
rule_attr, flags, rc);*/
return rc;
}
| 3,208 | 54 | jart/plegde | false |
pledge/libc/calls/pledge.c | /*-*- 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 <errno.h>
#include <unistd.h>
#include "libc/calls/calls.h"
#include "libc/calls/pledge.internal.h"
#include "libc/dce.h"
#include "libc/intrin/promises.internal.h"
#include "libc/runtime/runtime.h"
/**
* Permits system operations, e.g.
*
* __pledge_mode = PLEDGE_PENALTY_KILL_PROCESS | PLEDGE_STDERR_LOGGING;
* if (pledge("stdio rfile tty", 0)) {
* perror("pledge");
* exit(1);
* }
*
* Pledging causes most system calls to become unavailable. Your system
* call policy is enforced by the kernel (which means it can propagate
* across execve() if permitted). Root access is not required. Support
* is limited to Linux 2.6.23+ (c. RHEL6) and OpenBSD. If your kernel
* isn't supported, then pledge() will return 0 and do nothing rather
* than raising ENOSYS. We don't consider lack of system support to be
* an error, because the specified operations will be permitted.
*
* The promises you give pledge() define which system calls are allowed.
* Error messages are logged when sandbox violations occur, but how that
* happens depends on the `mode` parameter (see below).
*
* Timing is everything with pledge. It's designed to be a voluntary
* self-imposed security model. That works best when programs perform
* permission-hungry operations (e.g. calling GetSymbolTable) towards
* the beginning of execution, and then relinquish privilege afterwards
* by calling pledge(). Here's an example of where that matters. Your
* Cosmopolitan C Library needs to code morph your executable in memory
* once you start using threads. But that's only possible to do if you
* used the `prot_exec` promise. So the right thing to do here, is to
* call __enable_threads() before calling pledge() to force it early.
*
* __enable_threads();
* ShowCrashReports();
* pledge("...", 0);
*
* By default exit() is allowed. This is useful for processes that
* perform pure computation and interface with the parent via shared
* memory. On Linux we mean sys_exit (_Exit1), not sys_exit_group
* (_Exit). The difference is effectively meaningless, since _Exit()
* will attempt both. All it means is that, if you're using threads,
* then a `pledge("", 0)` thread can't kill all your threads unless you
* `pledge("stdio", 0)`.
*
* Once pledge is in effect, the chmod functions (if allowed) will not
* permit the sticky/setuid/setgid bits to change. Linux will EPERM here
* and OpenBSD should ignore those three bits rather than crashing.
*
* User and group IDs can't be changed once pledge is in effect. OpenBSD
* should ignore chown without crashing; whereas Linux will just EPERM.
*
* Using pledge is irreversible. On Linux it causes PR_SET_NO_NEW_PRIVS
* to be set on your process; however, if "id" or "recvfd" are allowed
* then then they theoretically could permit the gaining of some new
* privileges. You may call pledge() multiple times if "stdio" is
* allowed. In that case, the process can only move towards a more
* restrictive state.
*
* pledge() can't filter filesystem paths. See unveil() which lets you
* do that. pledge() also can't do address firewalling. For example if
* you use the `inet` promise then your process will be able to talk to
* *every* internet address including public ones.
*
* `promises` is a string that may include any of the following groups
* delimited by spaces.
*
* - "stdio" allows exit, close, dup, dup2, dup3, fchdir, fstat, fsync,
* fdatasync, ftruncate, getdents, getegid, getrandom, geteuid,
* getgid, getgroups, times, getrusage, getitimer, getpgid, getpgrp,
* getpid, getppid, getresgid, getresuid, getrlimit, getsid, wait4,
* gettimeofday, getuid, lseek, madvise, brk, arch_prctl, uname,
* set_tid_address, clock_getres, clock_gettime, clock_nanosleep,
* mremap, mmap, (PROT_EXEC and weird flags aren't allowed), mprotect
* (PROT_EXEC isn't allowed), msync, sync_file_range, migrate_pages,
* munmap, nanosleep, pipe, pipe2, read, readv, pread, recv, poll,
* recvfrom, preadv, write, writev, pwrite, pwritev, select, pselect6,
* copy_file_range, sendfile, tee, splice, vmsplice, alarm, pause,
* send, sendto (only if addr is null), setitimer, shutdown, sigaction
* (but SIGSYS is forbidden), sigaltstack, sigprocmask, sigreturn,
* sigsuspend, umask, mincore, socketpair, ioctl(FIONREAD),
* ioctl(FIONBIO), ioctl(FIOCLEX), ioctl(FIONCLEX), fcntl(F_GETFD),
* fcntl(F_SETFD), fcntl(F_GETFL), fcntl(F_SETFL), sched_yield,
* epoll_create, epoll_create1, epoll_ctl, epoll_wait, epoll_pwait,
* epoll_pwait2, clone(CLONE_THREAD), futex, set_robust_list,
* get_robust_list, setaffinity, sigpending.
*
* - "rpath" (read-only path ops) allows chdir, getcwd, open(O_RDONLY),
* openat(O_RDONLY), stat, fstat, lstat, fstatat, access, faccessat,
* faccessat2, readlink, readlinkat, statfs, fstatfs.
*
* - "wpath" (write path ops) allows getcwd, open(O_WRONLY),
* openat(O_WRONLY), stat, fstat, lstat, fstatat, access, faccessat,
* faccessat2, readlink, readlinkat, chmod, fchmod, fchmodat.
*
* - "cpath" (create path ops) allows open(O_CREAT), openat(O_CREAT),
* rename, renameat, renameat2, link, linkat, symlink, symlinkat,
* unlink, rmdir, unlinkat, mkdir, mkdirat.
*
* - "dpath" (create special path ops) allows mknod, mknodat, mkfifo.
*
* - "flock" allows flock, fcntl(F_GETLK), fcntl(F_SETLK),
* fcntl(F_SETLKW).
*
* - "tty" allows ioctl(TIOCGWINSZ), ioctl(TCGETS), ioctl(TCSETS),
* ioctl(TCSETSW), ioctl(TCSETSF).
*
* - "recvfd" allows recvmsg and recvmmsg.
*
* - "recvfd" allows sendmsg and sendmmsg.
*
* - "fattr" allows chmod, fchmod, fchmodat, utime, utimes, futimens,
* utimensat.
*
* - "inet" allows socket(AF_INET), listen, bind, connect, accept,
* accept4, getpeername, getsockname, setsockopt, getsockopt, sendto.
*
* - "unix" allows socket(AF_UNIX), listen, bind, connect, accept,
* accept4, getpeername, getsockname, setsockopt, getsockopt.
*
* - "dns" allows socket(AF_INET), sendto, recvfrom, connect.
*
* - "proc" allows fork, vfork, clone, kill, tgkill, getpriority,
* setpriority, prlimit, setrlimit, setpgid, setsid.
*
* - "id" allows setuid, setreuid, setresuid, setgid, setregid,
* setresgid, setgroups, prlimit, setrlimit, getpriority, setpriority,
* setfsuid, setfsgid.
*
* - "settime" allows settimeofday and clock_adjtime.
*
* - "exec" allows execve, execveat. Note that `exec` alone might not be
* enough by itself to let your executable be executed. For dynamic,
* interpreted, and ape binaries, you'll usually want `rpath` and
* `prot_exec` too. With APE it's possible to work around this
* requirement, by "assimilating" your binaries beforehand. See the
* assimilate.com program and `--assimilate` flag which can be used to
* turn APE binaries into static native binaries.
*
* - "prot_exec" allows mmap(PROT_EXEC) and mprotect(PROT_EXEC). This is
* needed to (1) code morph mutexes in __enable_threads(), and it's
* needed to (2) launch non-static or non-native executables, e.g.
* non-assimilated APE binaries, or dynamic-linked executables.
*
* - "unveil" allows unveil() to be called, as well as the underlying
* landlock_create_ruleset, landlock_add_rule, landlock_restrict_self
* calls on Linux.
*
* - "vminfo" OpenBSD defines this for programs like `top`. On Linux,
* this is a placeholder group that lets tools like pledge.com check
* `__promises` and automatically unveil() a subset of files top would
* need, e.g. /proc/stat, /proc/meminfo.
*
* - "tmppath" allows unlink, unlinkat, and lstat. This is mostly a
* placeholder group for pledge.com, which reads the `__promises`
* global to determine if /tmp and $TMPPATH should be unveiled.
*
* `execpromises` only matters if "exec" is specified in `promises`. In
* that case, this specifies the promises that'll apply once execve()
* happens. If this is NULL then the default is used, which is
* unrestricted. OpenBSD allows child processes to escape the sandbox
* (so a pledged OpenSSH server process can do things like spawn a root
* shell). Linux however requires monotonically decreasing privileges.
* This function will will perform some validation on Linux to make sure
* that `execpromises` is a subset of `promises`. Your libc wrapper for
* execve() will then apply its SECCOMP BPF filter later. Since Linux
* has to do this before calling sys_execve(), the executed process will
* be weakened to have execute permissions too.
*
* `__pledge_mode` is available to improve the experience of pledge() on
* Linux. It should specify one of the following penalties:
*
* - `PLEDGE_PENALTY_KILL_THREAD` causes the violating thread to be
* killed. This is the default on Linux. It's effectively the same as
* killing the process, since redbean has no threads. The termination
* signal can't be caught and will be either `SIGSYS` or `SIGABRT`.
* Consider enabling stderr logging below so you'll know why your
* program failed. Otherwise check the system log.
*
* - `PLEDGE_PENALTY_KILL_PROCESS` causes the process and all its
* threads to be killed. This is always the case on OpenBSD.
*
* - `PLEDGE_PENALTY_RETURN_EPERM` causes system calls to just return an
* `EPERM` error instead of killing. This is a gentler solution that
* allows code to display a friendly warning. Please note this may
* lead to weird behaviors if the software being sandboxed is lazy
* about checking error results.
*
* `mode` may optionally bitwise or the following flags:
*
* - `PLEDGE_STDERR_LOGGING` enables friendly error message logging
* letting you know which promises are needed whenever violations
* occur. Without this, violations will be logged to `dmesg` on Linux
* if the penalty is to kill the process. You would then need to
* manually look up the system call number and then cross reference it
* with the cosmopolitan libc pledge() documentation. You can also use
* `strace -ff` which is easier. This is ignored OpenBSD, which
* already has a good system log. Turning on stderr logging (which
* uses SECCOMP trapping) also means that the `WTERMSIG()` on your
* killed processes will always be `SIGABRT` on both Linux and
* OpenBSD. Otherwise, Linux prefers to raise `SIGSYS`. Enabling this
* option might not be a good idea if you're pledging `exec` because
* subprocesses can't inherit the `SIGSYS` handler this installs.
*
* @return 0 on success, or -1 w/ errno
* @raise EINVAL if `execpromises` on Linux isn't a subset of `promises`
* @raise EINVAL if `promises` allows exec and `execpromises` is null
* @threadsafe
* @vforksafe
*/
int pledge(const char *promises, const char *execpromises) {
int e, rc;
unsigned long ipromises, iexecpromises;
if (!ParsePromises(promises, &ipromises) &&
!ParsePromises(execpromises, &iexecpromises)) {
// copy exec and execnative from promises to execpromises
iexecpromises = ~(~iexecpromises | (~ipromises & (1ul << PROMISE_EXEC)));
// if bits are missing in execpromises that exist in promises
// then execpromises wouldn't be a monotonic access reduction
// this check only matters when exec / execnative are allowed
if ((ipromises & ~iexecpromises) && (~ipromises & (1ul << PROMISE_EXEC))) {
errno = EINVAL;
rc = -1;
} else {
rc = sys_pledge_linux(ipromises, __pledge_mode);
if (rc > -4096u) errno = -rc, rc = -1;
}
if (!rc && (getpid() == gettid())) {
__promises = ipromises;
__execpromises = iexecpromises;
}
} else {
errno = EINVAL;
rc = -1;
}
return rc;
}
| 13,517 | 262 | jart/plegde | false |
pledge/libc/calls/landlock.h | #ifndef PLEDGE_LIBC_CALLS_LANDLOCK_H_
#define PLEDGE_LIBC_CALLS_LANDLOCK_H_
#include <linux/landlock.h>
#include <stdint.h>
#include <stddef.h>
/**
* Allow renaming or linking file to a different directory.
*
* @see https://lore.kernel.org/r/[email protected]
* @see https://docs.kernel.org/userspace-api/landlock.html
* @note ABI 2+
*/
#ifndef LANDLOCK_ACCESS_FS_REFER
#define LANDLOCK_ACCESS_FS_REFER 0x2000ul
#endif
/**
* Control file truncation.
*
* @see https://lore.kernel.org/all/[email protected]/
* @see https://docs.kernel.org/userspace-api/landlock.html
* @note ABI 3+
*/
#ifndef LANDLOCK_ACCESS_FS_TRUNCATE
#define LANDLOCK_ACCESS_FS_TRUNCATE 0x4000ul
#endif
int landlock_restrict_self(int, uint32_t);
int landlock_add_rule(int, enum landlock_rule_type, const void *, uint32_t);
int landlock_create_ruleset(const struct landlock_ruleset_attr *, size_t,
uint32_t);
#endif
| 978 | 36 | jart/plegde | false |
pledge/libc/calls/landlock_create_ruleset.c | /*-*- 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/landlock.h"
/*
#include "libc/intrin/strace.internal.h"
int sys_landlock_create_ruleset(const struct landlock_ruleset_attr *, size_t,
uint32_t);
*/
#include <sys/syscall.h>
#include <unistd.h>
/**
* Create new Landlock filesystem sandboxing ruleset.
*
* You may also use this function to query the current ABI version:
*
* landlock_create_ruleset(0, 0, LANDLOCK_CREATE_RULESET_VERSION);
*
* @return close exec file descriptor for new ruleset
* @error ENOSYS if not running Linux 5.13+
* @error EPERM if pledge() or seccomp bpf shut it down
* @error EOPNOTSUPP Landlock supported but disabled at boot
* @error EINVAL unknown flags, or unknown access, or too small size
* @error E2BIG attr or size inconsistencies
* @error EFAULT attr or size inconsistencies
* @error ENOMSG empty landlock_ruleset_attr::handled_access_fs
*/
int landlock_create_ruleset(const struct landlock_ruleset_attr *attr,
size_t size, uint32_t flags) {
int rc;
rc = syscall(__NR_landlock_create_ruleset, attr, size, flags);
//KERNTRACE("landlock_create_ruleset(%p, %'zu, %#x) â %d% m", attr, size, flags,
// rc);
return rc;
}
| 3,057 | 54 | jart/plegde | false |
pledge/libc/calls/syscall_support-sysv.internal.h | #ifndef PLEDGE_LIBC_CALLS_SYSCALL_SUPPORT_SYSV_INTERNAL_H_
#define PLEDGE_LIBC_CALLS_SYSCALL_SUPPORT_SYSV_INTERNAL_H_
#include <stdbool.h>
bool is_linux_2_6_23(void);
#endif
| 177 | 9 | jart/plegde | false |
pledge/libc/calls/landlock_restrict_self.c | /*-*- 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/landlock.h"
/*
#include "libc/intrin/strace.internal.h"
int sys_landlock_restrict_self(int, uint32_t);
*/
#include <sys/syscall.h>
#include <unistd.h>
/**
* Enforces Landlock ruleset on calling thread.
*
* @error EOPNOTSUPP if Landlock supported but disabled at boot time
* @error EINVAL if flags isn't zero
* @error EBADF if `fd` isn't file descriptor for the current thread
* @error EBADFD if `fd` is not a ruleset file descriptor
* @error EPERM if `fd` has no read access to underlying ruleset, or
* current thread is not running with no_new_privs, or it doesnât
* have CAP_SYS_ADMIN in its namespace
* @error E2BIG if the maximum number of stacked rulesets is
* reached for current thread
*/
int landlock_restrict_self(int fd, uint32_t flags) {
int rc;
rc = syscall(__NR_landlock_restrict_self, fd, flags);
//KERNTRACE("landlock_create_ruleset(%d, %#x) â %d% m", fd, flags, rc);
return rc;
}
| 2,792 | 48 | jart/plegde | false |
pledge/libc/calls/pledge.internal.h | #ifndef PLEDGE_LIBC_CALLS_PLEDGE_INTERNAL_H_
#define PLEDGE_LIBC_CALLS_PLEDGE_INTERNAL_H_
#include "libc/calls/pledge.h"
#include "libc/intrin/promises.internal.h"
#include <stdint.h>
#include <stddef.h>
struct Pledges {
const char *name;
const uint16_t *syscalls;
const size_t len;
};
extern const struct Pledges kPledge[PROMISE_LEN_];
int sys_pledge_linux(unsigned long, int);
int ParsePromises(const char *, unsigned long *);
#endif
| 447 | 21 | jart/plegde | false |
pledge/libc/intrin/safemacros.internal.h | #ifndef PLEDGE_LIBC_INTRIN_SAFEMACROS_INTERNAL_H_
#define PLEDGE_LIBC_INTRIN_SAFEMACROS_INTERNAL_H_
#include "libc/integral/c.h"
#define max(x, y) \
({ \
autotype(x) MaxX = (x); \
autotype(y) MaxY = (y); \
MaxX > MaxY ? MaxX : MaxY; \
})
#endif
| 309 | 14 | jart/plegde | false |
pledge/libc/intrin/kprintf.h | #ifndef PLEDGE_LIBC_INTRIN_KPRINTF_H_
#define PLEDGE_LIBC_INTRIN_KPRINTF_H_
#include <stdio.h>
#define kprintf printf
#define ksnprintf snprintf
#endif
| 155 | 10 | jart/plegde | false |
pledge/libc/intrin/promises.internal.h | #ifndef PLEDGE_LIBC_INTRIN_PROMISES_INTERNAL_H_
#define PLEDGE_LIBC_INTRIN_PROMISES_INTERNAL_H_
#define PROMISE_STDIO 0
#define PROMISE_RPATH 1
#define PROMISE_WPATH 2
#define PROMISE_CPATH 3
#define PROMISE_DPATH 4
#define PROMISE_FLOCK 5
#define PROMISE_FATTR 6
#define PROMISE_INET 7
#define PROMISE_UNIX 8
#define PROMISE_DNS 9
#define PROMISE_TTY 10
#define PROMISE_RECVFD 11
#define PROMISE_PROC 12
#define PROMISE_EXEC 13
#define PROMISE_ID 14
#define PROMISE_UNVEIL 15
#define PROMISE_SENDFD 16
#define PROMISE_SETTIME 17
#define PROMISE_PROT_EXEC 18
#define PROMISE_VMINFO 19
#define PROMISE_TMPPATH 20
#define PROMISE_CHOWN 21
#define PROMISE_LEN_ 22
extern unsigned long __promises;
extern unsigned long __execpromises;
#endif
| 833 | 32 | jart/plegde | false |
pledge/libc/intrin/pthread_setcancelstate.c | /*-*- 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/blockcancel.internal.h"
/*
#include "libc/errno.h"
#include "libc/thread/posixthread.internal.h"
#include "libc/thread/thread.h"
#include "libc/thread/tls.h"
*/
#include <pthread.h>
void pthread_allow_cancellations(int oldstate) {
pthread_setcancelstate(oldstate, 0);
}
int pthread_block_cancellations(void) {
int oldstate;
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
return oldstate;
}
| 2,270 | 38 | jart/plegde | false |
pledge/libc/intrin/promises.c | /*-*- 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/pledge.h"
#include "libc/intrin/promises.internal.h"
// XXX: should be inherited thread local
// see also sys_pledge_linux() which is 100% pure
int __pledge_mode;
unsigned long __promises;
unsigned long __execpromises;
| 2,082 | 27 | jart/plegde | false |
pledge/libc/intrin/likely.h | #ifndef PLEDGE_LIBC_INTRIN_LIKELY_H_
#define PLEDGE_LIBC_INTRIN_LIKELY_H_
#ifndef __STRICT_ANSI__
#define LIKELY(x) __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
#define LIKELY(x)
#define UNLIKELY(x)
#endif
#endif
| 252 | 13 | jart/plegde | false |
pledge/libc/intrin/bits.h | #ifndef PLEDGE_LIBC_INTRIN_BITS_H_
#define PLEDGE_LIBC_INTRIN_BITS_H_
#include <stdint.h>
#ifdef __STRICT_ANSI__
#define READ32LE(S) \
((uint32_t)(255 & (S)[3]) << 030 | (uint32_t)(255 & (S)[2]) << 020 | \
(uint32_t)(255 & (S)[1]) << 010 | (uint32_t)(255 & (S)[0]) << 000)
#define READ64LE(S) \
((uint64_t)(255 & (S)[7]) << 070 | (uint64_t)(255 & (S)[6]) << 060 | \
(uint64_t)(255 & (S)[5]) << 050 | (uint64_t)(255 & (S)[4]) << 040 | \
(uint64_t)(255 & (S)[3]) << 030 | (uint64_t)(255 & (S)[2]) << 020 | \
(uint64_t)(255 & (S)[1]) << 010 | (uint64_t)(255 & (S)[0]) << 000)
#else /* gcc needs help knowing above are mov if s isn't a variable */
#define READ32LE(S) \
({ \
const uint8_t *Ptr = (const uint8_t *)(S); \
((uint32_t)Ptr[3] << 030 | (uint32_t)Ptr[2] << 020 | \
(uint32_t)Ptr[1] << 010 | (uint32_t)Ptr[0] << 000); \
})
#define READ64LE(S) \
({ \
const uint8_t *Ptr = (const uint8_t *)(S); \
((uint64_t)Ptr[7] << 070 | (uint64_t)Ptr[6] << 060 | \
(uint64_t)Ptr[5] << 050 | (uint64_t)Ptr[4] << 040 | \
(uint64_t)Ptr[3] << 030 | (uint64_t)Ptr[2] << 020 | \
(uint64_t)Ptr[1] << 010 | (uint64_t)Ptr[0] << 000); \
})
#endif
#endif
| 1,497 | 33 | jart/plegde | false |
pledge/libc/integral/c.h | #ifndef PLEDGE_LIBC_INTEGRAL_C_H_
#define PLEDGE_LIBC_INTEGRAL_C_H_
#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#ifndef __STRICT_ANSI__
#define pureconst __attribute__((__const__))
#else
#define pureconst
#endif
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__nonnull__) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 403)
#define paramsnonnull(opt_1idxs) __attribute__((__nonnull__ opt_1idxs))
#else
#define paramsnonnull(opt_1idxs)
#endif
#define libcesque dontthrow nocallback
#if defined(__cplusplus) && !defined(__STRICT_ANSI__) && \
(__has_attribute(dontthrow) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 303)
#define dontthrow __attribute__((__nothrow__))
#elif defined(_MSC_VER)
#define dontthrow __declspec(nothrow)
#else
#define dontthrow
#endif
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__leaf__) || \
(!defined(__llvm__) && \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 406))
#define nocallback __attribute__((__leaf__))
#else
#define nocallback
#endif
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__sentinel__) || __GNUC__ + 0 >= 4)
#define nullterminated(x) __attribute__((__sentinel__ x))
#else
#define nullterminated(x)
#endif
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__malloc__) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 409)
#define returnspointerwithnoaliases __attribute__((__malloc__))
#elif defined(_MSC_VER)
#define returnspointerwithnoaliases __declspec(allocator)
#else
#define returnspointerwithnoaliases
#endif
#if !defined(__STRICT_ANSI__) && \
((__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 304 || \
__has_attribute(__warn_unused_result__))
#define dontdiscard __attribute__((__warn_unused_result__))
#else
#define dontdiscard
#endif
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__returns_nonnull__) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 409)
#define returnsnonnull __attribute__((__returns_nonnull__))
#else
#define returnsnonnull
#endif
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__alloc_size__) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 409)
#define attributeallocsize(x) __attribute__((__alloc_size__ x))
#else
#define attributeallocsize(x)
#endif
#ifdef __cplusplus
#define forceinline inline
#else
#if !defined(__STRICT_ANSI__) && \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 302
#if (__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 403 || \
!defined(__cplusplus) || \
(defined(__clang__) && \
(defined(__GNUC_STDC_INLINE__) || defined(__GNUC_GNU_INLINE__)))
#if defined(__GNUC_STDC_INLINE__) || defined(__cplusplus)
#define forceinline \
static __inline __attribute__((__always_inline__, __gnu_inline__, \
__no_instrument_function__, __unused__))
#else
#define forceinline \
static __inline __attribute__((__always_inline__, \
__no_instrument_function__, __unused__))
#endif /* __GNUC_STDC_INLINE__ */
#endif /* GCC >= 4.3 */
#elif defined(_MSC_VER)
#define forceinline __forceinline
#else
#define forceinline static inline
#endif /* !ANSI && GCC >= 3.2 */
#endif /* __cplusplus */
#define strlenesque libcesque nosideeffect paramsnonnull()
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__pure__) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 296)
#define nosideeffect __attribute__((__pure__))
#else
#define nosideeffect
#endif
#if __cplusplus + 0 >= 201103L
#define autotype(x) auto
#elif ((__has_builtin(auto_type) || defined(__llvm__) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 409) && \
!defined(__chibicc__))
#define autotype(x) __auto_type
#else
#define autotype(x) typeof(x)
#endif
#define privileged
#ifndef __STRICT_ANSI__
#define thatispacked __attribute__((__packed__))
#else
#define thatispacked
#endif
#define notpossible __builtin_trap()
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__noreturn__) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 208)
#define wontreturn __attribute__((__noreturn__))
#else
#define wontreturn
#endif
#endif
| 4,386 | 149 | jart/plegde | false |
pledge/libc/sysv/calls/ioprio_set.c | #include "libc/calls/calls.h"
#include <sys/syscall.h>
#include <unistd.h>
int ioprio_set(int which, int who, int ioprio) {
return syscall(__NR_ioprio_set, which, who, ioprio);
}
| 183 | 9 | jart/plegde | false |
pledge/libc/runtime/isdynamicexecutable.c | /*-*- 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/blockcancel.internal.h"
#include "libc/calls/calls.h"
/*
#include "libc/calls/struct/stat.h"
#include "libc/elf/def.h"
*/
#include "libc/elf/elf.h"
/*
#include "libc/elf/struct/ehdr.h"
#include "libc/elf/struct/phdr.h"
#include "libc/errno.h"
*/
#include "libc/intrin/bits.h"
#include "libc/runtime/runtime.h"
/*
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
*/
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
/**
* Returns true if ELF executable uses dynamic loading magic.
*/
bool _IsDynamicExecutable(const char *prog) {
bool res;
Elf64_Ehdr *e;
Elf64_Phdr *p;
struct stat st;
int i, fd, err;
BLOCK_CANCELLATIONS;
fd = -1;
err = errno;
e = MAP_FAILED;
if ((fd = open(prog, O_RDONLY)) == -1) {
res = false;
goto Finish;
}
if (fstat(fd, &st) == -1 || st.st_size < 64) {
res = false;
goto Finish;
}
if ((e = mmap(0, st.st_size, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
res = false;
goto Finish;
}
if (READ32LE(e->e_ident) != READ32LE(ELFMAG)) {
res = false;
goto Finish;
}
if (e->e_type == ET_DYN) {
res = true;
goto Finish;
}
for (i = 0; i < e->e_phnum; ++i) {
p = GetElfSegmentHeaderAddress(e, st.st_size, i);
if (p->p_type == PT_INTERP || p->p_type == PT_DYNAMIC) {
res = true;
goto Finish;
}
}
res = false;
goto Finish;
Finish:
if (e != MAP_FAILED) munmap(e, st.st_size);
if (fd != -1) close(fd);
errno = err;
ALLOW_CANCELLATIONS;
return res;
}
| 3,446 | 94 | jart/plegde | false |
pledge/libc/runtime/runtime.h | #ifndef PLEDGE_LIBC_RUNTIME_RUNTIME_H_
#define PLEDGE_LIBC_RUNTIME_RUNTIME_H_
#include <stdbool.h>
#include "libc/integral/c.h"
unsigned getcpucount(void) pureconst;
bool _IsDynamicExecutable(const char *);
#endif
| 217 | 11 | jart/plegde | false |
pledge/libc/runtime/stack.h | #ifndef PLEDGE_LIBC_RUNTIME_STACK_H_
#define PLEDGE_LIBC_RUNTIME_STACK_H_
#include "libc/integral/c.h"
#include <sys/types.h>
forceinline void CheckLargeStackAllocation(void *p, ssize_t n) {
for (; n > 0; n -= 4096) {
((char *)p)[n - 1] = 0;
}
}
#endif
| 264 | 14 | jart/plegde | false |
pledge/libc/str/classifypath.c | /*-*- 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/dce.h"
#include "libc/str/path.h"
#include "libc/str/str.h"
/**
* Classifies file path name.
*
* For the purposes of this function, we always consider backslash
* interchangeable with forward slash, even though the underlying
* operating system might not. Therefore, for the sake of clarity,
* remaining documentation will only use the forward slash.
*
* This function behaves the same on all platforms. For instance, this
* function will categorize `C:/FOO.BAR` as a DOS path, even if you're
* running on UNIX rather than DOS.
*
* If you wish to check if a pathname is absolute, in a manner that's
* inclusive of DOS drive paths, DOS rooted paths, in addition to the
* New Technology UNC paths, then you may do the following:
*
* if (_classifypath(str) & _kPathAbs) { ... }
*
* To check if path is a relative path:
*
* if (~_classifypath(str) & _kPathAbs) { ... }
*
* Please note the above check includes rooted paths such as `\foo`
* which is considered absolute by MSDN and we consider it absolute
* although, it's technically relative to the current drive letter.
*
* Please note that `/foo/bar` is an absolute path on Windows, even
* though it's actually a rooted path that's considered relative to
* current drive by WIN32.
*
* @return integer value that's one of following:
* - `0` if non-weird relative path e.g. `c`
* - `_kPathAbs` if absolute (or rooted dos) path e.g. `/â¯`
* - `_kPathDos` if `c:`, `d:foo` i.e. drive-relative path
* - `_kPathAbs|_kPathDos` if proper dos path e.g. `c:/foo`
* - `_kPathDos|_kPathDev` if dos device path e.g. `nul`, `conin$`
* - `_kPathAbs|_kPathWin` if `//c`, `//?c`, etc.
* - `_kPathAbs|_kPathWin|_kPathDev` if `//./â¯`, `//?/â¯`
* - `_kPathAbs|_kPathWin|_kPathDev|_kPathRoot` if `//.` or `//?`
* - `_kPathAbs|_kPathNt` e.g. `\??\\â¯` (undoc. strict backslash)
* @see "The Definitive Guide on Win32 to NT Path Conversion", James
* Forshaw, Google Project Zero Blog, 2016-02-29
* @see "Naming Files, Paths, and Namespaces", MSDN 01/04/2021
*/
int classifypath(const char *s) {
if (s) {
switch (s[0]) {
case 0: // ""
default:
return 0;
case '\\':
case '/':
return _kPathAbs;
}
} else {
return 0;
}
}
| 4,149 | 81 | jart/plegde | false |
pledge/libc/str/str.h | #ifndef PLEDGE_LIBC_STR_STR_H_
#define PLEDGE_LIBC_STR_STR_H_
#include "libc/integral/c.h"
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#include <strings.h>
bool endswith(const char *, const char *) strlenesque;
#endif
| 238 | 14 | jart/plegde | false |
pledge/libc/str/isabspath.c | /*-*- 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/str/path.h"
#include "libc/str/str.h"
/**
* Returns true if pathname is considered absolute.
*
* - `/home/jart/foo.txt` is absolute
* - `C:/Users/jart/foo.txt` is absolute on Windows
* - `C:\Users\jart\foo.txt` is absolute on Windows
* - `\??\C:\Users\jart\foo.txt` is absolute on Windows
* - `\\.\C:\Users\jart\foo.txt` is absolute on Windows
* - `/Users/jart/foo.txt` is effectively absolute on Windows
* - `\Users\jart\foo.txt` is effectively absolute on Windows
*
*/
bool isabspath(const char *path) {
return classifypath(path) & _kPathAbs;
}
| 2,412 | 37 | jart/plegde | false |
pledge/libc/str/path.h | #ifndef PLEDGE_LIBC_STR_PATH_H_
#define PLEDGE_LIBC_STR_PATH_H_
#include "libc/integral/c.h"
#include <stdbool.h>
#define _kPathAbs 1
#define _kPathDev 2
#define _kPathRoot 4
#define _kPathDos 8
#define _kPathWin 16
#define _kPathNt 32
int classifypath(const char *) libcesque nosideeffect;
bool isabspath(const char *) libcesque strlenesque;
char *joinpaths(char *, size_t, const char *, const char *);
#endif
| 421 | 19 | jart/plegde | false |
pledge/libc/str/endswith.c | /*-*- 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/str/str.h"
/**
* Returns true if s has suffix.
*
* @param s is a NUL-terminated string
* @param suffix is also NUL-terminated
*/
bool endswith(const char *s, const char *suffix) {
size_t n, m;
n = strlen(s);
m = strlen(suffix);
if (m > n) return false;
return !memcmp(s + n - m, suffix, m);
}
| 2,160 | 34 | jart/plegde | false |
pledge/cmd/pledge.c | /*-*- 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/calls.h"
#include "libc/calls/landlock.h"
#include "libc/calls/pledge.h"
#include "libc/calls/pledge.internal.h"
/*
#include "libc/calls/struct/rlimit.h"
#include "libc/calls/struct/sched_param.h"
#include "libc/calls/struct/seccomp.h"
#include "libc/calls/struct/stat.h"
#include "libc/calls/struct/sysinfo.h"
#include "libc/calls/syscall-sysv.internal.h"
*/
#include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/dce.h"
/*
#include "libc/elf/def.h"
#include "libc/elf/struct/ehdr.h"
#include "libc/errno.h"
*/
#include "libc/fmt/conv.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/promises.internal.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/macros.internal.h"
/*
#include "libc/math.h"
#include "libc/mem/copyfd.internal.h"
#include "libc/mem/gc.internal.h"
#include "libc/mem/mem.h"
#include "libc/nexgen32e/kcpuids.h"
*/
#include "libc/runtime/runtime.h"
/*
#include "libc/sock/sock.h"
#include "libc/sock/struct/pollfd.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/ioprio.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/ok.h"
#include "libc/sysv/consts/poll.h"
#include "libc/sysv/consts/pr.h"
#include "libc/sysv/consts/prio.h"
#include "libc/sysv/consts/prot.h"
#include "libc/sysv/consts/rlim.h"
#include "libc/sysv/consts/rlimit.h"
#include "libc/sysv/consts/sched.h"
#include "libc/sysv/errfuns.h"
*/
#include "libc/x/x.h"
/*
#include "third_party/getopt/getopt.h"
*/
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <linux/ioprio.h>
#include <linux/sched.h>
#include <poll.h>
#include <sched.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/fsuid.h>
#include <sys/param.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/sysinfo.h>
#include <unistd.h>
// MANUALLY TESTED BY RUNNING
//
// test/tool/build/pledge_test.sh
//
/*
STATIC_YOINK("strerror_wr");
STATIC_YOINK("zip_uri_support");
*/
#define USAGE \
"\
usage: pledge [-hnN] PROG ARGS...\n\
-h show help\n\
-g GID call setgid()\n\
-u UID call setuid()\n\
-c PATH call chroot()\n\
-v [PERM:]PATH call unveil(PATH, PERM[rwxc])\n\
-V disable unveiling (only pledge)\n\
-q disable stderr violation logging\n\
-k kill process rather than eperm'ing\n\
-n set maximum niceness\n\
-D don't drop capabilities\n\
-N don't normalize file descriptors\n\
-C SECS set cpu limit [default: inherited]\n\
-M BYTES set virtual memory limit [default: 4gb]\n\
-O FILES set file descriptor limit [default: 64]\n\
-P PROCS set process limit [default: preexisting + cpus]\n\
-F BYTES set individual file size limit [default: 4gb]\n\
-T pledge exits 0 if pledge() is supported by host system\n\
-T unveil exits 0 if unveil() is supported by host system\n\
-p PLEDGE may contain any of following separated by spaces\n\
- stdio: allow stdio and benign system calls\n\
- rpath: read-only path ops\n\
- wpath: write path ops\n\
- cpath: create path ops\n\
- dpath: create special files\n\
- chown: allows file ownership changes\n\
- flock: file locks\n\
- tty: terminal ioctls\n\
- recvfd: allow SCM_RIGHTS\n\
- sendfd: allow SCM_RIGHTS\n\
- fattr: allow changing some struct stat bits\n\
- inet: allow IPv4 and IPv6\n\
- unix: allow local sockets\n\
- id: allow setuid and friends\n\
- dns: allow dns and related files\n\
- proc: allow process and thread creation\n\
- exec: implied by default\n\
- prot_exec: allow creating executable memory\n\
- vminfo: allows /proc/stat, /proc/self/maps, etc.\n\
- tmppath: allows /tmp, $TMPPATH, lstat, unlink\n\
\n\
pledge v1.8\n\
copyright 2023 justine alexandra roberts tunney\n\
notice licenses are embedded in the binary\n\
https://twitter.com/justinetunney\n\
https://linkedin.com/in/jtunney\n\
https://justine.lol/pledge/\n\
https://github.com/jart\n\
\n\
this program lets you launch linux commands in a sandbox that's\n\
inspired by the design of openbsd's pledge() system call. Visit\n\
the https://justine.lol/pledge/ page for online documentation.\n\
\n\
"
int g_gflag;
int g_uflag;
int g_kflag;
int g_hflag;
bool g_nice;
bool g_qflag;
bool isdynamic;
bool g_noclose;
long g_cpuquota;
long g_fszquota;
long g_nfdquota;
long g_memquota;
long g_proquota;
long g_dontdrop;
long g_dontunveil;
const char *g_test;
const char *g_chroot;
const char *g_promises;
char dsopath[PATH_MAX];
char tmppath[PATH_MAX];
struct {
int n;
char **p;
} unveils;
static void GetOpts(int argc, char *argv[]) {
int opt;
struct sysinfo si;
g_promises = 0;
g_nfdquota = 64;
g_fszquota = 256 * 1000 * 1000;
if (!sysinfo(&si)) {
g_memquota = si.totalram;
g_proquota = getcpucount() + si.procs;
} else {
g_proquota = getcpucount() * 100;
g_memquota = 4L * 1024 * 1024 * 1024;
}
while ((opt = getopt(argc, argv, "+hnqkNVT:p:u:g:c:C:D:P:M:F:O:v:")) != -1) {
switch (opt) {
case 'n':
g_nice = true;
break;
case 'q':
g_qflag = true;
break;
case 'k':
g_kflag = true;
break;
case 'N':
g_noclose = true;
break;
case 'D':
g_dontdrop = true;
break;
case 'V':
g_dontunveil = true;
break;
case 'T':
g_test = optarg;
break;
case 'c':
g_chroot = optarg;
break;
case 'g':
g_gflag = atoi(optarg);
break;
case 'u':
g_uflag = atoi(optarg);
break;
case 'C':
g_cpuquota = atoi(optarg);
break;
case 'P':
g_proquota = atoi(optarg);
break;
case 'O':
g_nfdquota = atoi(optarg);
break;
case 'F':
errno = 0;
g_fszquota = sizetol(optarg, 1000);
if (errno) {
kprintf("error: invalid size: -F %s\n", optarg);
exit(1);
}
break;
case 'M':
errno = 0;
g_memquota = sizetol(optarg, 1024);
if (errno) {
kprintf("error: invalid size: -F %s\n", optarg);
exit(1);
}
break;
case 'p':
if (g_promises) {
g_promises = xstrcat(g_promises, ' ', optarg);
} else {
g_promises = optarg;
}
break;
case 'v':
unveils.p = realloc(unveils.p, ++unveils.n * sizeof(*unveils.p));
unveils.p[unveils.n - 1] = optarg;
break;
case 'h':
case '?':
write(1, USAGE, sizeof(USAGE) - 1);
exit(0);
default:
write(2, USAGE, sizeof(USAGE) - 1);
exit(64);
}
}
if (!g_promises) {
g_promises = "stdio rpath";
}
}
const char *prog;
char pathbuf[PATH_MAX];
struct pollfd pfds[256];
static bool SupportsLandlock(void) {
int e = errno;
bool r = landlock_create_ruleset(0, 0, LANDLOCK_CREATE_RULESET_VERSION) >= 0;
errno = e;
return r;
}
int GetPollMaxFds(void) {
int n;
struct rlimit rl;
if (getrlimit(RLIMIT_NOFILE, &rl) != -1) {
n = rl.rlim_cur;
} else {
n = 64;
}
return MIN(ARRAYLEN(pfds), MAX(3, n));
}
void NormalizeFileDescriptors(void) {
int e, i, n, fd;
n = GetPollMaxFds();
e = errno;
for (i = 3; i < 100; ++i) {
close(i);
}
errno = e;
for (i = 0; i < n; ++i) {
pfds[i].fd = i;
pfds[i].events = POLLIN;
}
if (poll(pfds, n, 0) == -1) {
kprintf("error: poll() failed: %m\n");
exit(1);
}
for (i = 0; i < 3; ++i) {
if (pfds[i].revents & POLLNVAL) {
if ((fd = open("/dev/null", O_RDWR)) == -1) {
kprintf("error: open(\"/dev/null\") failed: %m\n");
exit(2);
}
if (fd != i) {
kprintf("error: open() is broken: %d vs. %d\n", fd, i);
exit(3);
}
}
}
for (i = 3; i < n; ++i) {
if (~pfds[i].revents & POLLNVAL) {
if (close(pfds[i].fd) == -1) {
kprintf("error: close(%d) failed: %m\n", pfds[i].fd);
exit(4);
}
}
}
}
int SetLimit(int r, long lo, long hi) {
struct rlimit old;
struct rlimit lim = {lo, hi};
if (r < 0 || r >= RLIM_NLIMITS) return 0;
if (!setrlimit(r, &lim)) return 0;
if (getrlimit(r, &old)) return -1;
lim.rlim_cur = MIN(lim.rlim_cur, old.rlim_max);
lim.rlim_max = MIN(lim.rlim_max, old.rlim_max);
return setrlimit(r, &lim);
}
/*
int GetBaseCpuFreqMhz(void) {
return KCPUIDS(16H, EAX) & 0x7fff;
}
*/
int SetCpuLimit(int secs) {
int mhz, lim;
if (secs <= 0) return 0;
errno = EOPNOTSUPP;
return -1;
/*
if (!(mhz = GetBaseCpuFreqMhz())) return eopnotsupp();
lim = ceil(3100. / mhz * secs);
return SetLimit(RLIMIT_CPU, lim, lim);
*/
}
bool PathExists(const char *path) {
int err;
struct stat st;
if (path) {
err = errno;
if (!stat(path, &st)) {
return true;
} else {
errno = err;
return false;
}
} else {
return false;
}
}
void Unveil(const char *path, const char *perm) {
if (unveil(path, perm) == -1) {
kprintf("error: unveil(%#s, %#s) failed: %m\n", path, perm);
_Exit(20);
}
}
int UnveilIfExists(const char *path, const char *perm) {
int err;
if (path) {
err = errno;
if (unveil(path, perm) != -1) {
return 0;
} else if (errno == ENOENT) {
errno = err;
} else {
kprintf("error: unveil(%#s, %#s) failed: %m\n", path, perm);
_Exit(20);
}
}
return -1;
}
void MakeProcessNice(void) {
if (!g_nice) return;
if (setpriority(PRIO_PROCESS, 0, 19) == -1) {
kprintf("error: setpriority(PRIO_PROCESS, 0, 19) failed: %m\n");
exit(23);
}
if (ioprio_set(IOPRIO_WHO_PROCESS, 0,
IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0)) == -1) {
kprintf("error: ioprio_set() failed: %m\n");
exit(23);
}
struct sched_param p = {sched_get_priority_min(SCHED_IDLE)};
if (sched_setscheduler(0, SCHED_IDLE, &p) == -1) {
kprintf("error: sched_setscheduler(SCHED_IDLE) failed: %m\n");
exit(23);
}
}
void ApplyFilesystemPolicy(unsigned long ipromises) {
const char *p;
if (g_dontunveil) return;
if (!SupportsLandlock()) return;
Unveil(prog, "rx");
if (isdynamic) {
Unveil(dsopath, "rx");
UnveilIfExists("/lib", "rx");
UnveilIfExists("/lib64", "rx");
UnveilIfExists("/usr/lib", "rx");
UnveilIfExists("/usr/lib64", "rx");
UnveilIfExists("/usr/local/lib", "rx");
UnveilIfExists("/usr/local/lib64", "rx");
UnveilIfExists("/etc/ld-musl-x86_64.path", "r");
UnveilIfExists("/etc/ld.so.conf", "r");
UnveilIfExists("/etc/ld.so.cache", "r");
UnveilIfExists("/etc/ld.so.conf.d", "r");
UnveilIfExists("/etc/ld.so.preload", "r");
}
if (~ipromises & (1ul << PROMISE_STDIO)) {
UnveilIfExists("/dev/fd", "r");
UnveilIfExists("/dev/log", "w");
UnveilIfExists("/dev/zero", "r");
UnveilIfExists("/dev/null", "rw");
UnveilIfExists("/dev/full", "rw");
UnveilIfExists("/dev/stdin", "rw");
UnveilIfExists("/dev/stdout", "rw");
UnveilIfExists("/dev/stderr", "rw");
UnveilIfExists("/dev/urandom", "r");
UnveilIfExists("/etc/localtime", "r");
UnveilIfExists("/proc/self/fd", "rw");
UnveilIfExists("/proc/self/stat", "r");
UnveilIfExists("/proc/self/status", "r");
UnveilIfExists("/usr/share/locale", "r");
UnveilIfExists("/proc/self/cmdline", "r");
UnveilIfExists("/usr/share/zoneinfo", "r");
UnveilIfExists("/proc/sys/kernel/version", "r");
UnveilIfExists("/usr/share/common-licenses", "r");
UnveilIfExists("/proc/sys/kernel/ngroups_max", "r");
UnveilIfExists("/proc/sys/kernel/cap_last_cap", "r");
UnveilIfExists("/proc/sys/vm/overcommit_memory", "r");
}
if (~ipromises & (1ul << PROMISE_INET)) {
UnveilIfExists("/etc/ssl/certs/ca-certificates.crt", "r");
}
if (~ipromises & (1ul << PROMISE_RPATH)) {
UnveilIfExists("/proc/filesystems", "r");
}
if (~ipromises & (1ul << PROMISE_DNS)) {
UnveilIfExists("/etc/hosts", "r");
UnveilIfExists("/etc/hostname", "r");
UnveilIfExists("/etc/services", "r");
UnveilIfExists("/etc/protocols", "r");
UnveilIfExists("/etc/resolv.conf", "r");
}
if (~ipromises & (1ul << PROMISE_TTY)) {
UnveilIfExists(ttyname(0), "rw");
UnveilIfExists("/dev/tty", "rw");
UnveilIfExists("/dev/console", "rw");
UnveilIfExists("/etc/terminfo", "r");
UnveilIfExists("/usr/lib/terminfo", "r");
UnveilIfExists("/usr/share/terminfo", "r");
}
if (~ipromises & (1ul << PROMISE_PROT_EXEC)) {
if (UnveilIfExists("/usr/bin/ape", "rx") == -1) {
if ((p = getenv("TMPDIR"))) {
UnveilIfExists(xjoinpaths(p, ".ape"), "rx");
}
if ((p = getenv("HOME"))) {
UnveilIfExists(xjoinpaths(p, ".ape"), "rx");
}
}
}
if (~ipromises & (1ul << PROMISE_VMINFO)) {
UnveilIfExists("/proc/stat", "r");
UnveilIfExists("/proc/meminfo", "r");
UnveilIfExists("/proc/cpuinfo", "r");
UnveilIfExists("/proc/diskstats", "r");
UnveilIfExists("/proc/self/maps", "r");
UnveilIfExists("/sys/devices/system/cpu", "r");
}
if (~ipromises & (1ul << PROMISE_TMPPATH)) {
UnveilIfExists("/tmp", "rwc");
UnveilIfExists(getenv("TMPPATH"), "rwc");
}
for (int i = 0; i < unveils.n; ++i) {
char *s, *t;
const char *path;
const char *perm;
s = unveils.p[i];
if ((t = strchr(s, ':'))) {
*t = 0;
perm = s;
path = t + 1;
} else {
perm = "r";
path = s;
}
UnveilIfExists(path, perm);
}
if (unveil(0, 0) == -1) {
kprintf("error: unveil(0, 0) failed: %m\n");
_Exit(20);
}
}
void DropCapabilities(void) {
int e, i;
for (e = errno, i = 0;; ++i) {
if (prctl(PR_CAPBSET_DROP, i) == -1) {
if (errno == EINVAL || errno == EPERM) {
errno = e;
break;
} else {
kprintf("error: prctl(PR_CAPBSET_DROP, %d) failed: %m\n", i);
_Exit(25);
}
}
}
}
bool FileExistsAndIsNewerThan(const char *filepath, const char *thanpath) {
struct stat st1, st2;
if (stat(filepath, &st1) == -1) return false;
if (stat(thanpath, &st2) == -1) return false;
if (st1.st_mtim.tv_sec < st2.st_mtim.tv_sec) return false;
if (st1.st_mtim.tv_sec > st2.st_mtim.tv_sec) return true;
return st1.st_mtim.tv_nsec >= st2.st_mtim.tv_nsec;
}
int ExtractEmbeddedSandbox(const char *to, int mode) {
extern char _binary_o__sandbox_so_start[],
_binary_o__sandbox_so_end[]; // Defined by the embedded sandbox object -
// see also the Makefile for how this is
// setup using ld -r -b binary
int fdout;
ssize_t write_rc;
size_t bytes_written, bytes_just_written, bytes_to_write;
if ((fdout = creat(to, mode)) == -1) return -1;
bytes_to_write = _binary_o__sandbox_so_end - _binary_o__sandbox_so_start;
for (bytes_written = 0; bytes_written < bytes_to_write;
bytes_written += bytes_just_written) {
write_rc = write(fdout, _binary_o__sandbox_so_start + bytes_written,
bytes_to_write - bytes_written);
if (write_rc >= 0) {
bytes_just_written = write_rc;
} else if (errno == EINTR) {
bytes_just_written = 0;
} else
break;
}
if (write_rc < 0) {
close(fdout);
return -1;
}
return close(fdout);
}
int main(int argc, char *argv[]) {
const char *s;
bool hasfunbits;
int fdin, fdout;
// Note that we need separate buffer variables for each environment variable,
// as strings passed to putenv must not be modified further (as this may
// itself modify the environment)
char buf[PATH_MAX];
char buf_ld_preload_env_var[PATH_MAX];
char buf_pledge_env_var[PATH_MAX];
int e, zipfd, memfd;
int useruid, usergid;
int owneruid, ownergid;
int oldfsuid, oldfsgid;
unsigned long ipromises;
if (!IsLinux()) {
kprintf("error: this program is only intended for linux\n");
exit(5);
}
// parse flags
GetOpts(argc, argv);
if (g_test) {
if (!strcmp(g_test, "pledge")) {
if (IsOpenbsd() || (IsLinux() && is_linux_2_6_23())) {
exit(0);
} else {
exit(1);
}
}
if (!strcmp(g_test, "unveil")) {
if (IsOpenbsd() || (IsLinux() && SupportsLandlock())) {
exit(0);
} else {
exit(1);
}
}
kprintf("error: unknown test: %s\n", g_test);
exit(2);
}
if (optind == argc) {
kprintf("error: too few args\n");
write(2, USAGE, sizeof(USAGE) - 1);
exit(64);
}
if (!g_noclose) {
NormalizeFileDescriptors();
}
// set resource limits
MakeProcessNice();
if (SetCpuLimit(g_cpuquota) == -1) {
kprintf("error: setrlimit(%s) failed: %m\n", "RLIMIT_CPU");
exit(1);
}
if (SetLimit(RLIMIT_FSIZE, g_fszquota, g_fszquota * 1.5) == -1) {
kprintf("error: setrlimit(%s) failed: %m\n", "RLIMIT_FSIZE");
exit(1);
}
if (SetLimit(RLIMIT_AS, g_memquota, g_memquota) == -1) {
kprintf("error: setrlimit(%s) failed: %m\n", "RLIMIT_AS");
exit(1);
}
if (SetLimit(RLIMIT_NPROC, g_proquota, g_proquota) == -1) {
kprintf("error: setrlimit(%s) failed: %m\n", "RLIMIT_NPROC");
exit(1);
}
// test for weird chmod bits
usergid = getgid();
ownergid = getegid();
useruid = getuid();
owneruid = geteuid();
hasfunbits = usergid != ownergid || useruid != owneruid;
if (hasfunbits) {
setuid(owneruid);
setgid(ownergid);
}
// some flags can't be allowed if binary has setuid bits
if (hasfunbits) {
if (g_uflag || g_gflag) {
kprintf("error: setuid flags forbidden on setuid binaries\n");
_Exit(6);
}
}
// check if user has permission to chroot directory
if (hasfunbits && g_chroot) {
oldfsuid = setfsuid(useruid);
oldfsgid = setfsgid(usergid);
if (access(g_chroot, R_OK) == -1) {
kprintf("error: access(%#s) failed: %m\n", g_chroot);
_Exit(7);
}
setfsuid(oldfsuid);
setfsgid(oldfsgid);
}
// change root fs path
if (g_chroot) {
if (chdir(g_chroot) == -1) {
kprintf("error: chdir(%#s) failed: %m\n", g_chroot);
_Exit(8);
}
if (chroot(g_chroot) == -1) {
kprintf("error: chroot(%#s) failed: %m\n", g_chroot);
_Exit(9);
}
}
// find program
if (hasfunbits) {
oldfsuid = setfsuid(useruid);
oldfsgid = setfsgid(usergid);
}
if (!(prog = commandv(argv[optind], pathbuf, sizeof(pathbuf)))) {
kprintf("error: command not found: %m\n", argv[optind]);
_Exit(10);
}
if (hasfunbits) {
setfsuid(oldfsuid);
setfsgid(oldfsgid);
}
// figure out where we want the dso
if (_IsDynamicExecutable(prog)) {
isdynamic = true;
if ((s = getenv("TMPDIR")) || //
(s = getenv("HOME")) || //
(s = ".")) {
ksnprintf(dsopath, sizeof(dsopath), "%s/sandbox.so", s);
if (!FileExistsAndIsNewerThan(dsopath,
argv[0] /*GetProgramExecutableName()*/)) {
ksnprintf(tmppath, sizeof(tmppath), "%s/sandbox.so.%d", s, getpid());
if (ExtractEmbeddedSandbox(tmppath, 0755) == -1) {
kprintf("error: extract dso failed: %m\n");
exit(1);
}
if (rename(tmppath, dsopath) == -1) {
kprintf("error: rename dso failed: %m\n");
exit(1);
}
}
ksnprintf(buf_ld_preload_env_var, sizeof(buf_ld_preload_env_var),
"LD_PRELOAD=%s", dsopath);
putenv(buf_ld_preload_env_var);
}
}
if (g_dontdrop) {
if (hasfunbits) {
kprintf("error: -D flag forbidden on setuid binaries\n");
_Exit(6);
}
} else {
DropCapabilities();
}
// set group id
if (usergid != ownergid) {
// setgid binaries must use the gid of the user that ran it
if (setgid(usergid) == -1) {
kprintf("error: setgid(%d) failed: %m\n", usergid);
_Exit(11);
}
if (getgid() != usergid || getegid() != usergid) {
kprintf("error: setgid() broken\n");
_Exit(12);
}
} else if (g_gflag) {
// otherwise we trust the gid flag
if (setgid(g_gflag) == -1) {
kprintf("error: setgid(%d) failed: %m\n", g_gflag);
_Exit(13);
}
if (getgid() != g_gflag || getegid() != g_gflag) {
kprintf("error: setgid() broken\n");
_Exit(14);
}
}
// set user id
if (useruid != owneruid) {
// setuid binaries must use the uid of the user that ran it
if (setuid(useruid) == -1) {
kprintf("error: setuid(%d) failed: %m\n", useruid);
_Exit(15);
}
if (getuid() != useruid || geteuid() != useruid) {
kprintf("error: setuid() broken\n");
_Exit(16);
}
} else if (g_uflag) {
// otherwise we trust the uid flag
if (setuid(g_uflag) == -1) {
kprintf("error: setuid(%d) failed: %m\n", g_uflag);
_Exit(17);
}
if (getuid() != g_uflag || geteuid() != g_uflag) {
kprintf("error: setuid() broken\n");
_Exit(18);
}
}
if (ParsePromises(g_promises, &ipromises) == -1) {
kprintf("error: bad promises list: %s\n", g_promises);
_Exit(21);
}
ApplyFilesystemPolicy(ipromises);
// pledge.com uses the return eperm instead of killing the process
// model. we do this becasue it's only possible to have sigsys print
// crash messages if we're not pledging exec, which is what this tool
// always has to do currently.
if (g_kflag) {
__pledge_mode = PLEDGE_PENALTY_KILL_PROCESS;
} else {
__pledge_mode = PLEDGE_PENALTY_RETURN_EPERM;
}
// we need to be able to call execv and mmap the dso
// it'll be pledged away once/if the dso gets loaded
if (!(~ipromises & (1ul << PROMISE_EXEC))) {
g_promises = xstrcat(g_promises, ' ', "exec");
if (!g_qflag) {
__pledge_mode |= PLEDGE_STDERR_LOGGING;
}
}
if (isdynamic) {
g_promises = xstrcat(g_promises, ' ', "prot_exec");
}
// pass arguments to pledge() inside the dso
if (isdynamic) {
ksnprintf(buf_pledge_env_var, sizeof(buf_pledge_env_var), "_PLEDGE=%ld,%ld",
~ipromises, __pledge_mode);
putenv(buf_pledge_env_var);
}
if (SetLimit(RLIMIT_NOFILE, g_nfdquota, g_nfdquota) == -1) {
kprintf("error: setrlimit(%s) failed: %m\n", "RLIMIT_NOFILE");
exit(1);
}
// apply sandbox
if (pledge(g_promises, g_promises) == -1) {
kprintf("error: pledge(%#s) failed: %m\n", g_promises);
_Exit(19);
}
extern char **environ;
// launch program
execve(prog, argv + optind, environ);
kprintf("%s: execve failed: %m\n", prog);
return 127;
}
| 24,610 | 873 | jart/plegde | false |
pledge/cmd/sandbox.c | /*-*- 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/pledge.h"
#include "libc/calls/pledge.internal.h"
#include "libc/intrin/promises.internal.h"
#include "libc/runtime/runtime.h"
/*
* runs pledge at glibc executable load time, e.g.
* strace -vff bash -c '_PLEDGE=4194303,0 LD_PRELOAD=$HOME/sandbox.so ls'
*/
__attribute__((__constructor__)) void init(void) {
int c, i, j;
const char *s;
uint64_t arg[2] = {0};
s = getenv("_PLEDGE");
for (i = j = 0; i < 2; ++i) {
while ((c = s[j] & 255)) {
++j;
if ('0' <= c & c <= '9') {
arg[i] *= 10;
arg[i] += c - '0';
} else {
break;
}
}
}
sys_pledge_linux(~arg[0], arg[1]);
}
| 2,524 | 48 | jart/plegde | false |
pledge/.ipynb_checkpoints/LICENSE-checkpoint | ISC License
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.
| 759 | 17 | jart/plegde | false |
cosmopolitan/LICENSE | ISC License
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.
| 759 | 17 | jart/cosmopolitan | false |
cosmopolitan/.gitignore | # -*- conf -*-
/o
/.prompt.jtlp
# TODO: Find some way to have Python write to o/
__pycache__
*.tmp
/.bochs.log
/HTAGS
/TAGS
/bx_enh_dbg.ini
/tool/emacs/*.elc
/perf.data
/perf.data.old
| 187 | 17 | jart/cosmopolitan | false |
cosmopolitan/CONTRIBUTING.md | # Contributing Guidelines
We'd love to accept your patches! Please read this guide first.
## Copyright Assignment
Please send an email to Justine Tunney <[email protected]> stating that
you intend to assign her the copyright to the changes you contribute to
Cosmopolitan. Please use the same email address you use for git commits
which should only contain original source code from you or other people
who are also assigning copyright. Please note that, if you're employed,
you may need to get your employer's approval beforehand. If you can not
assign copyright due to local laws, then you may alternatively consider
disclaiming it using the language in [Unlicense](https://unlicense.org)
or [CC-0](http://creativecommons.org/share-your-work/public-domain/cc0)
This is important because we can't produce 12kb single-file executables
that comply with license requirements if we have to embed lots of them.
Although that's less of an issue depending on the purpose of the files.
For example, ownership is much less of a concern in the unit test files
so you're encouraged to put your copyright on those, provided it's ISC.
## Style Guide
You can use clang-format to automatically format your files:
```sh
clang-format -i -style=file tool/net/redbean.c
```
If you use Emacs this can be automated on save for Cosmopolitan using
[tool/emacs/cosmo-format.el]([tool/emacs/cosmo-format.el]).
### Source Files
- Must use include paths relative to the root of the repository
- Must have comment at top of file documenting copyright and license
- Must have notice embedding if not owned by Justine (exception: tests)
- May use language extensions that are supported by both GCC and Clang
- Should use Google indentation (otherwise use `/* clang-format off */`)
- Should use asm() instead of compiler APIs (exception: ctz, clz, memcpy)
### Header Files
- Must not have copyright or license comments
- Must have once guards (otherwise change `.h` to `.inc`)
- Must be ANSI C89 compatible to be included in the amalgamation header
- Must include its dependencies (exception: libc/integral/normalize.inc)
- Must not define objects (i.e. `cc -c -xc foo.h` will produce empty `.o`)
- Should not use typedefs
- Should not use forward declarations
- Should not include documentation comments
- Should not include parameter names in prototypes
- Should not pose problems if included by C++ or Assembly sources
- Should not declare non-ANSI code, at all, when the user requests ANSI
### Build Config
- Must not write files outside `o/`
- Must not communicate with Internet
- Must not depend on system libraries
- Must not depend on system commands (exception: sh, make, gzip, zip)
| 2,675 | 63 | jart/cosmopolitan | false |
cosmopolitan/Makefile | #-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-â
#âââvi: set et ft=make ts=8 tw=8 fenc=utf-8 :viââââââââââââââââââââââââ
#
# SYNOPSIS
#
# Freestanding Hermetically-Sealed Monolithic Repository
#
# REQUIREMENTS
#
# You can run your programs on any operating system, but you have
# to build them on Linux 2.6+ (or WSL) using GNU Make. A modern C
# compiler that's statically-linked comes included as a courtesy.
#
# EXAMPLES
#
# # build and run everything
# make -j8 -O
# make -j8 -O MODE=dbg
# make -j8 -O MODE=opt
# make -j8 -O MODE=rel
# make -j8 -O MODE=tiny
#
# # build individual target
# make -j8 -O o//examples/hello.com
# o//examples/hello.com
#
# # view source
# less examples/hello.c
#
# # view binary
# o//tool/viz/bing.com o//examples/hello.com |
# o//tool/viz/fold.com
#
# # view transitive closure of legalese
# o//tool/viz/bing.com -n o//examples/hello.com |
# o//tool/viz/fold.com
#
# # basic debugging
# make -j8 -O MODE=dbg o/dbg/examples/crashreport.com
# o/examples/crashreport.com
# less examples/crashreport.c
#
# # extremely tiny binaries
# make -j8 -O MODE=tiny \
# LDFLAGS+=-s \
# CPPFLAGS+=-DIM_FEELING_NAUGHTY \
# CPPFLAGS+=-DSUPPORT_VECTOR=0b00000001 \
# o/tiny/examples/hello4.elf
# ls -hal o/tiny/examples/hello4.elf
# o/tiny/examples/hello4.elf
#
# TROUBLESHOOTING
#
# make -j8 -O V=1 o//examples/hello.com
# make o//examples/life.elf -pn |& less
# etc.
#
# SEE ALSO
#
# build/config.mk
SHELL = build/bootstrap/cocmd.com
MAKEFLAGS += --no-builtin-rules
.SUFFIXES:
.DELETE_ON_ERROR:
.FEATURES: output-sync
.PHONY: all o bins check test depend tags aarch64
ifneq ($(m),)
ifeq ($(MODE),)
MODE := $(m)
endif
endif
all: o
o: o/$(MODE)
o/$(MODE): \
o/$(MODE)/ape \
o/$(MODE)/dsp \
o/$(MODE)/net \
o/$(MODE)/libc \
o/$(MODE)/test \
o/$(MODE)/tool \
o/$(MODE)/examples \
o/$(MODE)/third_party
.STRICT = 1
.PLEDGE = stdio rpath wpath cpath fattr proc
.UNVEIL = \
libc/integral \
libc/disclaimer.inc \
rwc:/dev/shm \
rx:build/bootstrap \
rx:o/third_party/gcc \
/proc/stat \
rw:/dev/null \
w:o/stack.log \
/etc/hosts \
~/.runit.psk \
/proc/self/status \
/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
PKGS =
-include ~/.cosmo.mk
include build/functions.mk #ââ
include build/definitions.mk # âââMETA
include build/config.mk # â You can build
include build/rules.mk # â You can topologically order
include build/online.mk # â
include libc/stubs/stubs.mk #ââ
include libc/nexgen32e/nexgen32e.mk #ââ
include libc/sysv/sysv.mk # âââSYSTEM SUPPORT
include libc/nt/nt.mk # â You can do math
include libc/intrin/intrin.mk # â You can use the stack
include libc/linux/linux.mk # â You can manipulate arrays
include third_party/compiler_rt/compiler_rt.mk # â You can issue raw system calls
include libc/tinymath/tinymath.mk # â
include libc/str/str.mk # â
include third_party/xed/xed.mk # â
include third_party/puff/puff.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 # â
include libc/vga/vga.mk #ââ
include libc/calls/calls.mk #ââ
include third_party/getopt/getopt.mk # â
include libc/runtime/runtime.mk # âââSYSTEMS RUNTIME
include libc/crt/crt.mk # â You can issue system calls
include tool/hello/hello.mk # â
include third_party/nsync/nsync.mk # â
include third_party/dlmalloc/dlmalloc.mk #ââ
include libc/mem/mem.mk #ââ
include third_party/gdtoa/gdtoa.mk # âââDYNAMIC RUNTIME
include third_party/nsync/mem/mem.mk # â You can now use stdio
include libc/thread/thread.mk # â You can finally call malloc()
include libc/zipos/zipos.mk # â
include libc/time/time.mk # â
include libc/stdio/stdio.mk # â
include third_party/libcxx/libcxx.mk # â
include net/net.mk # â
include third_party/vqsort/vqsort.mk # â
include libc/log/log.mk # â
include third_party/ggml/ggml.mk # â
include third_party/radpajama/radpajama.mk # â
include third_party/bzip2/bzip2.mk # â
include dsp/core/core.mk # â
include libc/x/x.mk # â
include third_party/stb/stb.mk # â
include dsp/scale/scale.mk # â
include dsp/mpeg/mpeg.mk # â
include dsp/dsp.mk # â
include third_party/zlib/gz/gz.mk # â
include third_party/musl/musl.mk # â
include third_party/intel/intel.mk # â
include third_party/aarch64/aarch64.mk # â
include libc/libc.mk #ââ
include libc/sock/sock.mk #ââ
include dsp/tty/tty.mk # âââONLINE RUNTIME
include libc/dns/dns.mk # â You can communicate with the network
include net/http/http.mk # â
include third_party/mbedtls/mbedtls.mk # â
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
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/lua/lua.mk
include third_party/tr/tr.mk
include third_party/sed/sed.mk
include third_party/awk/awk.mk
include third_party/hiredis/hiredis.mk
include third_party/make/make.mk
include third_party/ctags/ctags.mk
include third_party/finger/finger.mk
include third_party/argon2/argon2.mk
include third_party/smallz4/smallz4.mk
include third_party/sqlite3/sqlite3.mk
include third_party/mbedtls/test/test.mk
include third_party/quickjs/quickjs.mk
include third_party/lz4cli/lz4cli.mk
include third_party/zip/zip.mk
include third_party/unzip/unzip.mk
include tool/build/lib/buildlib.mk
include third_party/chibicc/chibicc.mk
include third_party/chibicc/test/test.mk
include third_party/python/python.mk
include tool/build/emucrt/emucrt.mk
include tool/build/emubin/emubin.mk
include tool/build/build.mk
include tool/curl/curl.mk
include third_party/qemu/qemu.mk
include examples/examples.mk
include examples/pyapp/pyapp.mk
include examples/pylife/pylife.mk
include tool/decode/lib/decodelib.mk
include tool/decode/decode.mk
include tool/lambda/lib/lib.mk
include tool/lambda/lambda.mk
include tool/plinko/lib/lib.mk
include tool/plinko/plinko.mk
include test/tool/plinko/test.mk
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
include test/libc/nexgen32e/test.mk
include test/libc/runtime/test.mk
include test/libc/thread/test.mk
include test/libc/sock/test.mk
include test/libc/str/test.mk
include test/libc/log/test.mk
include test/libc/str/test.mk
include test/libc/calls/test.mk
include test/libc/x/test.mk
include test/libc/xed/test.mk
include test/libc/fmt/test.mk
include test/libc/dns/test.mk
include test/libc/time/test.mk
include test/libc/stdio/test.mk
include test/libc/zipos/test.mk
include test/libc/release/test.mk
include test/libc/test.mk
include test/net/http/test.mk
include test/net/https/test.mk
include test/net/finger/test.mk
include test/net/test.mk
include test/tool/build/lib/test.mk
include test/tool/build/test.mk
include test/tool/viz/lib/test.mk
include test/tool/viz/test.mk
include test/tool/net/test.mk
include test/tool/test.mk
include test/dsp/core/test.mk
include test/dsp/scale/test.mk
include test/dsp/tty/test.mk
include test/dsp/test.mk
include examples/package/lib/build.mk
include examples/package/build.mk
#-Ï-examples/package/new.sh
include test/test.mk
OBJS = $(foreach x,$(PKGS),$($(x)_OBJS))
SRCS := $(foreach x,$(PKGS),$($(x)_SRCS))
HDRS := $(foreach x,$(PKGS),$($(x)_HDRS))
INCS = $(foreach x,$(PKGS),$($(x)_INCS))
BINS = $(foreach x,$(PKGS),$($(x)_BINS))
TESTS = $(foreach x,$(PKGS),$($(x)_TESTS))
CHECKS = $(foreach x,$(PKGS),$($(x)_CHECKS))
bins: $(BINS)
check: $(CHECKS)
test: $(TESTS) aarch64
depend: o/$(MODE)/depend
tags: TAGS HTAGS
o/$(MODE)/.x:
@$(COMPILE) -AMKDIR -tT$@ $(MKDIR) $(@D)
o/$(MODE)/srcs.txt: o/$(MODE)/.x $(MAKEFILES) $(call uniq,$(foreach x,$(SRCS),$(dir $(x))))
$(file >$@,$(SRCS))
o/$(MODE)/hdrs.txt: o/$(MODE)/.x $(MAKEFILES) $(call uniq,$(foreach x,$(HDRS) $(INCS),$(dir $(x))))
$(file >$@,$(HDRS) $(INCS))
o/$(MODE)/incs.txt: o/$(MODE)/.x $(MAKEFILES) $(call uniq,$(foreach x,$(INCS) $(INCS),$(dir $(x))))
$(file >$@,$(INCS))
o/$(MODE)/depend: o/$(MODE)/.x o/$(MODE)/srcs.txt o/$(MODE)/hdrs.txt o/$(MODE)/incs.txt $(SRCS) $(HDRS) $(INCS)
@$(COMPILE) -AMKDEPS -L320 $(MKDEPS) -o $@ -r o/$(MODE)/ @o/$(MODE)/srcs.txt @o/$(MODE)/hdrs.txt @o/$(MODE)/incs.txt
o/$(MODE)/srcs-old.txt: o/$(MODE)/.x $(MAKEFILES) $(call uniq,$(foreach x,$(SRCS),$(dir $(x))))
$(file >$@) $(foreach x,$(SRCS),$(file >>$@,$(x)))
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: o/$(MODE)/srcs-old.txt $(SRCS) #o/$(MODE)/third_party/ctags/ctags.com
@$(RM) $@
@o/$(MODE)/third_party/ctags/ctags.com $(TAGSFLAGS) -L $< -o $@
HTAGS: private .UNSANDBOXED = 1
HTAGS: o/$(MODE)/hdrs-old.txt $(HDRS) #o/$(MODE)/third_party/ctags/ctags.com
@$(RM) $@
@build/htags o/$(MODE)/third_party/ctags/ctags.com -L $< -o $@
loc: private .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_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_PUFF \
THIRD_PARTY_COMPILER_RT \
LIBC_TINYMATH \
THIRD_PARTY_XED \
LIBC_STR \
LIBC_SYSV \
LIBC_INTRIN \
LIBC_NT_KERNEL32 \
LIBC_NEXGEN32E
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_REGEX
o/$(MODE)/cosmopolitan.a: \
$(foreach x,$(COSMOPOLITAN_OBJECTS),$($(x)_A_OBJS))
o/cosmopolitan.h: \
o/$(MODE)/tool/build/rollup.com \
libc/integral/normalize.inc \
$(foreach x,$(COSMOPOLITAN_HEADERS),$($(x)_HDRS)) \
$(foreach x,$(COSMOPOLITAN_HEADERS),$($(x)_INCS))
$(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: \
o/$(MODE)/third_party/chibicc/chibicc.com.dbg \
$(filter-out %.s,$(foreach x,$(COSMOPOLITAN_OBJECTS),$($(x)_SRCS))) \
$(SRCS) \
$(HDRS)
$(file >$(TMPDIR)/$(subst /,_,$@),$(filter-out %.s,$(foreach x,$(COSMOPOLITAN_OBJECTS),$($(x)_SRCS))))
o/$(MODE)/third_party/chibicc/chibicc.com.dbg -J \
-fno-common -include libc/integral/normalize.inc -o $@ \
@$(TMPDIR)/$(subst /,_,$@)
$(SRCS): \
libc/integral/normalize.inc \
libc/integral/c.inc \
libc/integral/cxx.inc \
libc/integral/cxxtypescompat.inc \
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 \
o/$(MODE)/third_party/libcxx/libcxx.a
aarch64: private .INTERNET = true
aarch64: private .UNSANDBOXED = true
aarch64:
$(MAKE) m=aarch64
# UNSPECIFIED PREREQUISITES TUTORIAL
#
# A build rule must exist for all files that make needs to consider in
# order to build the requested goal. That includes input source files,
# even if the rule is empty and does nothing. Otherwise, the .DEFAULT
# rule gets triggered.
#
# This is a normal and neecssary behavior when source files get deleted.
# The build reacts automatically to this happening, by simply deleting
# and regenerating the dependency graph; so we can safely use wildcard.
#
# This is abnormal if it needs to keep doing that repeatedly. That can
# only mean the build config is broken.
#
# Also note that a suboptimal in-between state may exist, where running
# `make -pn` reveals rules being generated with the .DEFAULT target, but
# never get executed since they're not members of the transitive closure
# of `make all`. In that case the build config could be improved.
%.mk:
~/.cosmo.mk:
$(SRCS):
$(HDRS):
$(INCS):
.DEFAULT:
@$(ECHO)
@$(ECHO) NOTE: deleting o/$(MODE)/depend because of an unspecified prerequisite: $@
@$(ECHO)
$(RM) o/$(MODE)/depend
-include o/$(MODE)/depend
| 13,990 | 461 | jart/cosmopolitan | false |
cosmopolitan/.clang-format | ---
BasedOnStyle: Google
StatementMacros:
- INITIALIZER
AlignConsecutiveMacros: true
AlignConsecutiveDeclarations: false
AlwaysBreakBeforeMultilineStrings: false
AllowShortFunctionsOnASingleLine: false
KeepEmptyLinesAtTheStartOfBlocks: true
ConstructorInitializerAllOnOneLineOrOnePerLine: true
IncludeBlocks: Merge
---
Language: Cpp
AllowShortFunctionsOnASingleLine: false
---
Language: Proto
...
| 399 | 18 | jart/cosmopolitan | false |
cosmopolitan/README.md | ![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 Libc](https://justine.lol/cosmopolitan/index.html) makes C
a build-once run-anywhere language, like Java, except it doesn't need an
interpreter or virtual machine. Instead, it reconfigures stock GCC and
Clang to output a POSIX-approved polyglot format that runs natively on
Linux + Mac + Windows + FreeBSD + OpenBSD + NetBSD + BIOS with the best
possible performance and the tiniest footprint imaginable.
## Background
For an introduction to this project, please read the [αcϵαlly pδrÏαblε
εxεcµÏαblε](https://justine.lol/ape.html) blog post and [cosmopolitan
libc](https://justine.lol/cosmopolitan/index.html) website. We also have
[API documentation](https://justine.lol/cosmopolitan/documentation.html).
## Getting Started
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.2.zip
unzip cosmopolitan-amalgamation-2.2.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 \
-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
```
You now have a portable program.
```sh
./hello.com
bash -c './hello.com' # zsh/fish workaround (we patched them in 2021)
```
If `./hello.com` executed on Linux throws an error about not finding an
interpreter, it should be fixed by running the following command (although
note that it may not survive a system restart):
```sh
sudo sh -c "echo ':APE:M::MZqFpD::/bin/sh:' >/proc/sys/fs/binfmt_misc/register"
```
If the same command produces puzzling errors on WSL or WINE when using
Redbean 2.x, they may be fixed by disabling binfmt_misc:
```sh
sudo sh -c 'echo -1 >/proc/sys/fs/binfmt_misc/status'
```
Since we used the `ape-no-modify-self.o` bootloader (rather than
`ape.o`) your executable will not modify itself when it's run. What
it'll instead do, is extract a 4kb program (the [APE loader](https://justine.lol/apeloader/))
to `${TMPDIR:-${HOME:-.}}` that maps your program into memory without
needing to copy it. The APE loader must be in an executable location
(e.g. not stored on a `noexec` mount) for it to run. See below for
alternatives:
It's possible to install the APE loader systemwide as follows.
```sh
# System-Wide APE Install
# for Linux, Darwin, and BSDs
# 1. Copies APE Loader to /usr/bin/ape
# 2. Registers w/ binfmt_misc too if Linux
ape/apeinstall.sh
# System-Wide APE Uninstall
# for Linux, Darwin, and BSDs
ape/apeuninstall.sh
```
It's also possible to convert APE binaries into the system-local format
by using the `--assimilate` flag. Please note that if binfmt_misc is in
play, you'll need to unregister it temporarily before doing this, since
the assimilate feature is part of the shell script header.
```sh
$ file hello.com
hello.com: DOS/MBR boot sector
./hello.com --assimilate
$ file hello.com
hello.com: ELF 64-bit LSB executable
```
Now that you're up and running with Cosmopolitan Libc and APE, here's
some of the most important troubleshooting tools APE offers that you
should know, in case you encounter any issues:
```sh
./hello.com --strace # log system calls to stderr
./hello.com --ftrace # log function calls to stderr
```
Do you love tiny binaries? If so, you may not be happy with Cosmo adding
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
```
Which will cause programs such as `hello.com` and `life.com` to shrink
from 60kb in size to about 16kb. There's also a prebuilt amalgamation
online <https://justine.lol/cosmopolitan/cosmopolitan-tiny.zip> hosted
on our download page <https://justine.lol/cosmopolitan/download.html>.
### MacOS
If you're developing on MacOS you can install the GNU compiler
collection for x86_64-elf via homebrew:
```sh
brew install x86_64-elf-gcc
```
Then in the above scripts just replace `gcc` and `objcopy` with
`x86_64-elf-gcc` and `x86_64-elf-objcopy` to compile your APE binary.
### Windows
If you're developing on Windows then you need to download an
x86_64-pc-linux-gnu toolchain beforehand. See the [Compiling on
Windows](https://justine.lol/cosmopolitan/windows-compiling.html)
tutorial. It's needed because the ELF object format is what makes
universal binaries possible.
Cosmopolitan officially only builds on Linux. However, one highly
experimental (and currently broken) thing you could try, is building the
entire cosmo repository from source using the cross9 toolchain.
```
mkdir -p o/third_party
rm -rf o/third_party/gcc
wget https://justine.lol/linux-compiler-on-windows/cross9.zip
unzip cross9.zip
mv cross9 o/third_party/gcc
build/bootstrap/make.com
```
## Source Builds
Cosmopolitan can be compiled from source on any Linux distro. First, you
need to download or clone the repository.
```sh
wget https://justine.lol/cosmopolitan/cosmopolitan.tar.gz
tar xf cosmopolitan.tar.gz # see releases page
cd cosmopolitan
```
This will build the entire repository and run all the tests:
```sh
build/bootstrap/make.com
o//examples/hello.com
find o -name \*.com | xargs ls -rShal | less
```
If you get an error running make.com then it's probably because you have
WINE installed to `binfmt_misc`. You can fix that by installing the the
APE loader as an interpreter. It'll improve build performance too!
```sh
ape/apeinstall.sh
```
Since the Cosmopolitan repository is very large, you might only want to
build a particular thing. Cosmopolitan's build config does a good job at
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
```
Sometimes it's desirable to build a subset of targets, without having to
list out each individual one. You can do that by asking make to build a
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
o//third_party/chibicc/chibicc.com --help
```
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
```
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
```
For further details, see [//build/config.mk](build/config.mk).
## GDB
Here's the recommended `~/.gdbinit` config:
```gdb
set host-charset UTF-8
set target-charset UTF-8
set target-wide-charset UTF-8
set osabi none
set complaints 0
set confirm off
set history save on
set history filename ~/.gdb_history
define asm
layout asm
layout reg
end
define src
layout src
layout reg
end
src
```
You normally run the `.com.dbg` file under gdb. If you need to debug the
`.com` file itself, then you can load the debug symbols independently as
```
gdb foo.com -ex 'add-symbol-file foo.com.dbg 0x401000'
```
## Discord Chatroom
The Cosmopolitan development team collaborates on the Redbean Discord
server. You're welcome to join us! <https://discord.gg/FwAVVu7eJ4>
## Support Vector
| Platform | Min Version | Circa |
| :--- | ---: | ---: |
| AMD | K8 Venus | 2005 |
| Intel | Core | 2006 |
| Linux | 2.6.18 | 2007 |
| Windows | 8 [1] | 2012 |
| Mac OS X | 15.6 | 2018 |
| OpenBSD | 6.4 | 2018 |
| FreeBSD | 13 | 2020 |
| NetBSD | 9.2 | 2021 |
[1] See our [vista branch](https://github.com/jart/cosmopolitan/tree/vista)
for a community supported version of Cosmopolitan that works on Windows
Vista and Windows 7.
## Special Thanks
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:
- [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.
| 9,179 | 281 | jart/cosmopolitan | false |
cosmopolitan/.gitattributes | # -*- conf -*-
*.gz binary
/build/bootstrap/*.com binary
/build/bootstrap/*.com binary
/usr/share/zoneinfo/* binary
| 159 | 6 | jart/cosmopolitan | false |
cosmopolitan/libc/complex.h | #ifndef _COMPLEX_H
#define _COMPLEX_H
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
#if __STDC_VERSION__ + 0 >= 201112 && !defined(__STDC_NO_COMPLEX__)
#define complex _Complex
#define imaginary _Imaginary
double cabs(complex double);
double carg(complex double);
double cimag(complex double);
double creal(complex double);
float cabsf(complex float);
float cargf(complex float);
float cimagf(complex float);
float crealf(complex float);
long double cabsl(complex long double);
long double cargl(complex long double);
long double cimagl(complex long double);
long double creall(complex long double);
complex double cacos(complex double);
complex double cacosh(complex double);
complex double casin(complex double);
complex double casinh(complex double);
complex double catan(complex double);
complex double catanh(complex double);
complex double ccos(complex double);
complex double ccosh(complex double);
complex double cexp(complex double);
complex double cexp2(complex double);
complex double clog(complex double);
complex double conj(complex double);
complex double cpow(complex double, complex double);
complex double cproj(complex double);
complex double csin(complex double);
complex double csinh(complex double);
complex double csqrt(complex double);
complex double ctan(complex double);
complex double ctanh(complex double);
complex float cacosf(complex float);
complex float cacoshf(complex float);
complex float casinf(complex float);
complex float casinhf(complex float);
complex float catanf(complex float);
complex float catanhf(complex float);
complex float ccosf(complex float);
complex float ccoshf(complex float);
complex float cexpf(complex float);
complex float cexp2f(complex float);
complex float clogf(complex float);
complex float conjf(complex float);
complex float cpowf(complex float, complex float);
complex float cprojf(complex float);
complex float csinf(complex float);
complex float csinhf(complex float);
complex float csqrtf(complex float);
complex float ctanf(complex float);
complex float ctanhf(complex float);
complex long double cprojl(complex long double);
complex long double csinhl(complex long double);
complex long double csinl(complex long double);
complex long double csqrtl(complex long double);
complex long double ctanhl(complex long double);
complex long double ctanl(complex long double);
complex long double cacoshl(complex long double);
complex long double cacosl(complex long double);
complex long double casinhl(complex long double);
complex long double casinl(complex long double);
complex long double catanhl(complex long double);
complex long double catanl(complex long double);
complex long double ccoshl(complex long double);
complex long double ccosl(complex long double);
complex long double cexpl(complex long double);
complex long double cexp2l(complex long double);
complex long double clogl(complex long double);
complex long double conjl(complex long double);
complex long double cpowl(complex long double, complex long double);
#ifndef __cplusplus
#define __CIMAG(x, t) \
(+(union { \
_Complex t __z; \
t __xy[2]; \
}){(_Complex t)(x)} \
.__xy[1])
#define creal(x) ((double)(x))
#define crealf(x) ((float)(x))
#define creall(x) ((long double)(x))
#define cimag(x) __CIMAG(x, double)
#define cimagf(x) __CIMAG(x, float)
#define cimagl(x) __CIMAG(x, long double)
#endif
#ifdef __GNUC__
#define _Complex_I (__extension__(0.0f + 1.0fi))
#else
#define _Complex_I (0.0f + 1.0fi)
#endif
#ifdef _Imaginary_I
#define __CMPLX(x, y, t) ((t)(x) + _Imaginary_I * (t)(y))
#elif defined(__clang__)
#define __CMPLX(x, y, t) (+(_Complex t){(t)(x), (t)(y)})
#else
#define __CMPLX(x, y, t) (__builtin_complex((t)(x), (t)(y)))
#endif
#define CMPLX(x, y) __CMPLX(x, y, double)
#define CMPLXF(x, y) __CMPLX(x, y, float)
#define CMPLXL(x, y) __CMPLX(x, y, long double)
#endif /* C11 */
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* _COMPLEX_H */
| 4,001 | 122 | jart/cosmopolitan | false |
cosmopolitan/libc/assert.h | #ifndef COSMOPOLITAN_LIBC_ASSERT_H_
#define COSMOPOLITAN_LIBC_ASSERT_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern bool __assert_disable;
void __assert_fail(const char *, const char *, int) _Hide relegated;
#ifdef NDEBUG
#define assert(x) ((void)0)
#else
#define assert(x) ((void)((x) || (__assert_fail(#x, __FILE__, __LINE__), 0)))
#endif
#ifndef __cplusplus
#define static_assert _Static_assert
#endif
#ifndef NDEBUG
#define _unassert(x) __assert_macro(x, #x)
#define _npassert(x) __assert_macro(x, #x)
#define __assert_macro(x, s) \
({ \
if (__builtin_expect(!(x), 0)) { \
__assert_fail(s, __FILE__, __LINE__); \
notpossible; \
} \
(void)0; \
})
#else
#define _unassert(x) \
({ \
if (__builtin_expect(!(x), 0)) { \
unreachable; \
} \
(void)0; \
})
#define _npassert(x) \
({ \
if (__builtin_expect(!(x), 0)) { \
notpossible; \
} \
(void)0; \
})
#endif
#ifdef __GNUC__
#endif
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_ASSERT_H_ */
| 1,484 | 53 | jart/cosmopolitan | false |
cosmopolitan/libc/limits.h | #ifndef COSMOPOLITAN_LIBC_LIMITS_H_
#define COSMOPOLITAN_LIBC_LIMITS_H_
#define __STDC_LIMIT_MACROS
#define UCHAR_MIN 0
#define UCHAR_MAX 255
#if '\200' < 0
#define CHAR_MIN '\200'
#define CHAR_MAX '\177'
#else
#define CHAR_MIN '\0'
#define CHAR_MAX '\377'
#endif
#define SCHAR_MAX __SCHAR_MAX__
#define SHRT_MAX __SHRT_MAX__
#define INT_MAX __INT_MAX__
#define LONG_MAX __LONG_MAX__
#define LLONG_MAX LONG_LONG_MAX
#define LONG_LONG_MAX __LONG_LONG_MAX__
#define SIZE_MAX __SIZE_MAX__
#define INT8_MAX __INT8_MAX__
#define INT16_MAX __INT16_MAX__
#define INT32_MAX __INT32_MAX__
#define INT64_MAX __INT64_MAX__
#define WINT_MAX __WCHAR_MAX__
#define WCHAR_MAX __WCHAR_MAX__
#define INTPTR_MAX __INTPTR_MAX__
#define PTRDIFF_MAX __PTRDIFF_MAX__
#define UINTPTR_MAX __UINTPTR_MAX__
#define UINT8_MAX __UINT8_MAX__
#define UINT16_MAX __UINT16_MAX__
#define UINT32_MAX __UINT32_MAX__
#define UINT64_MAX __UINT64_MAX__
#define INTMAX_MAX __INTMAX_MAX__
#define UINTMAX_MAX __UINTMAX_MAX__
#define SSIZE_MAX __INT64_MAX__
#define SCHAR_MIN (-SCHAR_MAX - 1)
#define SHRT_MIN (-SHRT_MAX - 1)
#define INT_MIN (-INT_MAX - 1)
#define LONG_MIN (-LONG_MAX - 1)
#define LLONG_MIN (-LLONG_MAX - 1)
#define LONG_LONG_MIN (-LONG_LONG_MAX - 1)
#define SIZE_MIN (-SIZE_MAX - 1)
#define INT8_MIN (-INT8_MAX - 1)
#define INT16_MIN (-INT16_MAX - 1)
#define INT32_MIN (-INT32_MAX - 1)
#define INT64_MIN (-INT64_MAX - 1)
#define INTMAX_MIN (-INTMAX_MAX - 1)
#define INTPTR_MIN (-INTPTR_MAX - 1)
#define WINT_MIN (-WINT_MAX - 1)
#define WCHAR_MIN (-WCHAR_MAX - 1)
#define PTRDIFF_MIN (-PTRDIFF_MAX - 1)
#define USHRT_MAX 65535
#define UINT_MAX 0xffffffffu
#if __SIZEOF_LONG__ == 8
#define ULONG_MAX 0xfffffffffffffffful
#else
#define ULONG_MAX 0xfffffffful
#endif
#define ULLONG_MAX 0xffffffffffffffffull
#define ULONG_LONG_MAX 0xffffffffffffffffull
#define USHRT_MIN 0
#define UINT_MIN 0u
#define ULONG_MIN 0ul
#define ULLONG_MIN 0ull
#define ULONG_LONG_MIN 0ull
#define UINT8_MIN 0
#define UINT16_MIN 0
#define UINT32_MIN 0u
#define UINT64_MIN 0ull
#define UINTPTR_MIN 0ull
#define UINTMAX_MIN ((uintmax_t)0)
#define MB_CUR_MAX 4
#define MB_LEN_MAX 4
#if __GNUC__ * 100 + __GNUC_MINOR__ >= 406 || defined(__llvm__)
#define INT128_MIN (-INT128_MAX - 1)
#define UINT128_MIN ((uint128_t)0)
#define INT128_MAX \
((int128_t)0x7fffffffffffffff << 64 | (int128_t)0xffffffffffffffff)
#define UINT128_MAX \
((uint128_t)0xffffffffffffffff << 64 | (uint128_t)0xffffffffffffffff)
#endif /* GCC 4.6+ */
#define SIG_ATOMIC_MIN INT32_MIN
#define SIG_ATOMIC_MAX INT32_MAX
#define FILESIZEBITS 64
#define SYMLOOP_MAX 40
#define TTY_NAME_MAX 32
#define HOST_NAME_MAX 255
#define TZNAME_MAX 6
#define WORD_BIT 32
#define SEM_VALUE_MAX 0x7fffffff
#define SEM_NSEMS_MAX 256
#define DELAYTIMER_MAX 0x7fffffff
#define MQ_PRIO_MAX 32768
#define LOGIN_NAME_MAX 256
#define NL_ARGMAX 9
#define NL_MSGMAX 32767
#define NL_SETMAX 255
#define NL_TEXTMAX 2048
#define INT_FAST8_MIN (-__INT_FAST8_MAX__ - 1)
#define INT_FAST16_MIN (-__INT_FAST16_MAX__ - 1)
#define INT_FAST32_MIN (-__INT_FAST32_MAX__ - 1)
#define INT_FAST64_MIN (-__INT_FAST64_MAX__ - 1)
#define INT_LEAST8_MIN (-__INT_LEAST8_MAX__ - 1)
#define INT_LEAST16_MIN (-__INT_LEAST16_MAX__ - 1)
#define INT_LEAST32_MIN (-__INT_LEAST32_MAX__ - 1)
#define INT_LEAST64_MIN (-__INT_LEAST64_MAX__ - 1)
#define INT_FAST8_MAX __INT_FAST8_MAX__
#define INT_FAST16_MAX __INT_FAST16_MAX__
#define INT_FAST32_MAX __INT_FAST32_MAX__
#define INT_FAST64_MAX __INT_FAST64_MAX__
#define INT_LEAST8_MAX __INT_LEAST8_MAX__
#define INT_LEAST16_MAX __INT_LEAST16_MAX__
#define INT_LEAST32_MAX __INT_LEAST32_MAX__
#define INT_LEAST64_MAX __INT_LEAST64_MAX__
#define UINT_FAST8_MAX __UINT_FAST8_MAX__
#define UINT_FAST16_MAX __UINT_FAST16_MAX__
#define UINT_FAST32_MAX __UINT_FAST32_MAX__
#define UINT_FAST64_MAX __UINT_FAST64_MAX__
#define UINT_LEAST8_MAX __UINT_LEAST8_MAX__
#define UINT_LEAST16_MAX __UINT_LEAST16_MAX__
#define UINT_LEAST32_MAX __UINT_LEAST32_MAX__
#define UINT_LEAST64_MAX __UINT_LEAST64_MAX__
#define BC_BASE_MAX 99
#define BC_DIM_MAX 2048
#define BC_SCALE_MAX 99
#define BC_STRING_MAX 1000
#define CHARCLASS_NAME_MAX 14
#define COLL_WEIGHTS_MAX 2
#define EXPR_NEST_MAX 32
#define LINE_MAX 4096
#define RE_DUP_MAX 255
#define LONG_BIT 64
#define NZERO 20
#define NL_LANGMAX 32
#endif /* COSMOPOLITAN_LIBC_LIMITS_H_ */
| 4,681 | 150 | jart/cosmopolitan | false |
cosmopolitan/libc/macros.internal.h | #ifndef COSMOPOLITAN_LIBC_MACROS_H_
#define COSMOPOLITAN_LIBC_MACROS_H_
#if 0
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § macros ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#endif
/**
* @fileoverview Common C preprocessor, assembler, and linker macros.
*/
#define TRUE 1
#define FALSE 0
#define IS2POW(X) (!((X) & ((X)-1)))
#define ROUNDUP(X, K) (((X) + (K)-1) & -(K))
#define ROUNDDOWN(X, K) ((X) & -(K))
#ifndef __ASSEMBLER__
#define ABS(X) ((X) >= 0 ? (X) : -(X))
#define MIN(X, Y) ((Y) > (X) ? (X) : (Y))
#define MAX(X, Y) ((Y) < (X) ? (X) : (Y))
#else
// The GNU assembler does not grok the ?: ternary operator; furthermore,
// boolean expressions yield -1 and 0 for "true" and "false", not 1 and 0.
#define __MAPBOOL(P) (!!(P) / (!!(P) + !(P)))
#define __IFELSE(P, X, Y) (__MAPBOOL(P) * (X) + __MAPBOOL(!(P)) * (Y))
#define MIN(X, Y) (__IFELSE((Y) > (X), (X), (Y)))
#define MAX(X, Y) (__IFELSE((Y) < (X), (X), (Y)))
#endif
#define PASTE(A, B) __PASTE(A, B)
#define STRINGIFY(A) __STRINGIFY(A)
#define EQUIVALENT(X, Y) (__builtin_constant_p((X) == (Y)) && ((X) == (Y)))
#define TYPE_BIT(type) (sizeof(type) * CHAR_BIT)
#define TYPE_SIGNED(type) (((type)-1) < 0)
#define TYPE_INTEGRAL(type) (((type)0.5) != 0.5)
#define ARRAYLEN(A) \
((sizeof(A) / sizeof(*(A))) / ((unsigned)!(sizeof(A) % sizeof(*(A)))))
#define __STRINGIFY(A) #A
#define __PASTE(A, B) A##B
#ifdef __ASSEMBLER__
// clang-format off
// Ends function definition.
// @cost saves 1-3 lines of code
.macro .endfn name:req bnd vis
.size "\name",.-"\name"
.type "\name",@function
.ifnb \bnd
.\bnd "\name"
.endif
.ifnb \vis
.\vis "\name"
.endif
.endm
// Ends variable definition.
// @cost saves 1-3 lines of code
.macro .endobj name:req bnd vis
.size "\name",.-"\name"
.type "\name",@object
.ifnb \bnd
.\bnd "\name"
.endif
.ifnb \vis
.\vis "\name"
.endif
.endm
// Shorthand notation for widely-acknowledged sections.
.macro .rodata
.section .rodata,"a",@progbits
.endm
.macro .init
.section .init,"ax",@progbits
.endm
.macro .real
.section .text.real,"ax",@progbits
.endm
.macro .head
.section .text.head,"ax",@progbits
.endm
.macro .text.startup
.section .text.startup,"ax",@progbits
.endm
.macro .text.exit
.section .text.exit,"ax",@progbits
.endm
.macro .firstclass
.section .text.hot,"ax",@progbits
.endm
.macro .text.unlikely
.section .text.unlikely,"ax",@progbits
.endm
.macro .text.likely
.section .text.hot,"ax",@progbits
.endm
.macro .text.modernity
.section .text.modernity,"ax",@progbits
.balign 16
.endm
.macro .text.antiquity
.section .text.antiquity,"ax",@progbits
.endm
.macro .text.hot
.section .text.hot,"ax",@progbits
.endm
.macro .preinit_array
.section .preinit_array,"a",@init_array
.endm
.macro .init_array
.section .init_array,"a",@init_array
.endm
.macro .text.windows
.section .text.windows,"ax",@progbits
.endm
// Mergeable NUL-terminated UTF-8 string constant section.
//
// @note linker de-dupes C strings here across whole compile
// @note therefore item/values are reordered w.r.t. link order
// @note therefore no section relative addressing
.macro .rodata.str1.1
.section .rodata.str1.1,"aMS",@progbits,1
.balign 1
.endm
// Locates unreferenced code invulnerable to --gc-sections.
.macro .keep.text
.section .keep.text,"ax",@progbits
.endm
// Flags code as only allowed for testing purposes.
.macro .testonly
.section .test,"ax",@progbits
.endm
// Makes code runnable while code morphing.
.macro .privileged
.section .privileged,"ax",@progbits
.endm
// Declares alternative implementation of function.
// @param implement e.g. tinymath_pow
// @param canonical e.g. pow
.macro .alias implement:req canonical:req
.equ \canonical,\implement
.weak \canonical
.endm
#ifdef __aarch64__
.macro jmp dest:req
b \dest
.endm
#endif
// Pulls unrelated module into linkage.
//
// In order for this technique to work with --gc-sections, another
// module somewhere might want to weakly reference whats yoinked.
.macro .yoink symbol:req
.section .yoink
#ifdef __x86_64__
nopl "\symbol"(%rip)
#elif defined(__aarch64__)
b "\symbol"
#endif
.previous
.endm
// Begins definition of frameless function that calls no functions.
.macro .leafprologue
#if !(defined(TINY) && !defined(__PG__))
#ifdef __x86_64__
push %rbp
mov %rsp,%rbp
#elif defined(__aarch64__)
stp x29,x30,[sp,#-16]!
mov x29,sp
#endif
#endif
.endm
// Ends definition of frameless function that calls no functions.
.macro .leafepilogue
#if !(defined(TINY) && !defined(__PG__))
#ifdef __x86_64__
pop %rbp
#elif defined(__aarch64__)
ldp x29,x30,[sp],#16
#endif
#endif
ret
.endm
// Documents unreachable assembly code.
.macro .unreachable
#if !defined(NDEBUG) && defined(__x86_64__)
ud2 // crash if contract is broken
#elif !defined(NDEBUG) && defined(__aarch64__)
brk #1000
#elif defined(__FNO_OMIT_FRAME_POINTER__)
nop // avoid noreturn tail call backtrace ambiguity
#endif
.endm
// Embeds Fixed-Width Zero-Padded String.
// @note .fxstr is better
.macro .ascin str:req fieldsize:req
1347: .ascii "\str"
.org 1347b+\fieldsize,0x00
.endm
#ifdef __x86_64__
#if __MNO_VZEROUPPER__ + 0
#define vzeroupper
#endif
// Mergeable numeric constant sections.
//
// @note linker de-dupes item/values across whole compile
// @note therefore item/values are reordered w.r.t. link order
// @note therefore no section relative addressing
.macro .rodata.cst4
.section .rodata.cst4,"aM",@progbits,4
.balign 4
.endm
.macro .rodata.cst8
.section .rodata.cst8,"aM",@progbits,8
.balign 8
.endm
.macro .rodata.cst16
.section .rodata.cst16,"aM",@progbits,16
.balign 16
.endm
.macro .rodata.cst32
.section .rodata.cst32,"aM",@progbits,32
.balign 32
.endm
.macro .rodata.cst64
.section .rodata.cst64,"aM",@progbits,64
.balign 64
.endm
.macro .tdata
.section .tdata,"awT",@progbits
.balign 4
.endm
.macro .tbss
.section .tdata,"awT",@nobits
.balign 4
.endm
// Loads address of errno into %rcx
.macro .errno
call __errno_location
.endm
// Post-Initialization Read-Only (PIRO) BSS section.
// @param ss is an optional string, for control image locality
.macro .piro ss
.ifnb \ss
.section .piro.sort.bss.\ss,"aw",@nobits
.else
.section .piro.bss,"aw",@nobits
.endif
.endm
// Helpers for Cosmopolitan _init() amalgamation magic.
// @param name should be consistent across macros for a module
// @see libc/runtime/_init.S
.macro .initro number:req name:req
.section ".initro.\number\().\name","a",@progbits
.balign 8
.endm
.macro .initbss number:req name:req
.section ".piro.bss.init.2.\number\().\name","aw",@nobits
.balign 8
.endm
.macro .init.start number:req name:req
.section ".init.\number\().\name","ax",@progbits
"\name":
.endm
.macro .init.end number:req name:req bnd=globl vis
.endfn "\name",\bnd,\vis
.previous
.endm
// LOOP Instruction Replacement.
.macro .loop label:req
.byte 0x83
.byte 0xe9
.byte 0x01
jnz \label
.endm
// Pushes CONSTEXPR â [-128,127].
// @note assembler is wrong for non-literal constexprs
.macro pushb x:req
.byte 0x6a
.byte \x
.endm
// Sign-extends CONSTEXPR â [-128,127] to REGISTER.
// @cost â¥1 cycles, -2 bytes
.macro pushpop constexpr:req register:req
pushb \constexpr
pop \register
.endm
// Moves REGISTER to REGISTER.
// @cost â¥1 cycles, -1 REX byte
.macro movpp src:req dest:req
push \src
pop \dest
.endm
// Declares optional function.
.macro .optfn fn:req
.globl "\fn"
.weak "\fn"
.equ "\fn",_missingno
.type "\fn",@function
.endm
// Embeds fixed-width zero-filled string table.
// @note zero-padded â nul-terminated
.macro .fxstr width head rest:vararg
.ifnb \head
0: .ascii "\head"
.org 0b+\width
.fxstr \width,\rest
.endif
.endm
// Marks symbols as object en-masse.
// @note zero-padded â nul-terminated
.macro .object symbol rest:vararg
.ifnb \symbol
.type \symbol,@object
.object \rest
.endif
.endm
// Pads function prologue unconditionally for runtime hooking.
// @cost â¥0.3 cycles, 5 bytes
// @see .profilable
.macro .hookable
.byte 0x0f
.byte 0x1f
.byte 0x44
.byte 0x00
.byte 0x00
.endm
// Puts initialized data in uninitialized data section.
.macro .bsdata name:req expr:req bnd vis
.section ".initbss.300._init_\name","aw",@nobits
"\name":
.quad 0
.endobj "\name",\bnd,\vis
.previous
.section ".initro.300._init_\name","a",@progbits
.quad \expr
.previous
.section ".init.300._init_\name","ax",@progbits
"_init_\name":
movsq
.endfn "_init_\name"
.previous
.endm
// ICE Breakpoint.
// Modern gas forgot this but objdump knows
// @mode long,legacy,real
.macro icebp
.byte 0xF1
.endm
.macro int1
icebp
.endm
// Sets breakpoint for software debugger.
// @mode long,legacy,real
.macro .softicebp
.byte 0x53 # push bx
.byte 0x87 # xchg bx,bx (bochs breakpoint)
.byte 0xdb
.byte 0x5b # pop bx
.byte 0x66 # xchg ax,ax (microsoft breakpoint)
.byte 0x90
int3 # gdb breakpoint
.endm
// Assembles Intel Official 4-Byte NOP.
.macro fatnop4
.byte 0x0f,0x1f,0x40,0x00
.endm
// Calls Windows function.
//
// @param cx,dx,r8,r9,stack
// @return ax
// @clob ax,cx,dx,r8-r11
.macro ntcall symbol:req
sub $32,%rsp
call *\symbol(%rip)
add $32,%rsp
.endm
// Custom emulator instruction for bottom stack frame.
.macro bofram endfunc:req
.byte 0x0f,0x1f,0105,\endfunc-. # nopl disp8(%rbp)
.endm
// Good alignment for functions where alignment actually helps.
// @note 16-byte
.macro .alignfunc
#ifndef __OPTIMIZE_SIZE__
.p2align 4
#endif
.endm
// Good alignment for loops where alignment actually helps.
// @note 16-byte if <10 padding otherwise 8-byte
.macro .alignloop
#ifndef __OPTIMIZE_SIZE__
.p2align 4,,10
.p2align 4
#endif
.endm
// Loads Effective Address
// Supporting security blankets
.macro plea symbol:req reg64:req reg32:req
#if __PIC__ + __PIE__ + __code_model_medium__ + __code_model_large__ + 0 > 1
lea \symbol(%rip),\reg64
#else
mov $\symbol,\reg32
#endif
.endm
// Loads Effective Address to Stack
// Supporting security blankets
.macro pshaddr symbol:req
#if __PIC__ + __PIE__ + __code_model_medium__ + __code_model_large__ + 0 > 1
push $IMAGE_BASE_VIRTUAL+RVA(\symbol)(%rip),\reg64
#else
push $\symbol
#endif
.endm
// TODO(jart): delete
// Loads Effective Address
// Supporting security blankets
.macro ezlea symbol:req reg:req
#if __pic__ + __pie__ + __code_model_medium__ + __code_model_large__ + 0 > 1
// lea \symbol(%rip),%r\reg
mov $\symbol,%e\reg
#else
mov $\symbol,%e\reg
#endif
.endm
.macro farcall symbol:req
.type \symbol,@function
#if __PIC__ + __PIE__ + __code_model_medium__ + __code_model_large__ + 0 > 1
call *\symbol\()@gotpcrel(%rip)
#else
call \symbol\()@plt
#endif
.endm
// Inserts profiling hook in prologue if cc wants it.
//
// Cosmopolitan does this in a slightly different way from normal
// GNU toolchains. We always use the -mnop-mcount behavior, since
// the runtime is able to morph the binary at runtime. It is good
// since we can put hooks for profiling and function tracing into
// most builds, without any impact on performance.
//
// @cost â¥0.3 cycles, 5 bytes
// @see build/compile
.macro .profilable
#ifdef __PG__
1382:
#if defined(__MFENTRY__)
call __fentry__
#elif defined(__PIC__) || defined(__PIE__)
// nopw 0x00(%rax,%rax,1)
.byte 0x66,0x0f,0x1f,0x44,0x00,0x00
#else
// nopl 0x00(%rax,%rax,1)
.byte 0x0f,0x1f,0x44,0x00,0x00
#endif
#endif
.endm
// Pushes RVA on stack of linktime mergeable string literal.
// @see popstr
.macro pushstr text
.section .rodata.str1.1,"aSM",@progbits,1
.Lstr\@: .asciz "\text"
.endobj .Lstr\@
.previous
push $.Lstr\@ - IMAGE_BASE_VIRTUAL
.endm
// Pops off stack string address.
// @see pushstr
.macro popstr dest:req
addl $IMAGE_BASE_VIRTUAL,(%rsp)
pop \dest
.endm
// Loads address of linktime mergeable string literal into register.
.macro loadstr text:req reg:req regsz bias=0
.section .rodata.str1.1,"aSM",@progbits,1
.type .Lstr\@,@object
.Lstr\@: .asciz "\text"
.Lstr\@.size = .-.Lstr\@ - 1
.size .Lstr\@,.-.Lstr\@
.previous
ezlea .Lstr\@,\reg
.ifnb \regsz
#ifdef __OPTIMIZE_SIZE__
.if .Lstr\@.size + \bias < 128
pushpop .Lstr\@.size,%r\regsz
.else
mov $.Lstr\@.size,%e\regsz
.endif
#else
mov $.Lstr\@.size,%e\regsz
#endif
.endif
.endm
.macro .poison name:req kind:req
#ifdef __SANITIZE_ADDRESS__
2323: .quad 0
.init.start 304,"_init_\name\()_poison_\@"
push %rdi
push %rsi
ezlea 2323b,di
mov $8,%esi
mov $\kind,%edx
call __asan_poison
pop %rsi
pop %rdi
.init.end 304,"_init_\name\()_poison_\@"
#endif
.endm
.macro .underrun
#ifdef __SANITIZE_ADDRESS__
.poison __BASE_FILE__, -20 # kAsanGlobalUnderrun
#endif
.endm
.macro .overrun
#ifdef __SANITIZE_ADDRESS__
.poison __BASE_FILE__, -21 # kAsanGlobalOverrun
#endif
.endm
#else
.macro .underrun
.endm
.macro .overrun
.endm
// clang-format on
#endif /* __x86_64__ */
#endif /* __ASSEMBLER__ */
#endif /* COSMOPOLITAN_LIBC_MACROS_H_ */
| 13,325 | 579 | jart/cosmopolitan | false |
cosmopolitan/libc/mach.h | #ifndef COSMOPOLITAN_LIBC_MACH_H_
#define COSMOPOLITAN_LIBC_MACH_H_
/* ââââââ
âââââââââââ
âââââââââââââââ
ââââââââââââââââââââ
âââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââ
âââââââââââââââââââââââââââââââââââââââ
âââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââââââ
âââââ âââââââââââââââââââââââââââââââââââââââââââââ
ââââââ âââââââââââââââââââââââââââââââââââââââââââââ
ââââââââ âââââââââââââââââââââââââââââââââââââââââââââ
âââââââââ âââââââââââââââââââââââââââââââââââââââââââââ
âââââââââââ ââââââââââââââ ââââââââââââââââââââââââââââââ
ââââââââââââ ââââââââââââââââââââââââââââââââââââââââ â
âââââââââââââ âââââââââââââââââââââââââââââââââââ âââââ
âââââââââââââ ââââââââââââââââââââââââââââââ ââââââââ
âââââââââââââ ââââââââââââââââââââââââââ âââââââââââ
âââââââââââââ âââââââââââââââââââââ âââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § xnu's not unix! » carnegie mellon mach microkernel ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define XNU_SYSCALL_MASK_MACH 0x1000000
#define XNU_SYSCALL_MASK_UNIX 0x2000000
#define XNU_SYSCALL_MASK_MACH_IPC 0x5000000
#define kXnuCommonPage 0x00007fffffe00000
#define kXnuNtTscBase 0x050 /* uint64_t */
#define kXnuNtScale 0x058 /* uint32_t */
#define kXnuNtShift 0x05c /* uint32_t */
#define kXnuNtNsBase 0x060 /* uint64_t */
#define kXnuNtGeneration 0x068 /* uint32_t */
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
bool swtch(void);
bool swtch_pri(int);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_MACH_H_ */
| 4,563 | 50 | jart/cosmopolitan | false |
cosmopolitan/libc/libc.mk | #-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-â
#âââvi: set et ft=make ts=8 tw=8 fenc=utf-8 :viââââââââââââââââââââââââ
PKGS += LIBC
LIBC_HDRS = $(filter %.h,$(LIBC_FILES))
LIBC_INCS = $(filter %.inc,$(LIBC_FILES))
LIBC_FILES := $(wildcard libc/*) $(wildcard libc/isystem/*)
LIBC_CHECKS = $(LIBC_HDRS:%=o/$(MODE)/%.ok)
.PHONY: o/$(MODE)/libc
o/$(MODE)/libc: o/$(MODE)/libc/calls \
o/$(MODE)/libc/crt \
o/$(MODE)/libc/dns \
o/$(MODE)/libc/elf \
o/$(MODE)/libc/fmt \
o/$(MODE)/libc/intrin \
o/$(MODE)/libc/linux \
o/$(MODE)/libc/log \
o/$(MODE)/libc/mem \
o/$(MODE)/libc/nexgen32e \
o/$(MODE)/libc/nt \
o/$(MODE)/libc/runtime \
o/$(MODE)/libc/sock \
o/$(MODE)/libc/stdio \
o/$(MODE)/libc/str \
o/$(MODE)/libc/stubs \
o/$(MODE)/libc/sysv \
o/$(MODE)/libc/testlib \
o/$(MODE)/libc/thread \
o/$(MODE)/libc/time \
o/$(MODE)/libc/tinymath \
o/$(MODE)/libc/vga \
o/$(MODE)/libc/x \
o/$(MODE)/libc/zipos \
$(LIBC_CHECKS)
| 1,067 | 37 | jart/cosmopolitan | false |
cosmopolitan/libc/iso646.internal.h | #ifndef COSMOPOLITAN_LIBC_ISO646_H_
#define COSMOPOLITAN_LIBC_ISO646_H_
#ifndef __cplusplus
#define and &&
#define and_eq &=
#define bitand &
#define bitor |
#define compl ~
#define not !
#define not_eq !=
#define or ||
#define or_eq |=
#define xor ^
#define xor_eq ^=
#endif /* __cplusplus */
#endif /* COSMOPOLITAN_LIBC_ISO646_H_ */
| 337 | 19 | jart/cosmopolitan | false |
cosmopolitan/libc/macho.internal.h | #ifndef COSMOPOLITAN_LIBC_MACHO_H_
#define COSMOPOLITAN_LIBC_MACHO_H_
#ifndef __STRICT_ANSI__
/*
* xnu osfmk/mach/machine.h
*/
#define MAC_ARCH_MASK 0xff000000
#define MAC_ARCH_ABI64 0x01000000
#define MAC_ARCH_ABI64_32 0x02000000
#define MAC_CPU_MC680x0 6
#define MAC_CPU_X86 7
#define MAC_CPU_I386 MAC_CPU_X86
#define MAC_CPU_NEXGEN32E (MAC_CPU_X86 | MAC_ARCH_ABI64)
#define MAC_CPU_MC98000 10
#define MAC_CPU_HPPA 11
#define MAC_CPU_ARM 12
#define MAC_CPU_ARM64 (MAC_CPU_ARM | MAC_ARCH_ABI64)
#define MAC_CPU_ARM64_32 (MAC_CPU_ARM | MAC_ARCH_ABI64_32)
#define MAC_CPU_MC88000 13
#define MAC_CPU_SPARC 14
#define MAC_CPU_I860 15
#define MAC_CPU_POWERPC 18
#define MAC_CPU_POWERPC64 (MAC_CPU_POWERPC | MAC_ARCH_ABI64)
#define MAC_CPU_SUBTYPE_MASK 0xff000000
#define MAC_CPU_SUBTYPE_LIB64 0x80000000
#define MAC_CPU_SUBTYPE_PTRAUTH_ABI 0x80000000
#define MAC_CPU_SUBTYPE_MULTIPLE -1
#define MAC_CPU_SUBTYPE_LITTLE_ENDIAN 0
#define MAC_CPU_SUBTYPE_BIG_ENDIAN 1
#define MAC_OBJECT 0x1
#define MAC_EXECUTE 0x2
#define MAC_FVMLIB 0x3
#define MAC_CORE 0x4
#define MAC_PRELOAD 0x5
#define MAC_DYLIB 0x6
#define MAC_DYLINKER 0x7
#define MAC_BUNDLE 0x8
#define MAC_CPU_NEXGEN32E_ALL 3
#define MAC_CPU_ARM64_ALL 0
#define MAC_CPU_ARM64_V8 1
#define MAC_CPU_ARM64E 2
/*
* xnu osfmk/mach/i386/thread_status.h
*/
#define MAC_THREAD_NEXGEN32E 4 // x86_THREAD_STATE64
#define MAC_THREAD_NEXGEN32E_256BIT 17
/*
* xnu osfmk/mach/arm/thread_status.h
*
* struct arm_neon_saved_state64 {
* union {
* uint128_t q[32];
* uint64x2_t d[32];
* uint32x4_t s[32];
* } v;
* uint32_t fpsr;
* uint32_t fpcr;
* };
*/
#define MAC_THREAD_ARM_STATE64 6
#define ARM_NEON_SAVED_STATE64_COUNT 68
/*
* xnu EXTERNAL_HEADERS/mach-o/loader.h
*/
#define MAC_NOUNDEFS 0x1
#define MAC_INCRLINK 0x2
#define MAC_DYLDLINK 0x4
#define MAC_BINDATLOAD 0x8
#define MAC_PREBOUND 0x10
#define MAC_SPLIT_SEGS 0x20
#define MAC_LAZY_INIT 0x40
#define MAC_TWOLEVEL 0x80
#define MAC_FORCE_FLAT 0x100
#define MAC_NOMULTIDEFS 0x200
#define MAC_NOFIXPREBINDING 0x400
#define MAC_PREBINDABLE 0x800
#define MAC_ALLMODSBOUND 0x1000
#define MAC_SUBSECTIONS_VIA_SYMBOLS 0x2000
#define MAC_CANONICAL 0x4000
#define MAC_ALLOW_STACK_EXECUTION 0x20000
#define MAC_ROOT_SAFE 0x40000
#define MAC_SETUID_SAFE 0x80000
#define MAC_PIE 0x200000
#define MAC_HAS_TLV_DESCRIPTORS 0x800000
#define MAC_NO_HEAP_EXECUTION 0x1000000
#define MAC_SG_HIGHVM 0x1
#define MAC_SG_FVMLIB 0x2
#define MAC_SG_NORELOC 0x4
/* section type */
#define MAC_S_REGULAR 0x0
#define MAC_S_ZEROFILL 0x1
#define MAC_S_CSTRING_LITERALS 0x2
#define MAC_S_4BYTE_LITERALS 0x3
#define MAC_S_8BYTE_LITERALS 0x4
#define MAC_S_LITERAL_POINTERS 0x5
#define MAC_S_NON_LAZY_SYMBOL_POINTERS 0x6
#define MAC_S_LAZY_SYMBOL_POINTERS 0x7
#define MAC_S_SYMBOL_STUBS 0x8
#define MAC_S_MOD_INIT_FUNC_POINTERS 0x9
#define MAC_S_MOD_TERM_FUNC_POINTERS 0xa
#define MAC_S_COALESCED 0xb
#define MAC_S_GB_ZEROFILL 0xc
#define MAC_S_INTERPOSING 0xd
#define MAC_S_16BYTE_LITERALS 0xe
/* section attributes */
#define MAC_S_ATTRIBUTES_USR 0xff000000
#define MAC_S_ATTR_PURE_INSTRUCTIONS 0x80000000
#define MAC_S_ATTR_NO_TOC 0x40000000
#define MAC_S_ATTR_STRIP_STATIC_SYMS 0x20000000
#define MAC_S_ATTR_NO_DEAD_STRIP 0x10000000
#define MAC_S_ATTR_LIVE_SUPPORT 0x08000000
#define MAC_S_ATTR_SELF_MODIFYING_CODE 0x04000000
#define MAC_S_ATTR_DEBUG 0x02000000
#define MAC_S_ATTRIBUTES_SYS 0x00ffff00
#define MAC_S_ATTR_SOME_INSTRUCTIONS 0x00000400
#define MAC_S_ATTR_EXT_RELOC 0x00000200
#define MAC_S_ATTR_LOC_RELOC 0x00000100
#define MAC_LC_REQ_DYLD 0x80000000
#define MAC_LC_SEGMENT 0x1
#define MAC_LC_SYMTAB 0x2
#define MAC_LC_SYMSEG 0x3
#define MAC_LC_THREAD 0x4
#define MAC_LC_UNIXTHREAD 0x5
#define MAC_LC_LOADFVMLIB 0x6
#define MAC_LC_IDFVMLIB 0x7
#define MAC_LC_IDENT 0x8
#define MAC_LC_FVMFILE 0x9
#define MAC_LC_PREPAGE 0xa
#define MAC_LC_DYSYMTAB 0xb
#define MAC_LC_LOAD_DYLIB 0xc
#define MAC_LC_ID_DYLIB 0xd
#define MAC_LC_LOAD_DYLINKER 0xe
#define MAC_LC_ID_DYLINKER 0xf
#define MAC_LC_PREBOUND_DYLIB 0x10
#define MAC_LC_ROUTINES 0x11
#define MAC_LC_SUB_FRAMEWORK 0x12
#define MAC_LC_SUB_UMBRELLA 0x13
#define MAC_LC_SUB_CLIENT 0x14
#define MAC_LC_SUB_LIBRARY 0x15
#define MAC_LC_TWOLEVEL_HINTS 0x16
#define MAC_LC_PREBIND_CKSUM 0x17
#define MAC_LC_LOAD_WEAK_DYLIB (0x18 | MAC_LC_REQ_DYLD)
#define MAC_LC_SEGMENT_64 0x19
#define MAC_LC_ROUTINES_64 0x1a
#define MAC_LC_UUID 0x1b
#define MAC_LC_CODE_SIGNATURE 0x1d
#define MAC_LC_SEGMENT_SPLIT_INFO 0x1e
#define MAC_LC_LAZY_LOAD_DYLIB 0x20
#define MAC_LC_ENCRYPTION_INFO 0x21
#define MAC_LC_DYLD_INFO 0x22
#define MAC_LC_DYLD_INFO_ONLY (0x22 | MAC_LC_REQ_DYLD)
#define MAC_LC_VERSION_MIN_MACOSX 0x24
#define MAC_LC_VERSION_MIN_IPHONEOS 0x25
#define MAC_LC_FUNCTION_STARTS 0x26
#define MAC_LC_DYLD_ENVIRONMENT 0x27
#define MAC_LC_DATA_IN_CODE 0x29
#define MAC_LC_SOURCE_VERSION 0x2a
#define MAC_LC_DYLIB_CODE_SIGN_DRS 0x2B
#define MAC_LC_ENCRYPTION_INFO_64 0x2C
#define MAC_LC_LINKER_OPTION 0x2D
#define MAC_LC_LINKER_OPTIMIZATION_HINT 0x2E
#define MAC_LC_VERSION_MIN_TVOS 0x2F
#define MAC_LC_VERSION_MIN_WATCHOS 0x30
#define MAC_LC_NOTE 0x31
#define MAC_LC_BUILD_VERSION 0x32
#define MAC_LC_DYLD_EXPORTS_TRIE (0x33 | MAC_LC_REQ_DYLD)
#define MAC_LC_DYLD_CHAINED_FIXUPS (0x34 | MAC_LC_REQ_DYLD)
#define MAC_LC_FILESET_ENTRY (0x35 | MAC_LC_REQ_DYLD)
#define MAC_LC_RPATH (0x1c | MAC_LC_REQ_DYLD)
#define MAC_LC_MAIN (0x28 | MAC_LC_REQ_DYLD)
#define MAC_LC_REEXPORT_DYLIB (0x1f | MAC_LC_REQ_DYLD)
#define VM_PROT_NONE 0
#define VM_PROT_READ 1
#define VM_PROT_WRITE 2
#define VM_PROT_EXECUTE 4
#define VM_PROT_NO_CHANGE 8
#define VM_PROT_COPY 16
#define VM_PROT_TRUSTED 32
#define VM_PROT_STRIP_READ 64
#define MACHO_VERSION(x, y, z) ((x) << 16 | (y) << 8 | (z))
#if !(__ASSEMBLER__ + __LINKER__ + 0)
struct MachoHeader {
uint32_t magic;
uint32_t arch;
uint32_t arch2;
uint32_t filetype;
uint32_t loadcount;
uint32_t loadsize;
uint32_t flags;
uint32_t __reserved;
};
struct MachoLoadCommand {
uint32_t command;
uint32_t size;
};
struct MachoLoadSegment {
uint32_t command;
uint32_t size;
char name[16];
uint64_t vaddr;
uint64_t memsz;
uint64_t offset;
uint64_t filesz;
uint32_t maxprot;
uint32_t initprot;
uint32_t sectioncount;
uint32_t flags;
};
struct MachoSection {
char name[16];
char commandname[16];
uint64_t vaddr;
uint64_t memsz;
uint32_t offset;
uint32_t alignlog2;
uint32_t relotaboff;
uint32_t relocount;
uint32_t attr;
uint32_t __reserved[3];
};
struct MachoLoadSymtab {
uint32_t command;
uint32_t size;
uint32_t offset;
uint32_t count;
uint32_t stroff;
uint32_t strsize;
};
struct MachoLoadMinCommand {
uint32_t command;
uint32_t size;
uint32_t version; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
uint32_t sdk;
};
struct MachoLoadSourceVersionCommand {
uint32_t command;
uint32_t size;
uint64_t version; /* A.B.C.D.E packed as a24.b10.c10.d10.e10 */
};
struct MachoLoadEntrypointCommand {
uint32_t command;
uint32_t size;
uint64_t entryoff;
uint64_t stacksize;
};
struct MachoLoadThreadCommand {
uint32_t command;
uint32_t size;
uint32_t flavor;
uint32_t count;
uint32_t wut[];
};
struct MachoLoadUuid {
uint32_t command;
uint32_t size;
uint8_t uuid[16];
};
struct MachoDyldInfoCommand {
uint32_t cmd;
uint32_t cmdsize;
uint32_t rebase_off;
uint32_t rebase_size;
uint32_t bind_off;
uint32_t bind_size;
uint32_t weak_bind_off;
uint32_t weak_bind_size;
uint32_t lazy_bind_off;
uint32_t lazy_bind_size;
uint32_t export_off;
uint32_t export_size;
};
struct MachoDylib {
uint32_t name; /* (char *)&lc->command + name */
uint32_t timestamp;
uint32_t current_version; /* MACHO_VERSION(x,y,z) */
uint32_t compatibility_version; /* MACHO_VERSION(x,y,z) */
};
struct MachoDylibCommand {
uint32_t cmd;
uint32_t cmdsize;
struct MachoDylib dylib;
};
struct MachoEntryPointCommand {
uint32_t cmd; /* MAC_LC_MAIN */
uint32_t cmdsize; /* 24 */
uint64_t entryoff; /* __TEXT offset of _start() */
uint64_t stacksize; /* initial stack size [optional] */
};
struct MachoLinkeditDataCommand {
/* MAC_LC_CODE_SIGNATURE */
/* MAC_LC_SEGMENT_SPLIT_INFO */
/* MAC_LC_FUNCTION_STARTS */
/* MAC_LC_DATA_IN_CODE */
/* MAC_LC_DYLIB_CODE_SIGN_DRS */
/* MAC_LC_LINKER_OPTIMIZATION_HINT */
/* MAC_LC_DYLD_EXPORTS_TRIE */
/* MAC_LC_DYLD_CHAINED_FIXUPS */
uint32_t cmd;
uint32_t cmdsize;
uint32_t dataoff;
uint32_t datasize;
};
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* !ANSI */
#endif /* COSMOPOLITAN_LIBC_MACHO_H_ */
| 9,875 | 342 | jart/cosmopolitan | false |
cosmopolitan/libc/dce.h | #ifndef COSMOPOLITAN_LIBC_DCE_H_
#define COSMOPOLITAN_LIBC_DCE_H_
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § autotune » dead code elimination â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#ifndef SUPPORT_VECTOR
#ifdef __x86_64__
/**
* Supported Platforms Tuning Knob (Runtime & Compile-Time)
* Tuning this bitmask will remove platform polyfills at compile-time.
*/
#define SUPPORT_VECTOR 255
#else
#define SUPPORT_VECTOR (_HOSTLINUX | _HOSTXNU)
#endif
#endif
#define _HOSTLINUX 1
#define _HOSTMETAL 2
#define _HOSTWINDOWS 4
#define _HOSTXNU 8
#define _HOSTOPENBSD 16
#define _HOSTFREEBSD 32
#define _HOSTNETBSD 64
#ifdef NDEBUG
#define NoDebug() 1
#else
#define NoDebug() 0
#endif
#ifdef MODE_DBG
#define IsModeDbg() 1
#else
#define IsModeDbg() 0
#endif
#ifdef __MFENTRY__
#define HaveFentry() 1
#else
#define HaveFentry() 0
#endif
#ifdef TRUSTWORTHY
#define IsTrustworthy() 1
#else
#define IsTrustworthy() 0
#endif
#ifdef TINY
#define IsTiny() 1
#else
#define IsTiny() 0
#endif
#ifdef __OPTIMIZE__
#define IsOptimized() 1
#else
#define IsOptimized() 0
#endif
#ifdef __SANITIZE_ADDRESS__
#define IsAsan() 1
#else
#define IsAsan() 0
#endif
#ifdef __aarch64__
#define IsXnuSilicon() IsXnu()
#else
#define IsXnuSilicon() 0
#endif
#if defined(__PIE__) || defined(__PIC__)
#define IsPositionIndependent() 1
#else
#define IsPositionIndependent() 0
#endif
#define SupportsLinux() ((SUPPORT_VECTOR & _HOSTLINUX) == _HOSTLINUX)
#define SupportsMetal() ((SUPPORT_VECTOR & _HOSTMETAL) == _HOSTMETAL)
#define SupportsWindows() ((SUPPORT_VECTOR & _HOSTWINDOWS) == _HOSTWINDOWS)
#define SupportsXnu() ((SUPPORT_VECTOR & _HOSTXNU) == _HOSTXNU)
#define SupportsFreebsd() ((SUPPORT_VECTOR & _HOSTFREEBSD) == _HOSTFREEBSD)
#define SupportsOpenbsd() ((SUPPORT_VECTOR & _HOSTOPENBSD) == _HOSTOPENBSD)
#define SupportsNetbsd() ((SUPPORT_VECTOR & _HOSTNETBSD) == _HOSTNETBSD)
#define SupportsBsd() \
(!!(SUPPORT_VECTOR & (_HOSTXNU | _HOSTFREEBSD | _HOSTOPENBSD | _HOSTNETBSD)))
#define SupportsSystemv() \
(!!(SUPPORT_VECTOR & \
(_HOSTLINUX | _HOSTXNU | _HOSTOPENBSD | _HOSTFREEBSD | _HOSTNETBSD)))
#ifndef __ASSEMBLER__
#define IsLinux() (SupportsLinux() && (__hostos & _HOSTLINUX))
#define IsMetal() (SupportsMetal() && (__hostos & _HOSTMETAL))
#define IsWindows() (SupportsWindows() && (__hostos & _HOSTWINDOWS))
#define IsXnu() (SupportsXnu() && (__hostos & _HOSTXNU))
#define IsFreebsd() (SupportsFreebsd() && (__hostos & _HOSTFREEBSD))
#define IsOpenbsd() (SupportsOpenbsd() && (__hostos & _HOSTOPENBSD))
#define IsNetbsd() (SupportsNetbsd() && (__hostos & _HOSTNETBSD))
#define IsBsd() (IsXnu() || IsFreebsd() || IsOpenbsd() || IsNetbsd())
#else
/* clang-format off */
#define IsLinux() $_HOSTLINUX,__hostos(%rip)
#define IsMetal() $_HOSTMETAL,__hostos(%rip)
#define IsWindows() $_HOSTWINDOWS,__hostos(%rip)
#define IsBsd() $_HOSTXNU|_HOSTFREEBSD|_HOSTOPENBSD|_HOSTNETBSD,__hostos(%rip)
#define IsXnu() $_HOSTXNU,__hostos(%rip)
#define IsFreebsd() $_HOSTFREEBSD,__hostos(%rip)
#define IsOpenbsd() $_HOSTOPENBSD,__hostos(%rip)
#define IsNetbsd() $_HOSTNETBSD,__hostos(%rip)
/* clang-format on */
#endif
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern const int __hostos;
#ifdef __x86_64__
bool IsWsl1(void);
#else
#define IsWsl1() false
#endif
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_DCE_H_ */
| 3,855 | 130 | jart/cosmopolitan | false |
cosmopolitan/libc/notice.inc | .ident "\n\
Cosmopolitan\n\
Copyright 2020 Justine Alexandra Roberts Tunney\n\
\n\
Permission to use, copy, modify, and/or distribute this software for\n\
any purpose with or without fee is hereby granted, provided that the\n\
above copyright notice and this permission notice appear in all copies.\n\
\n\
THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL\n\
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED\n\
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE\n\
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL\n\
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\n\
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n\
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n\
PERFORMANCE OF THIS SOFTWARE.\
"
| 818 | 18 | jart/cosmopolitan | false |
cosmopolitan/libc/empty.s | 0 | 1 | jart/cosmopolitan | false |
|
cosmopolitan/libc/disclaimer.inc | 0 | 1 | jart/cosmopolitan | false |
|
cosmopolitan/libc/ar.h | #ifndef COSMOPOLITAN_LIBC_AR_H_
#define COSMOPOLITAN_LIBC_AR_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
#define ARMAG "!<arch>\n"
#define SARMAG 8
#define ARFMAG "`\n"
struct ar_hdr {
char ar_name[16];
char ar_date[12];
char ar_uid[6], ar_gid[6];
char ar_mode[8];
char ar_size[10];
char ar_fmag[2];
};
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_AR_H_ */
| 442 | 22 | jart/cosmopolitan | false |
cosmopolitan/libc/zip.h | #ifndef COSMOPOLITAN_LIBC_ZIP_H_
#define COSMOPOLITAN_LIBC_ZIP_H_
#include "libc/intrin/bits.h"
#include "libc/calls/struct/timespec.h"
#include "libc/macros.internal.h"
#include "libc/str/str.h"
/**
* @fileoverview PKZIP Data Structures.
*/
#define kZipAlign 2
#define kZipCosmopolitanVersion kZipEra2001
#define kZipOsDos 0
#define kZipOsAmiga 1
#define kZipOsOpenvms 2
#define kZipOsUnix 3
#define kZipOsVmcms 4
#define kZipOsAtarist 5
#define kZipOsOs2hpfs 6
#define kZipOsMacintosh 7
#define kZipOsZsystem 8
#define kZipOsCpm 9
#define kZipOsWindowsntfs 10
#define kZipOsMvsos390zos 11
#define kZipOsVse 12
#define kZipOsAcornrisc 13
#define kZipOsVfat 14
#define kZipOsAltmvs 15
#define kZipOsBeos 16
#define kZipOsTandem 17
#define kZipOsOs400 18
#define kZipOsOsxdarwin 19
#define kZipEra1989 10 /* PKZIP 1.0 */
#define kZipEra1993 20 /* PKZIP 2.0: deflate/subdir/etc. support */
#define kZipEra2001 45 /* PKZIP 4.5: kZipExtraZip64 support */
#define kZipIattrBinary 0 /* first bit not set */
#define kZipIattrText 1 /* first bit set */
#define kZipCompressionNone 0
#define kZipCompressionDeflate 8
#define kZipCdirHdrMagic 0x06054b50 /* PKâ£â "PK\5\6" */
#define kZipCdirHdrMinSize 22
#define kZipCdirAlign kZipAlign
#define kZipCdirHdrLinkableSize 294
#define kZipCdir64HdrMagic 0x06064b50 /* PKâ£â "PK\6\6" */
#define kZipCdir64HdrMinSize 56
#define kZipCdir64LocatorMagic 0x07064b50 /* PKâ ⢠"PK\6\7" */
#define kZipCdir64LocatorSize 20
#define kZipCfileHdrMagic 0x02014b50 /* PKâºâ» "PK\1\2" */
#define kZipCfileHdrMinSize 46
#define kZipCfileOffsetGeneralflag 8
#define kZipCfileOffsetCompressionmethod 10
#define kZipCfileOffsetLastmodifiedtime 12
#define kZipCfileOffsetLastmodifieddate 14
#define kZipCfileOffsetCrc32 16
#define kZipCfileOffsetCompressedsize 20
#define kZipCfileOffsetUncompressedsize 24
#define kZipCfileOffsetExternalattributes 38
#define kZipCfileOffsetOffset 42
#define kZipLfileHdrMagic 0x04034b50 /* PKâ¥â¦ "PK\3\4" */
#define kZipLfileHdrMinSize 30
#define kZipLfileOffsetGeneralflag 6
#define kZipLfileOffsetCompressionmethod 8
#define kZipLfileOffsetLastmodifiedtime 10
#define kZipLfileOffsetLastmodifieddate 12
#define kZipLfileOffsetCrc32 14
#define kZipLfileOffsetCompressedsize 18
#define kZipLfileOffsetUncompressedsize 22
#define kZipGflagUtf8 0x800
#define kZipExtraHdrSize 4
#define kZipExtraZip64 0x0001
#define kZipExtraNtfs 0x000a
#define kZipExtraUnix 0x000d
#define kZipExtraExtendedTimestamp 0x5455
#define kZipExtraInfoZipNewUnixExtra 0x7875
#define kZipCfileMagic "PK\001\002"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
/* end of central directory record */
#define ZIP_CDIR_MAGIC(P) READ32LE(P)
#define ZIP_CDIR_DISK(P) READ16LE((P) + 4)
#define ZIP_CDIR_STARTINGDISK(P) READ16LE((P) + 6)
#define ZIP_CDIR_RECORDSONDISK(P) READ16LE((P) + 8)
#define ZIP_CDIR_RECORDS(P) READ16LE((P) + 10)
#define ZIP_CDIR_SIZE(P) READ32LE((P) + 12)
#define ZIP_CDIR_OFFSET(P) READ32LE((P) + 16)
#define ZIP_CDIR_COMMENTSIZE(P) READ16LE((P) + 20)
#define ZIP_CDIR_COMMENT(P) ((P) + 22) /* recommend stopping at nul */
#define ZIP_CDIR_HDRSIZE(P) (ZIP_CDIR_COMMENTSIZE(P) + kZipCdirHdrMinSize)
/* zip64 end of central directory record */
#define ZIP_CDIR64_MAGIC(P) READ32LE(P)
#define ZIP_CDIR64_HDRSIZE(P) (READ64LE((P) + 4) + 12)
#define ZIP_CDIR64_VERSIONMADE(P) READ16LE((P) + 12)
#define ZIP_CDIR64_VERSIONNEED(P) READ16LE((P) + 14)
#define ZIP_CDIR64_DISK(P) READ32LE((P) + 16)
#define ZIP_CDIR64_STARTINGDISK(P) READ32LE((P) + 20)
#define ZIP_CDIR64_RECORDSONDISK(P) READ64LE((P) + 24)
#define ZIP_CDIR64_RECORDS(P) READ64LE((P) + 32)
#define ZIP_CDIR64_SIZE(P) READ64LE((P) + 40)
#define ZIP_CDIR64_OFFSET(P) READ64LE((P) + 48)
#define ZIP_CDIR64_COMMENTSIZE(P) \
(ZIP_CDIR64_HDRSIZE(P) >= 56 ? ZIP_CDIR64_HDRSIZE(P) - 56 : 0)
#define ZIP_CDIR64_COMMENT(P) ((P) + 56) /* recommend stopping at nul */
#define ZIP_LOCATE64_MAGIC(P) READ32LE(P)
#define ZIP_LOCATE64_STARTINGDISK(P) READ32LE((P) + 4)
#define ZIP_LOCATE64_OFFSET(P) READ64LE((P) + 8)
#define ZIP_LOCATE64_TOTALDISKS(P) READ32LE((P) + 12)
/* central directory file header */
#define ZIP_CFILE_MAGIC(P) READ32LE(P)
#define ZIP_CFILE_VERSIONMADE(P) (255 & (P)[4])
#define ZIP_CFILE_FILEATTRCOMPAT(P) (255 & (P)[5])
#define ZIP_CFILE_VERSIONNEED(P) (255 & (P)[6])
#define ZIP_CFILE_OSNEED(P) (255 & (P)[7])
#define ZIP_CFILE_GENERALFLAG(P) READ16LE((P) + kZipCfileOffsetGeneralflag)
#define ZIP_CFILE_COMPRESSIONMETHOD(P) \
READ16LE((P) + kZipCfileOffsetCompressionmethod)
#define ZIP_CFILE_LASTMODIFIEDTIME(P) \
READ16LE((P) + kZipCfileOffsetLastmodifiedtime) /* @see DOS_TIME() */
#define ZIP_CFILE_LASTMODIFIEDDATE(P) \
READ16LE((P) + kZipCfileOffsetLastmodifieddate) /* @see DOS_DATE() */
#define ZIP_CFILE_CRC32(P) READ32LE((P) + kZipCfileOffsetCrc32)
#define ZIP_CFILE_COMPRESSEDSIZE(P) READ32LE(P + kZipCfileOffsetCompressedsize)
#define ZIP_CFILE_UNCOMPRESSEDSIZE(P) \
READ32LE((P) + kZipCfileOffsetUncompressedsize)
#define ZIP_CFILE_NAMESIZE(P) READ16LE((P) + 28)
#define ZIP_CFILE_EXTRASIZE(P) READ16LE((P) + 30)
#define ZIP_CFILE_COMMENTSIZE(P) READ16LE((P) + 32)
#define ZIP_CFILE_DISK(P) READ16LE((P) + 34)
#define ZIP_CFILE_INTERNALATTRIBUTES(P) READ16LE((P) + 36)
#define ZIP_CFILE_EXTERNALATTRIBUTES(P) \
READ32LE((P) + kZipCfileOffsetExternalattributes)
#define ZIP_CFILE_OFFSET(P) READ32LE((P) + kZipCfileOffsetOffset)
#define ZIP_CFILE_NAME(P) ((const char *)((P) + 46)) /* not nul-terminated */
#define ZIP_CFILE_EXTRA(P) ((P) + 46 + ZIP_CFILE_NAMESIZE(P))
#define ZIP_CFILE_COMMENT(P) \
((const char *)((P) + 46 + ZIP_CFILE_NAMESIZE(P) + \
ZIP_CFILE_EXTRASIZE(P))) /* recommend stopping at nul */
#define ZIP_CFILE_HDRSIZE(P) \
(ZIP_CFILE_NAMESIZE(P) + ZIP_CFILE_EXTRASIZE(P) + ZIP_CFILE_COMMENTSIZE(P) + \
kZipCfileHdrMinSize)
/* local file header */
#define ZIP_LFILE_MAGIC(P) READ32LE(P)
#define ZIP_LFILE_VERSIONNEED(P) (255 & (P)[4])
#define ZIP_LFILE_OSNEED(P) (255 & (P)[5])
#define ZIP_LFILE_GENERALFLAG(P) READ16LE((P) + kZipLfileOffsetGeneralflag)
#define ZIP_LFILE_COMPRESSIONMETHOD(P) \
READ16LE((P) + kZipLfileOffsetCompressionmethod)
#define ZIP_LFILE_LASTMODIFIEDTIME(P) \
READ16LE((P) + kZipLfileOffsetLastmodifiedtime) /* @see DOS_TIME() */
#define ZIP_LFILE_LASTMODIFIEDDATE(P) \
READ16LE((P) + kZipLfileOffsetLastmodifieddate) /* @see DOS_DATE() */
#define ZIP_LFILE_CRC32(P) READ32LE((P) + kZipLfileOffsetCrc32)
#define ZIP_LFILE_COMPRESSEDSIZE(P) \
READ32LE((P) + kZipLfileOffsetCompressedsize)
#define ZIP_LFILE_UNCOMPRESSEDSIZE(P) \
READ32LE((P) + kZipLfileOffsetUncompressedsize)
#define ZIP_LFILE_NAMESIZE(P) READ16LE((P) + 26)
#define ZIP_LFILE_EXTRASIZE(P) READ16LE((P) + 28)
#define ZIP_LFILE_NAME(P) ((const char *)((P) + 30))
#define ZIP_LFILE_EXTRA(P) ((P) + 30 + ZIP_LFILE_NAMESIZE(P))
#define ZIP_LFILE_HDRSIZE(P) \
(ZIP_LFILE_NAMESIZE(P) + ZIP_LFILE_EXTRASIZE(P) + kZipLfileHdrMinSize)
#define ZIP_LFILE_CONTENT(P) ((P) + ZIP_LFILE_HDRSIZE(P))
#define ZIP_LFILE_SIZE(P) (ZIP_LFILE_HDRSIZE(P) + ZIP_LFILE_COMPRESSEDSIZE(P))
#define ZIP_EXTRA_HEADERID(P) READ16LE(P)
#define ZIP_EXTRA_CONTENTSIZE(P) READ16LE((P) + 2)
#define ZIP_EXTRA_CONTENT(P) ((P) + 4)
#define ZIP_EXTRA_SIZE(P) (ZIP_EXTRA_CONTENTSIZE(P) + kZipExtraHdrSize)
void *GetZipCdir(const uint8_t *, size_t);
uint8_t *FindEmbeddedApe(const uint8_t *, size_t);
bool IsZipCdir32(const uint8_t *, size_t, size_t);
bool IsZipCdir64(const uint8_t *, size_t, size_t);
int GetZipCfileMode(const uint8_t *);
uint64_t GetZipCdirOffset(const uint8_t *);
uint64_t GetZipCdirRecords(const uint8_t *);
void *GetZipCdirComment(const uint8_t *);
uint64_t GetZipCdirSize(const uint8_t *);
uint64_t GetZipCdirCommentSize(const uint8_t *);
uint64_t GetZipCfileUncompressedSize(const uint8_t *);
uint64_t GetZipCfileCompressedSize(const uint8_t *);
uint64_t GetZipCfileOffset(const uint8_t *);
uint64_t GetZipLfileUncompressedSize(const uint8_t *);
uint64_t GetZipLfileCompressedSize(const uint8_t *);
void GetZipCfileTimestamps(const uint8_t *, struct timespec *,
struct timespec *, struct timespec *, int);
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_ZIP_H_ */
| 8,838 | 207 | jart/cosmopolitan | false |
cosmopolitan/libc/math.h | #ifndef COSMOPOLITAN_LIBC_MATH_H_
#define COSMOPOLITAN_LIBC_MATH_H_
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § mathematics â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define M_E 2.7182818284590452354 /* ð */
#define M_LOG2_10 0xd.49a784bcd1b8afep-2 /* logâ10 â 3.3219280948873623478 */
#define M_LOG10_2 0x9.a209a84fbcff799p-5 /* logââ2 â 0.301029995663981195 */
#define M_LOG2E 0xb.8aa3b295c17f0bcp-3 /* logâð â 1.4426950408889634074 */
#define M_LOG10E 0.43429448190325182765 /* logââð */
#define M_LN2 0xb.17217f7d1cf79acp-4 /* logâ2 â */
#define M_LN10 2.30258509299404568402 /* logâ10 */
#define M_TAU 0x1.921fb54442d1846ap+2 /* Ï = 2Ï */
#define M_PI 0x1.921fb54442d1846ap+1 /* Ï â 3.14159265358979323846 */
#define M_PI_2 1.57079632679489661923 /* Ï/2 */
#define M_PI_4 0.78539816339744830962 /* Ï/4 */
#define M_1_PI 0.31830988618379067154 /* 1/Ï */
#define M_2_PI 0.63661977236758134308 /* 2/Ï */
#define M_2_SQRTPI 1.12837916709551257390 /* 2/sqrtÏ */
#define M_SQRT2 1.41421356237309504880 /* sqrt2 */
#define M_SQRT1_2 0.70710678118654752440 /* 1/sqrt2 */
#define DBL_DECIMAL_DIG __DBL_DECIMAL_DIG__
#define DBL_DIG __DBL_DIG__
#define DBL_EPSILON __DBL_EPSILON__
#define DBL_MANT_DIG __DBL_MANT_DIG__
#define DBL_MANT_DIG __DBL_MANT_DIG__
#define DBL_MAX __DBL_MAX__
#define DBL_MAX_10_EXP __DBL_MAX_10_EXP__
#define DBL_MAX_EXP __DBL_MAX_EXP__
#define DBL_MIN __DBL_MIN__ /* 2.23eâ308 â 1.79e308 */
#define DBL_MIN_10_EXP __DBL_MIN_10_EXP__
#define DBL_MIN_EXP __DBL_MIN_EXP__
#define DECIMAL_DIG __LDBL_DECIMAL_DIG__
#define FLT_DECIMAL_DIG __FLT_DECIMAL_DIG__
#define FLT_RADIX __FLT_RADIX__
#define FLT_DIG __FLT_DIG__
#define FLT_EPSILON __FLT_EPSILON__
#define FLT_MANT_DIG __FLT_MANT_DIG__
#define FLT_MANT_DIG __FLT_MANT_DIG__
#define FLT_MAX __FLT_MAX__
#define FLT_MAX_10_EXP __FLT_MAX_10_EXP__
#define FLT_MAX_EXP __FLT_MAX_EXP__
#define FLT_MIN __FLT_MIN__ /* 1.18eâ38 â 3.40e38 */
#define FLT_MIN_10_EXP __FLT_MIN_10_EXP__
#define FLT_MIN_EXP __FLT_MIN_EXP__
#define HLF_MAX 6.50e4f
#define HLF_MIN 3.10e-5f
#define LDBL_DECIMAL_DIG __LDBL_DECIMAL_DIG__
#define LDBL_DIG __LDBL_DIG__
#define LDBL_EPSILON __LDBL_EPSILON__
#define LDBL_MANT_DIG __LDBL_MANT_DIG__
#define LDBL_MANT_DIG __LDBL_MANT_DIG__
#define LDBL_MAX __LDBL_MAX__
#define LDBL_MAX_10_EXP __LDBL_MAX_10_EXP__
#define LDBL_MAX_EXP __LDBL_MAX_EXP__
#define LDBL_MIN __LDBL_MIN__ /* 3.37eâ4932 â 1.18e4932 */
#define LDBL_MIN_10_EXP __LDBL_MIN_10_EXP__
#define LDBL_MIN_EXP __LDBL_MIN_EXP__
#define FP_NAN 0
#define FP_INFINITE 1
#define FP_ZERO 2
#define FP_SUBNORMAL 3
#define FP_NORMAL 4
#define FP_ILOGB0 (-2147483647 - 1)
#define FP_ILOGBNAN (-2147483647 - 1)
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
#define NAN __builtin_nanf("")
#define INFINITY __builtin_inff()
#define HUGE_VAL __builtin_inf()
#define HUGE_VALF __builtin_inff()
#define HUGE_VALL __builtin_infl()
#if __FLT_EVAL_METHOD__ + 0 == 2
typedef long double float_t;
typedef long double double_t;
#else
typedef float float_t;
typedef double double_t;
#endif
#define isinf(x) __builtin_isinf(x)
#define isnan(x) __builtin_isnan(x)
#define isfinite(x) __builtin_isfinite(x)
#define isnormal(x) __builtin_isnormal(x)
#define isgreater(x, y) __builtin_isgreater(x, y)
#define isgreaterequal(x, y) __builtin_isgreaterequal(x, y)
#define isless(x, y) __builtin_isless(x, y)
#define islessequal(x, y) __builtin_islessequal(x, y)
#define islessgreater(x, y) __builtin_islessgreater(x, y)
#define isunordered(x, y) __builtin_isunordered(x, y)
#define fpclassify(x) \
__builtin_fpclassify(FP_NAN, FP_INFINITE, FP_NORMAL, FP_SUBNORMAL, FP_ZERO, x)
#define signbit(x) \
(sizeof(x) == sizeof(double) ? __builtin_signbit(x) \
: sizeof(x) == sizeof(float) ? __builtin_signbitf(x) \
: __builtin_signbitl(x))
extern int signgam;
double acos(double);
double acosh(double);
double asin(double);
double asinh(double);
double atan(double);
double atan2(double, double);
double atanh(double);
double cbrt(double);
double ceil(double);
double copysign(double, double);
double cos(double);
double cosh(double);
double drem(double, double);
double erf(double);
double erfc(double);
double exp(double);
double exp10(double);
double exp2(double);
double expm1(double);
double fabs(double);
double fdim(double, double);
double floor(double);
double fma(double, double, double);
double fmax(double, double);
double fmin(double, double);
double fmod(double, double);
double hypot(double, double);
double ldexp(double, int);
double log(double);
double log10(double);
double log1p(double);
double log2(double);
double logb(double);
double nearbyint(double);
double nextafter(double, double);
double nexttoward(double, long double);
double pow(double, double);
double pow10(double);
double powi(double, int);
double remainder(double, double);
double rint(double);
double round(double);
double scalb(double, double);
double scalbln(double, long int);
double scalbn(double, int);
double significand(double);
double sin(double);
double sinh(double);
double sqrt(double);
double tan(double);
double tanh(double);
double trunc(double);
double tgamma(double);
double lgamma(double);
double lgamma_r(double, int *);
int finite(double);
float acosf(float);
float acoshf(float);
float asinf(float);
float asinhf(float);
float atan2f(float, float);
float atanf(float);
float atanhf(float);
float cbrtf(float);
float ceilf(float);
float copysignf(float, float);
float cosf(float);
float coshf(float);
float dremf(float, float);
float erfcf(float);
float erff(float);
float exp10f(float);
float exp2f(float);
float expf(float);
float expm1f(float);
float fabsf(float);
float fdimf(float, float);
float floorf(float);
float fmaf(float, float, float);
float fmaxf(float, float);
float fminf(float, float);
float fmodf(float, float);
float hypotf(float, float);
float ldexpf(float, int);
float lgammaf(float);
float lgammaf_r(float, int *);
float log10f(float);
float log1pf(float);
float log2f(float);
float logbf(float);
float logf(float);
float nearbyintf(float);
float nextafterf(float, float);
float nexttowardf(float, long double);
float pow10f(float);
float powf(float, float);
float powif(float, int);
float remainderf(float, float);
float rintf(float);
float roundf(float);
float scalbf(float, float);
float scalblnf(float, long int);
float scalbnf(float, int);
float significandf(float);
float sinf(float);
float sinhf(float);
float sqrtf(float);
float tanf(float);
float tanhf(float);
float tgammaf(float);
float truncf(float);
int finitef(float);
int finitel(long double);
long double acoshl(long double);
long double acosl(long double);
long double asinhl(long double);
long double asinl(long double);
long double atan2l(long double, long double);
long double atanhl(long double);
long double atanl(long double);
long double cbrtl(long double);
long double ceill(long double);
long double copysignl(long double, long double);
long double coshl(long double);
long double cosl(long double);
long double dreml(long double, long double);
long double erfcl(long double);
long double erfl(long double);
long double exp10l(long double);
long double exp2l(long double);
long double expl(long double);
long double expm1l(long double);
long double fabsl(long double);
long double fdiml(long double, long double);
long double floorl(long double);
long double fmal(long double, long double, long double);
long double fmaxl(long double, long double);
long double fminl(long double, long double);
long double fmodl(long double, long double);
long double hypotl(long double, long double);
long double ldexpl(long double, int);
long double lgammal(long double);
long double lgammal_r(long double, int *);
long double log10l(long double);
long double log1pl(long double);
long double log2l(long double);
long double logbl(long double);
long double logl(long double);
long double nearbyintl(long double);
long double nextafterl(long double, long double);
long double nexttowardl(long double, long double);
long double pow10l(long double);
long double powl(long double, long double);
long double remainderl(long double, long double);
long double rintl(long double);
long double roundl(long double);
long double scalbl(long double, long double);
long double scalblnl(long double, long int);
long double scalbnl(long double, int);
long double significandl(long double);
long double sinhl(long double);
long double sinl(long double);
long double sqrtl(long double);
long double tanhl(long double);
long double tanl(long double);
long double tgammal(long double);
long double truncl(long double);
long lrint(double);
long lrintf(float);
long lrintl(long double);
long lround(double);
long lroundf(float);
long lroundl(long double);
int ilogbf(float);
int ilogb(double);
int ilogbl(long double);
long long llrint(double);
long long llrintf(float);
long long llrintl(long double);
long long llround(double);
long long llroundf(float);
long long llroundl(long double);
double frexp(double, int *);
double modf(double, double *);
double nan(const char *);
double remquo(double, double, int *);
float frexpf(float, int *);
float modff(float, float *);
float nanf(const char *);
float remquof(float, float, int *);
long double frexpl(long double, int *);
long double modfl(long double, long double *);
long double nanl(const char *);
long double remquol(long double, long double, int *);
void sincos(double, double *, double *);
void sincosf(float, float *, float *);
void sincosl(long double, long double *, long double *);
double fsumf(const float *, size_t);
double fsum(const double *, size_t);
double j0(double);
double j1(double);
double jn(int, double);
float j0f(float);
float j1f(float);
float jnf(int, float);
double y0(double);
double y1(double);
double yn(int, double);
float y0f(float);
float y1f(float);
float ynf(int, float);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_MATH_H_ */
| 10,814 | 332 | jart/cosmopolitan | false |
cosmopolitan/libc/literal.h | #ifndef COSMOPOLITAN_LIBC_LITERAL_H_
#define COSMOPOLITAN_LIBC_LITERAL_H_
#define __STDC_CONSTANT_MACROS
#ifdef __INT8_C
#define INT8_C(c) __INT8_C(c)
#define UINT8_C(c) __UINT8_C(c)
#define INT16_C(c) __INT16_C(c)
#define UINT16_C(c) __UINT16_C(c)
#define INT32_C(c) __INT32_C(c)
#define UINT32_C(c) __UINT32_C(c)
#define INT64_C(c) __INT64_C(c)
#define UINT64_C(c) __UINT64_C(c)
#else
#define INT8_C(c) c
#define UINT8_C(c) c
#define INT16_C(c) c
#define UINT16_C(c) c
#define INT32_C(c) c
#define UINT32_C(c) c##U
#define INT64_C(c) c##L
#define UINT64_C(c) c##UL
#endif
#if UINTPTR_MAX == UINT64_MAX
#define INTMAX_C(c) c##L
#define UINTMAX_C(c) c##UL
#else
#define INTMAX_C(c) c##LL
#define UINTMAX_C(c) c##ULL
#endif
#if __SIZEOF_INTMAX__ == 16
#define INT128_C(c) ((intmax_t)(c))
#define UINT128_C(c) ((uintmax_t)(c))
#elif __SIZEOF_INTMAX__ == 8
#define INT128_C(c) __INT64_C(c)
#define UINT128_C(c) __UINT64_C(c)
#endif
#endif /* COSMOPOLITAN_LIBC_LITERAL_H_ */
| 991 | 42 | jart/cosmopolitan | false |
cosmopolitan/libc/type2str.h | #ifndef COSMOPOLITAN_LIBC_TYPE2STR_H_
#define COSMOPOLITAN_LIBC_TYPE2STR_H_
#if __STDC_VERSION__ + 0 >= 201112
/* clang-format off */
#define _TYPE2STR(X) \
_Generic(X, \
_Bool: "_Bool", \
signed char: "signed char", \
unsigned char: "unsigned char", \
char: "char", \
short: "short", \
unsigned short: "unsigned short", \
int: "int", \
unsigned: "unsigned", \
long: "long", \
unsigned long: "unsigned long", \
long long: "long long", \
unsigned long long: "unsigned long long", \
float: "float", \
double: "double", \
long double: "long double")
#define _PRINTF_GENERIC(X, D, U) \
_Generic(X, \
_Bool: "hhh" U, \
signed char: "hh" D, \
unsigned char: "hh" U, \
char: "hh" D, \
short: "h" D, \
unsigned short: "h" U, \
int: D, \
unsigned: U, \
long: "l" D, \
unsigned long: "l" U, \
long long: "ll" D, \
unsigned long long: "ll" U, \
float: "f", \
double: "f", \
long double: "Lf")
/* clang-format on */
#endif /* C11 */
#endif /* COSMOPOLITAN_LIBC_TYPE2STR_H_ */
| 1,616 | 45 | jart/cosmopolitan | false |
cosmopolitan/libc/paths.h | #ifndef COSMOPOLITAN_LIBC_PATHS_H_
#define COSMOPOLITAN_LIBC_PATHS_H_
#define _PATH_DEFPATH "/usr/local/bin:/bin:/usr/bin"
#define _PATH_STDPATH "/bin:/usr/bin:/sbin:/usr/sbin"
#define _PATH_BSHELL "/bin/sh"
#define _PATH_CONSOLE "/dev/console"
#define _PATH_DEVNULL "/dev/null"
#define _PATH_KLOG "/proc/kmsg"
#define _PATH_LASTLOG "/var/log/lastlog"
#define _PATH_MAILDIR "/var/mail"
#define _PATH_MAN "/usr/share/man"
#define _PATH_MNTTAB "/etc/fstab"
#define _PATH_MOUNTED "/etc/mtab"
#define _PATH_NOLOGIN "/etc/nologin"
#define _PATH_SENDMAIL "/usr/sbin/sendmail"
#define _PATH_SHADOW "/etc/shadow"
#define _PATH_SHELLS "/etc/shells"
#define _PATH_TTY "/dev/tty"
#define _PATH_UTMP "/dev/null/utmp"
#define _PATH_VI "/usr/bin/vi"
#define _PATH_WTMP "/dev/null/wtmp"
#define _PATH_DEV "/dev/"
#define _PATH_TMP "/tmp/"
#define _PATH_VARDB "/var/lib/misc/"
#define _PATH_VARRUN "/var/run/"
#define _PATH_VARTMP "/var/tmp/"
#endif /* COSMOPOLITAN_LIBC_PATHS_H_ */
| 1,020 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/imag.internal.h | #ifndef COSMOPOLITAN_LIBC_IMAG_H_
#define COSMOPOLITAN_LIBC_IMAG_H_
#define I _Complex_I
#endif /* COSMOPOLITAN_LIBC_IMAG_H_ */
| 130 | 7 | jart/cosmopolitan | false |
cosmopolitan/libc/dos.h | #ifndef COSMOPOLITAN_LIBC_DOS_H_
#define COSMOPOLITAN_LIBC_DOS_H_
#define DOS_DATE(YEAR, MONTH_IDX1, DAY_IDX1) \
(((YEAR)-1980) << 9 | (MONTH_IDX1) << 5 | (DAY_IDX1))
#define DOS_TIME(HOUR, MINUTE, SECOND) \
((HOUR) << 11 | (MINUTE) << 5 | (SECOND) >> 1)
#endif /* COSMOPOLITAN_LIBC_DOS_H_ */
| 299 | 10 | jart/cosmopolitan | false |
cosmopolitan/libc/stdalign.internal.h | #ifndef COSMOPOLITAN_LIBC_STDALIGN_INTERNAL_H_
#define COSMOPOLITAN_LIBC_STDALIGN_INTERNAL_H_
#ifndef __cplusplus
#define alignas _Alignas
#define alignof _Alignof
#endif /* __cplusplus */
#define __alignas_is_defined 1
#define __alignof_is_defined 1
#endif /* COSMOPOLITAN_LIBC_STDALIGN_INTERNAL_H_ */
| 306 | 13 | jart/cosmopolitan | false |
cosmopolitan/libc/README.md | # Cosmopolitan Standard Library
This directory defines static archives defining functions, like
`printf()`, `mmap()`, win32, etc. Please note that the Cosmopolitan
build configuration doesn't link any C/C++ library dependencies
by default, so you still have the flexibility to choose the one
provided by your system. If you'd prefer Cosmopolitan, just add
`$(LIBC)` and `$(CRT)` to your linker arguments.
Your library is compromised of many bite-sized static archives.
We use the checkdeps tool to guarantee that the contents of the
archives are organized in a logical way that's easy to use with
or without our makefile infrastructure, since there's no cyclic
dependencies.
The Cosmopolitan Library exports only the most stable canonical
system calls for all supported operating systems, regardless of
which platform is used for compilation. We polyfill many of the
APIs, e.g. `read()`, `write()` so they work consistently everywhere
while other apis, e.g. `CreateWindowEx()`, might only work on one
platform, in which case they become no-op functions on others.
Cosmopolitan polyfill wrappers will usually use the dollar sign
naming convention, so they may be bypassed when necessary. This
same convention is used when multiple implementations of string
library and other performance-critical function are provided to
allow Cosmopolitan to go fast on both old and newer computers.
We take an approach to configuration that relies heavily on the
compiler's dead code elimination pass (`libc/dce.h`). Most of the
code is written so that, for example, folks not wanting support
for OpenBSD can flip a bit in `SUPPORT_VECTOR` and that code will
be omitted from the build. The same is true for builds that are
tuned using `-march=native` which effectively asks the library to
not include runtime support hooks for x86 processors older than
what you use.
Please note that, unlike Cygwin or MinGW, Cosmopolitan does not
achieve broad support by bolting on a POSIX emulation layer. We
do nothing more than (in most cases) stateless API translations
that get you 90% of the way there in a fast lightweight manner.
We therefore can't address some of the subtle differences, such
as the nuances of absolute paths on Windows. Our approach could
be compared to something more along the lines of, "the Russians
just used a pencil to write in space", versus spending millions
researching a pen like NASA.
| 2,398 | 47 | jart/cosmopolitan | false |
cosmopolitan/libc/notice.internal.h | #ifndef COSMOPOLITAN_LIBC_INTERNAL_NOTICE_H_
#define COSMOPOLITAN_LIBC_INTERNAL_NOTICE_H_
#ifndef __STRICT_ANSI__
#ifdef __ASSEMBLER__
.include "libc/notice.inc"
#else
asm(".include \"libc/notice.inc\"");
#endif
#endif /* !ANSI */
#endif /* COSMOPOLITAN_LIBC_INTERNAL_NOTICE_H_ */
| 283 | 13 | jart/cosmopolitan | false |
cosmopolitan/libc/atomic.h | #ifndef COSMOPOLITAN_LIBC_ATOMIC_H_
#define COSMOPOLITAN_LIBC_ATOMIC_H_
#define atomic_bool _Atomic(_Bool)
#define atomic_bool32 _Atomic(__INT32_TYPE__)
#define atomic_char _Atomic(char)
#define atomic_schar _Atomic(signed char)
#define atomic_uchar _Atomic(unsigned char)
#define atomic_short _Atomic(short)
#define atomic_ushort _Atomic(unsigned short)
#define atomic_int _Atomic(int)
#define atomic_uint _Atomic(unsigned int)
#define atomic_long _Atomic(long)
#define atomic_ulong _Atomic(unsigned long)
#define atomic_llong _Atomic(long long)
#define atomic_ullong _Atomic(unsigned long long)
#define atomic_char16_t _Atomic(__CHAR16_TYPE__)
#define atomic_char32_t _Atomic(__CHAR32_TYPE__)
#define atomic_wchar_t _Atomic(__WCHAR_TYPE__)
#define atomic_intptr_t _Atomic(__INTPTR_TYPE__)
#define atomic_uintptr_t _Atomic(__UINTPTR_TYPE__)
#define atomic_size_t _Atomic(__SIZE_TYPE__)
#define atomic_ptrdiff_t _Atomic(__PTRDIFF_TYPE__)
#define atomic_int_fast8_t _Atomic(__INT_FAST8_TYPE__)
#define atomic_uint_fast8_t _Atomic(__UINT_FAST8_TYPE__)
#define atomic_int_fast16_t _Atomic(__INT_FAST16_TYPE__)
#define atomic_uint_fast16_t _Atomic(__UINT_FAST16_TYPE__)
#define atomic_int_fast32_t _Atomic(__INT_FAST32_TYPE__)
#define atomic_uint_fast32_t _Atomic(__UINT_FAST32_TYPE__)
#define atomic_int_fast64_t _Atomic(__INT_FAST64_TYPE__)
#define atomic_uint_fast64_t _Atomic(__UINT_FAST64_TYPE__)
#define atomic_int_least8_t _Atomic(__INT_LEAST8_TYPE__)
#define atomic_uint_least8_t _Atomic(__UINT_LEAST8_TYPE__)
#define atomic_int_least16_t _Atomic(__INT_LEAST16_TYPE__)
#define atomic_uint_least16_t _Atomic(__UINT_LEAST16_TYPE__)
#define atomic_int_least32_t _Atomic(__INT_LEAST32_TYPE__)
#define atomic_uint_least32_t _Atomic(__UINT_LEAST32_TYPE__)
#define atomic_int_least64_t _Atomic(__INT_LEAST64_TYPE__)
#define atomic_uint_least64_t _Atomic(__UINT_LEAST64_TYPE__)
#ifdef __CLANG_ATOMIC_BOOL_LOCK_FREE
#define ATOMIC_BOOL_LOCK_FREE __CLANG_ATOMIC_BOOL_LOCK_FREE
#define ATOMIC_CHAR_LOCK_FREE __CLANG_ATOMIC_CHAR_LOCK_FREE
#define ATOMIC_CHAR16_T_LOCK_FREE __CLANG_ATOMIC_CHAR16_T_LOCK_FREE
#define ATOMIC_CHAR32_T_LOCK_FREE __CLANG_ATOMIC_CHAR32_T_LOCK_FREE
#define ATOMIC_WCHAR_T_LOCK_FREE __CLANG_ATOMIC_WCHAR_T_LOCK_FREE
#define ATOMIC_SHORT_LOCK_FREE __CLANG_ATOMIC_SHORT_LOCK_FREE
#define ATOMIC_INT_LOCK_FREE __CLANG_ATOMIC_INT_LOCK_FREE
#define ATOMIC_LONG_LOCK_FREE __CLANG_ATOMIC_LONG_LOCK_FREE
#define ATOMIC_LLONG_LOCK_FREE __CLANG_ATOMIC_LLONG_LOCK_FREE
#define ATOMIC_POINTER_LOCK_FREE __CLANG_ATOMIC_POINTER_LOCK_FREE
#else
#define ATOMIC_BOOL_LOCK_FREE __GCC_ATOMIC_BOOL_LOCK_FREE
#define ATOMIC_CHAR_LOCK_FREE __GCC_ATOMIC_CHAR_LOCK_FREE
#define ATOMIC_CHAR16_T_LOCK_FREE __GCC_ATOMIC_CHAR16_T_LOCK_FREE
#define ATOMIC_CHAR32_T_LOCK_FREE __GCC_ATOMIC_CHAR32_T_LOCK_FREE
#define ATOMIC_WCHAR_T_LOCK_FREE __GCC_ATOMIC_WCHAR_T_LOCK_FREE
#define ATOMIC_SHORT_LOCK_FREE __GCC_ATOMIC_SHORT_LOCK_FREE
#define ATOMIC_INT_LOCK_FREE __GCC_ATOMIC_INT_LOCK_FREE
#define ATOMIC_LONG_LOCK_FREE __GCC_ATOMIC_LONG_LOCK_FREE
#define ATOMIC_LLONG_LOCK_FREE __GCC_ATOMIC_LLONG_LOCK_FREE
#define ATOMIC_POINTER_LOCK_FREE __GCC_ATOMIC_POINTER_LOCK_FREE
#endif
#endif /* COSMOPOLITAN_LIBC_ATOMIC_H_ */
| 3,441 | 66 | jart/cosmopolitan | false |
cosmopolitan/libc/errno.h | #ifndef COSMOPOLITAN_LIBC_ERRNO_H_
#define COSMOPOLITAN_LIBC_ERRNO_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
/**
* @fileoverview System error codes.
* @see libc/sysv/consts.sh for numbers
*/
#if defined(__GNUC__) && defined(__x86_64__) && defined(__MNO_RED_ZONE__) && \
!defined(__STRICT_ANSI__)
#define errno \
(*({ \
errno_t *_ep; \
asm("call\t__errno_location" : "=a"(_ep) : /* no inputs */ : "cc"); \
_ep; \
}))
#else
#define errno (*__errno_location())
#endif
/**
* System call unavailable.
* @note kNtErrorInvalidFunction on NT
*/
extern const errno_t ENOSYS;
/**
* Operation not permitted.
* @note kNtErrorInvalidAccess on NT
*/
extern const errno_t EPERM;
/**
* No such file or directory.
*/
extern const errno_t ENOENT;
/**
* No such process.
*/
extern const errno_t ESRCH;
/**
* The greatest of all errnos.
*/
extern const errno_t EINTR;
/**
* Unix consensus.
*/
extern const errno_t EIO;
/**
* No such device or address.
*/
extern const errno_t ENXIO;
/**
* Argument list too errno_t.
*/
extern const errno_t E2BIG;
/**
* Exec format error.
*/
extern const errno_t ENOEXEC;
/**
* Bad file descriptor.
*/
extern const errno_t EBADF;
/**
* No child process.
*/
extern const errno_t ECHILD;
/**
* Resource temporarily unavailable (e.g. SO_RCVTIMEO expired, too many
* processes, too much memory locked, read or write with O_NONBLOCK needs
* polling, etc.).
*/
extern const errno_t EAGAIN;
/**
* We require more vespene gas.
*/
extern const errno_t ENOMEM;
/**
* Permission denied.
*/
extern const errno_t EACCES;
/**
* Pointer passed to system call that would otherwise segfault.
*/
extern const errno_t EFAULT;
/**
* Block device required.
*/
extern const errno_t ENOTBLK;
/**
* Device or resource busy.
*/
extern const errno_t EBUSY;
/**
* File exists.
*/
extern const errno_t EEXIST;
/**
* Improper link.
*/
extern const errno_t EXDEV;
/**
* No such device.
*/
extern const errno_t ENODEV;
/**
* Not a directory.
*/
extern const errno_t ENOTDIR;
/**
* Is a a directory.
*/
extern const errno_t EISDIR;
/**
* Invalid argument.
*/
extern const errno_t EINVAL;
/**
* Too many open files in system.
*/
extern const errno_t ENFILE;
/**
* Too many open files.
*/
extern const errno_t EMFILE;
/**
* Inappropriate i/o control operation.
*/
extern const errno_t ENOTTY;
/**
* Won't open executable that's executing in write mode.
*/
extern const errno_t ETXTBSY;
/**
* File too large.
*/
extern const errno_t EFBIG;
/**
* No space left on device.
*/
extern const errno_t ENOSPC;
/**
* Disk quota exceeded.
*/
extern const errno_t EDQUOT;
/**
* Invalid seek.
*/
extern const errno_t ESPIPE;
/**
* Read-only filesystem.
*/
extern const errno_t EROFS;
/**
* Too many links.
*/
extern const errno_t EMLINK;
/**
* Broken pipe.
*/
extern const errno_t EPIPE;
/**
* Mathematics argument out of domain of function.
*/
extern const errno_t EDOM;
/**
* Result too large.
*/
extern const errno_t ERANGE;
/**
* Resource deadlock avoided.
*/
extern const errno_t EDEADLK;
/**
* Filename too errno_t.
*/
extern const errno_t ENAMETOOLONG;
/**
* No locks available.
*/
extern const errno_t ENOLCK;
/**
* Directory not empty.
*/
extern const errno_t ENOTEMPTY;
/**
* Too many levels of symbolic links.
*/
extern const errno_t ELOOP;
/**
* No message error.
*/
extern const errno_t ENOMSG;
/**
* Identifier removed.
*/
extern const errno_t EIDRM;
/**
* Timer expired.
*/
extern const errno_t ETIME;
/**
* Protocol error.
*/
extern const errno_t EPROTO;
/**
* Overflow error.
*/
extern const errno_t EOVERFLOW;
/**
* Unicode decoding error.
*/
extern const errno_t EILSEQ;
/**
* Too many users.
*/
extern const errno_t EUSERS;
/**
* Not a socket.
*/
extern const errno_t ENOTSOCK;
/**
* Destination address required.
*/
extern const errno_t EDESTADDRREQ;
/**
* Message too errno_t.
*/
extern const errno_t EMSGSIZE;
/**
* Protocol wrong type for socket.
*/
extern const errno_t EPROTOTYPE;
/**
* Protocol not available.
*/
extern const errno_t ENOPROTOOPT;
/**
* Protocol not supported.
*/
extern const errno_t EPROTONOSUPPORT;
/**
* Socket type not supported.
*/
extern const errno_t ESOCKTNOSUPPORT;
/**
* Operation not supported.
*/
extern const errno_t ENOTSUP;
/**
* Socket operation not supported.
*/
extern const errno_t EOPNOTSUPP;
/**
* Protocol family not supported.
*/
extern const errno_t EPFNOSUPPORT;
/**
* Address family not supported.
*/
extern const errno_t EAFNOSUPPORT;
/**
* Address already in use.
*/
extern const errno_t EADDRINUSE;
/**
* Address not available.
*/
extern const errno_t EADDRNOTAVAIL;
/**
* Network is down.
*/
extern const errno_t ENETDOWN;
/**
* Host is unreachable.
*/
extern const errno_t ENETUNREACH;
/**
* Connection reset by network.
*/
extern const errno_t ENETRESET;
/**
* Connection reset before accept.
*/
extern const errno_t ECONNABORTED;
/**
* Connection reset by client.
*/
extern const errno_t ECONNRESET;
/**
* No buffer space available.
*/
extern const errno_t ENOBUFS;
/**
* Socket is connected.
*/
extern const errno_t EISCONN;
/**
* Socket is not connected.
*/
extern const errno_t ENOTCONN;
/**
* Cannot send after transport endpoint shutdown.
*/
extern const errno_t ESHUTDOWN;
/**
* Too many references: cannot splice.
*/
extern const errno_t ETOOMANYREFS;
/**
* Connection timed out.
*/
extern const errno_t ETIMEDOUT;
/**
* Connection refused error.
*/
extern const errno_t ECONNREFUSED;
/**
* Host down error.
*/
extern const errno_t EHOSTDOWN;
/**
* Host unreachable error.
*/
extern const errno_t EHOSTUNREACH;
/**
* Connection already in progress.
*/
extern const errno_t EALREADY;
/**
* Operation already in progress.
*/
extern const errno_t EINPROGRESS;
/**
* Stale error.
*/
extern const errno_t ESTALE;
/**
* Remote error.
*/
extern const errno_t EREMOTE;
/**
* Bad message.
*/
extern const errno_t EBADMSG;
/**
* Operation canceled.
*/
extern const errno_t ECANCELED;
/**
* Owner died.
*/
extern const errno_t EOWNERDEAD;
/**
* State not recoverable.
*/
extern const errno_t ENOTRECOVERABLE;
/**
* No network.
*/
extern const errno_t ENONET;
/**
* Please restart syscall.
*/
extern const errno_t ERESTART;
/**
* Out of streams resources.
*/
extern const errno_t ENOSR;
/**
* No string.
*/
extern const errno_t ENOSTR;
/**
* No data.
*/
extern const errno_t ENODATA;
/**
* Multihop attempted.
*/
extern const errno_t EMULTIHOP;
/**
* Link severed.
*/
extern const errno_t ENOLINK;
/**
* No medium found.
*/
extern const errno_t ENOMEDIUM;
/**
* Wrong medium type.
*/
extern const errno_t EMEDIUMTYPE;
/**
* Inappropriate file type or format. (BSD only)
*/
extern const errno_t EFTYPE;
extern const errno_t EAUTH;
extern const errno_t EBADARCH;
extern const errno_t EBADEXEC;
extern const errno_t EBADMACHO;
extern const errno_t EBADRPC;
extern const errno_t EDEVERR;
extern const errno_t ENEEDAUTH;
extern const errno_t ENOATTR;
extern const errno_t ENOPOLICY;
extern const errno_t EPROCLIM;
extern const errno_t EPROCUNAVAIL;
extern const errno_t EPROGMISMATCH;
extern const errno_t EPROGUNAVAIL;
extern const errno_t EPWROFF;
extern const errno_t ERPCMISMATCH;
extern const errno_t ESHLIBVERS;
extern const errno_t EADV;
extern const errno_t EBADE;
extern const errno_t EBADFD;
extern const errno_t EBADR;
extern const errno_t EBADRQC;
extern const errno_t EBADSLT;
extern const errno_t ECHRNG;
extern const errno_t ECOMM;
extern const errno_t EDOTDOT;
extern const errno_t EHWPOISON;
extern const errno_t EISNAM;
extern const errno_t EKEYEXPIRED;
extern const errno_t EKEYREJECTED;
extern const errno_t EKEYREVOKED;
extern const errno_t EL2HLT;
extern const errno_t EL2NSYNC;
extern const errno_t EL3HLT;
extern const errno_t EL3RST;
extern const errno_t ELIBACC;
extern const errno_t ELIBBAD;
extern const errno_t ELIBEXEC;
extern const errno_t ELIBMAX;
extern const errno_t ELIBSCN;
extern const errno_t ELNRNG;
extern const errno_t ENAVAIL;
extern const errno_t ENOANO;
extern const errno_t ENOCSI;
extern const errno_t ENOKEY;
extern const errno_t ENOPKG;
extern const errno_t ENOTNAM;
extern const errno_t ENOTUNIQ;
extern const errno_t EREMCHG;
extern const errno_t EREMOTEIO;
extern const errno_t ERFKILL;
extern const errno_t ESRMNT;
extern const errno_t ESTRPIPE;
extern const errno_t EUCLEAN;
extern const errno_t EUNATCH;
extern const errno_t EXFULL;
#define E2BIG E2BIG
#define EACCES EACCES
#define EADDRINUSE EADDRINUSE
#define EADDRNOTAVAIL EADDRNOTAVAIL
#define EADV EADV
#define EAFNOSUPPORT EAFNOSUPPORT
#define EAGAIN EAGAIN
#define EALREADY EALREADY
#define EAUTH EAUTH
#define EBADARCH EBADARCH
#define EBADE EBADE
#define EBADEXEC EBADEXEC
#define EBADF EBADF
#define EBADFD EBADFD
#define EBADMACHO EBADMACHO
#define EBADMSG EBADMSG
#define EBADR EBADR
#define EBADRPC EBADRPC
#define EBADRQC EBADRQC
#define EBADSLT EBADSLT
#define EBUSY EBUSY
#define ECANCELED ECANCELED
#define ECHILD ECHILD
#define ECHRNG ECHRNG
#define ECOMM ECOMM
#define ECONNABORTED ECONNABORTED
#define ECONNREFUSED ECONNREFUSED
#define ECONNRESET ECONNRESET
#define EDEADLK EDEADLK
#define EDESTADDRREQ EDESTADDRREQ
#define EDEVERR EDEVERR
#define EDOM EDOM
#define EDOTDOT EDOTDOT
#define EDQUOT EDQUOT
#define EEXIST EEXIST
#define EFAULT EFAULT
#define EFBIG EFBIG
#define EFTYPE EFTYPE
#define EHOSTDOWN EHOSTDOWN
#define EHOSTUNREACH EHOSTUNREACH
#define EHWPOISON EHWPOISON
#define EIDRM EIDRM
#define EILSEQ EILSEQ
#define EINPROGRESS EINPROGRESS
#define EINTR EINTR
#define EINVAL EINVAL
#define EIO EIO
#define EISCONN EISCONN
#define EISDIR EISDIR
#define EISNAM EISNAM
#define EKEYEXPIRED EKEYEXPIRED
#define EKEYREJECTED EKEYREJECTED
#define EKEYREVOKED EKEYREVOKED
#define EL2HLT EL2HLT
#define EL2NSYNC EL2NSYNC
#define EL3HLT EL3HLT
#define EL3RST EL3RST
#define ELIBACC ELIBACC
#define ELIBBAD ELIBBAD
#define ELIBEXEC ELIBEXEC
#define ELIBMAX ELIBMAX
#define ELIBSCN ELIBSCN
#define ELNRNG ELNRNG
#define ELOOP ELOOP
#define EMEDIUMTYPE EMEDIUMTYPE
#define EMFILE EMFILE
#define EMLINK EMLINK
#define EMSGSIZE EMSGSIZE
#define EMULTIHOP EMULTIHOP
#define ENAMETOOLONG ENAMETOOLONG
#define ENAVAIL ENAVAIL
#define ENEEDAUTH ENEEDAUTH
#define ENETDOWN ENETDOWN
#define ENETRESET ENETRESET
#define ENETUNREACH ENETUNREACH
#define ENFILE ENFILE
#define ENOANO ENOANO
#define ENOATTR ENOATTR
#define ENOBUFS ENOBUFS
#define ENOCSI ENOCSI
#define ENODATA ENODATA
#define ENODEV ENODEV
#define ENOENT ENOENT
#define ENOEXEC ENOEXEC
#define ENOKEY ENOKEY
#define ENOLCK ENOLCK
#define ENOLINK ENOLINK
#define ENOMEDIUM ENOMEDIUM
#define ENOMEM ENOMEM
#define ENOMSG ENOMSG
#define ENONET ENONET
#define ENOPKG ENOPKG
#define ENOPOLICY ENOPOLICY
#define ENOPROTOOPT ENOPROTOOPT
#define ENOSPC ENOSPC
#define ENOSR ENOSR
#define ENOSTR ENOSTR
#define ENOSYS ENOSYS
#define ENOTBLK ENOTBLK
#define ENOTCONN ENOTCONN
#define ENOTDIR ENOTDIR
#define ENOTEMPTY ENOTEMPTY
#define ENOTNAM ENOTNAM
#define ENOTRECOVERABLE ENOTRECOVERABLE
#define ENOTSOCK ENOTSOCK
#define ENOTSUP ENOTSUP
#define ENOTTY ENOTTY
#define ENOTUNIQ ENOTUNIQ
#define ENXIO ENXIO
#define EOPNOTSUPP EOPNOTSUPP
#define EOVERFLOW EOVERFLOW
#define EOWNERDEAD EOWNERDEAD
#define EPERM EPERM
#define EPFNOSUPPORT EPFNOSUPPORT
#define EPIPE EPIPE
#define EPROCLIM EPROCLIM
#define EPROCUNAVAIL EPROCUNAVAIL
#define EPROGMISMATCH EPROGMISMATCH
#define EPROGUNAVAIL EPROGUNAVAIL
#define EPROTO EPROTO
#define EPROTONOSUPPORT EPROTONOSUPPORT
#define EPROTOTYPE EPROTOTYPE
#define EPWROFF EPWROFF
#define ERANGE ERANGE
#define EREMCHG EREMCHG
#define EREMOTE EREMOTE
#define EREMOTEIO EREMOTEIO
#define ERESTART ERESTART
#define ERFKILL ERFKILL
#define EROFS EROFS
#define ERPCMISMATCH ERPCMISMATCH
#define ESHLIBVERS ESHLIBVERS
#define ESHUTDOWN ESHUTDOWN
#define ESOCKTNOSUPPORT ESOCKTNOSUPPORT
#define ESPIPE ESPIPE
#define ESRCH ESRCH
#define ESRMNT ESRMNT
#define ESTALE ESTALE
#define ESTRPIPE ESTRPIPE
#define ETIME ETIME
#define ETIMEDOUT ETIMEDOUT
#define ETOOMANYREFS ETOOMANYREFS
#define ETXTBSY ETXTBSY
#define EUCLEAN EUCLEAN
#define EUNATCH EUNATCH
#define EUSERS EUSERS
#define EWOULDBLOCK EAGAIN
#define EXDEV EXDEV
#define EXFULL EXFULL
extern errno_t __errno;
errno_t *__errno_location(void);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_ERRNO_H_ */
| 13,816 | 705 | jart/cosmopolitan | false |
cosmopolitan/libc/inttypes.h | #ifndef COSMOPOLITAN_LIBC_INTTYPES_H_
#define COSMOPOLITAN_LIBC_INTTYPES_H_
typedef __INT_LEAST8_TYPE__ int_least8_t;
typedef __UINT_LEAST8_TYPE__ uint_least8_t;
typedef __INT_LEAST16_TYPE__ int_least16_t;
typedef __UINT_LEAST16_TYPE__ uint_least16_t;
typedef __INT_LEAST32_TYPE__ int_least32_t;
typedef __UINT_LEAST32_TYPE__ uint_least32_t;
typedef __INT_LEAST64_TYPE__ int_least64_t;
typedef __UINT_LEAST64_TYPE__ uint_least64_t;
typedef __INT_FAST8_TYPE__ int_fast8_t;
typedef __UINT_FAST8_TYPE__ uint_fast8_t;
typedef __INT_FAST16_TYPE__ int_fast16_t;
typedef __UINT_FAST16_TYPE__ uint_fast16_t;
typedef __INT_FAST32_TYPE__ int_fast32_t;
typedef __UINT_FAST32_TYPE__ uint_fast32_t;
typedef __INT_FAST64_TYPE__ int_fast64_t;
typedef __UINT_FAST64_TYPE__ uint_fast64_t;
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define __PRI8 "hh"
#if __SIZEOF_INT__ == 2
#define __PRI16 ""
#elif __SIZEOF_SHORT__ == 2
#define __PRI16 "h"
#elif __SIZEOF_LONG__ == 2
#define __PRI16 "l"
#endif
#if __SIZEOF_INT__ == 4
#define __PRI32 ""
#elif __SIZEOF_LONG__ == 4
#define __PRI32 "l"
#elif __SIZEOF_LONG_LONG__ == 4
#define __PRI32 "ll"
#endif
#if __SIZEOF_INT__ == 8
#define __PRI64 ""
#elif __SIZEOF_LONG__ == 8
#define __PRI64 "l"
#elif __SIZEOF_LONG_LONG__ == 8
#define __PRI64 "ll"
#endif
#if __SIZEOF_INT__ == 16
#define __PRI128 ""
#elif __SIZEOF_LONG__ == 16
#define __PRI128 "l"
#elif __SIZEOF_LONG_LONG__ == 16
#define __PRI128 "ll"
#elif __SIZEOF_INTMAX__ == 16
#define __PRI128 "j"
#else
#define __PRI128 "jj"
#endif
#if __SIZEOF_POINTER__ == __SIZEOF_INT__
#define __PRIPTR ""
#elif __SIZEOF_POINTER__ == __SIZEOF_LONG__
#define __PRIPTR "l"
#elif __SIZEOF_POINTER__ == __SIZEOF_LONG_LONG__
#define __PRIPTR "ll"
#endif
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation » printf » decimal ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PRId8 __PRI8 "d"
#define PRId16 __PRI16 "d"
#define PRId32 __PRI32 "d"
#define PRId64 __PRI64 "d"
#define PRId128 __PRI128 "d"
#define PRIdLEAST8 __PRI8 "d"
#define PRIdLEAST16 __PRI16 "d"
#define PRIdLEAST32 __PRI32 "d"
#define PRIdLEAST64 __PRI64 "d"
#define PRIdLEAST128 __PRI128 "d"
#define PRIdFAST8 __PRI8 "d"
#define PRIdFAST16 __PRI32 "d"
#define PRIdFAST32 __PRI32 "d"
#define PRIdFAST64 __PRI64 "d"
#define PRIdFAST128 __PRI128 "d"
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation » printf » unsigned decimal ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PRIu8 __PRI8 "u"
#define PRIu16 __PRI16 "u"
#define PRIu32 __PRI32 "u"
#define PRIu64 __PRI64 "u"
#define PRIu128 __PRI128 "u"
#define PRIuLEAST8 __PRI8 "u"
#define PRIuLEAST16 __PRI16 "u"
#define PRIuLEAST32 __PRI32 "u"
#define PRIuLEAST64 __PRI64 "u"
#define PRIuLEAST128 __PRI128 "u"
#define PRIuFAST8 __PRI8 "u"
#define PRIuFAST16 __PRI32 "u"
#define PRIuFAST32 __PRI32 "u"
#define PRIuFAST64 __PRI64 "u"
#define PRIuFAST128 __PRI128 "u"
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation » printf » wut ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PRIi8 __PRI8 "i"
#define PRIi16 __PRI16 "i"
#define PRIi32 __PRI32 "i"
#define PRIi64 __PRI64 "i"
#define PRIi128 __PRI128 "i"
#define PRIiLEAST8 __PRI8 "i"
#define PRIiLEAST16 __PRI16 "i"
#define PRIiLEAST32 __PRI32 "i"
#define PRIiLEAST64 __PRI64 "i"
#define PRIiLEAST128 __PRI128 "i"
#define PRIiFAST8 __PRI8 "i"
#define PRIiFAST16 __PRI32 "i"
#define PRIiFAST32 __PRI32 "i"
#define PRIiFAST64 __PRI64 "i"
#define PRIiFAST128 __PRI128 "i"
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation » printf » octal ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PRIo8 __PRI8 "o"
#define PRIo16 __PRI16 "o"
#define PRIo32 __PRI32 "o"
#define PRIo64 __PRI64 "o"
#define PRIo128 __PRI128 "o"
#define PRIoLEAST8 __PRI8 "o"
#define PRIoLEAST16 __PRI16 "o"
#define PRIoLEAST32 __PRI32 "o"
#define PRIoLEAST64 __PRI64 "o"
#define PRIoLEAST128 __PRI128 "o"
#define PRIoFAST8 __PRI8 "o"
#define PRIoFAST16 __PRI32 "o"
#define PRIoFAST32 __PRI32 "o"
#define PRIoFAST64 __PRI64 "o"
#define PRIoFAST128 __PRI128 "o"
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation » printf » hexadecimal ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PRIx8 __PRI8 "x"
#define PRIx16 __PRI16 "x"
#define PRIx32 __PRI32 "x"
#define PRIx64 __PRI64 "x"
#define PRIx128 __PRI128 "x"
#define PRIxLEAST8 __PRI8 "x"
#define PRIxLEAST16 __PRI16 "x"
#define PRIxLEAST32 __PRI32 "x"
#define PRIxLEAST64 __PRI64 "x"
#define PRIxLEAST128 __PRI128 "x"
#define PRIxFAST8 __PRI8 "x"
#define PRIxFAST16 __PRI32 "x"
#define PRIxFAST32 __PRI32 "x"
#define PRIxFAST64 __PRI64 "x"
#define PRIxFAST128 __PRI128 "x"
#define PRIX8 __PRI8 "X"
#define PRIX16 __PRI16 "X"
#define PRIX32 __PRI32 "X"
#define PRIX64 __PRI64 "X"
#define PRIX128 __PRI128 "X"
#define PRIXLEAST8 __PRI8 "X"
#define PRIXLEAST16 __PRI16 "X"
#define PRIXLEAST32 __PRI32 "X"
#define PRIXLEAST64 __PRI64 "X"
#define PRIXLEAST128 __PRI128 "X"
#define PRIXFAST8 __PRI8 "X"
#define PRIXFAST16 __PRI32 "X"
#define PRIXFAST32 __PRI32 "X"
#define PRIXFAST64 __PRI64 "X"
#define PRIXFAST128 __PRI128 "X"
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation » printf » binary ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PRIb8 __PRI8 "b"
#define PRIb16 __PRI16 "b"
#define PRIb32 __PRI32 "b"
#define PRIb64 __PRI64 "b"
#define PRIb128 __PRI128 "b"
#define PRIbLEAST8 __PRI8 "b"
#define PRIbLEAST16 __PRI16 "b"
#define PRIbLEAST32 __PRI32 "b"
#define PRIbLEAST64 __PRI64 "b"
#define PRIbLEAST128 __PRI128 "b"
#define PRIbFAST8 __PRI8 "b"
#define PRIbFAST16 __PRI32 "b"
#define PRIbFAST32 __PRI32 "b"
#define PRIbFAST64 __PRI64 "b"
#define PRIbFAST128 __PRI128 "b"
#define PRIB8 __PRI8 "B"
#define PRIB16 __PRI16 "B"
#define PRIB32 __PRI32 "B"
#define PRIB64 __PRI64 "B"
#define PRIB128 __PRI128 "B"
#define PRIBLEAST8 __PRI8 "B"
#define PRIBLEAST16 __PRI16 "B"
#define PRIBLEAST32 __PRI32 "B"
#define PRIBLEAST64 __PRI64 "B"
#define PRIBLEAST128 __PRI128 "B"
#define PRIBFAST8 __PRI8 "B"
#define PRIBFAST16 __PRI32 "B"
#define PRIBFAST32 __PRI32 "B"
#define PRIBFAST64 __PRI64 "B"
#define PRIBFAST128 __PRI128 "B"
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation » printf » miscellaneous ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PRIdMAX "jd"
#define PRIiMAX "ji"
#define PRIoMAX "jo"
#define PRIuMAX "ju"
#define PRIxMAX "jx"
#define PRIXMAX "jX"
#define PRIdPTR __PRIPTR "d"
#define PRIiPTR __PRIPTR "i"
#define PRIoPTR __PRIPTR "o"
#define PRIuPTR __PRIPTR "u"
#define PRIxPTR __PRIPTR "x"
#define PRIXPTR __PRIPTR "X"
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation » scanf » decimal ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define SCNd8 __PRI8 "d"
#define SCNd16 __PRI16 "d"
#define SCNd32 __PRI32 "d"
#define SCNd64 __PRI64 "d"
#define SCNd128 __PRI128 "d"
#define SCNdLEAST8 __PRI8 "d"
#define SCNdLEAST16 __PRI16 "d"
#define SCNdLEAST32 __PRI32 "d"
#define SCNdLEAST64 __PRI64 "d"
#define SCNdLEAST128 __PRI128 "d"
#define SCNdFAST8 __PRI8 "d"
#define SCNdFAST16 __PRI32 "d"
#define SCNdFAST32 __PRI32 "d"
#define SCNdFAST64 __PRI64 "d"
#define SCNdFAST128 __PRI128 "d"
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation » scanf » flexidecimal ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define SCNi8 __PRI8 "i"
#define SCNi16 __PRI16 "i"
#define SCNi32 __PRI32 "i"
#define SCNi64 __PRI64 "i"
#define SCNi128 __PRI128 "i"
#define SCNiLEAST8 __PRI8 "i"
#define SCNiLEAST16 __PRI16 "i"
#define SCNiLEAST32 __PRI32 "i"
#define SCNiLEAST64 __PRI64 "i"
#define SCNiLEAST128 __PRI128 "i"
#define SCNiFAST8 __PRI8 "i"
#define SCNiFAST16 __PRI32 "i"
#define SCNiFAST32 __PRI32 "i"
#define SCNiFAST64 __PRI64 "i"
#define SCNiFAST128 __PRI128 "i"
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation » scanf » unsigned decimal ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define SCNu8 __PRI8 "u"
#define SCNu16 __PRI16 "u"
#define SCNu32 __PRI32 "u"
#define SCNu64 __PRI64 "u"
#define SCNu128 __PRI128 "u"
#define SCNuLEAST8 __PRI8 "u"
#define SCNuLEAST16 __PRI16 "u"
#define SCNuLEAST32 __PRI32 "u"
#define SCNuLEAST64 __PRI64 "u"
#define SCNuLEAST128 __PRI128 "u"
#define SCNuFAST8 __PRI8 "u"
#define SCNuFAST16 __PRI32 "u"
#define SCNuFAST32 __PRI32 "u"
#define SCNuFAST64 __PRI64 "u"
#define SCNuFAST128 __PRI128 "u"
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation » scanf » octal ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define SCNo8 __PRI8 "o"
#define SCNo16 __PRI16 "o"
#define SCNo32 __PRI32 "o"
#define SCNo64 __PRI64 "o"
#define SCNo128 __PRI128 "o"
#define SCNoLEAST8 __PRI8 "o"
#define SCNoLEAST16 __PRI16 "o"
#define SCNoLEAST32 __PRI32 "o"
#define SCNoLEAST64 __PRI64 "o"
#define SCNoLEAST128 __PRI128 "o"
#define SCNoFAST8 __PRI8 "o"
#define SCNoFAST16 __PRI32 "o"
#define SCNoFAST32 __PRI32 "o"
#define SCNoFAST64 __PRI64 "o"
#define SCNoFAST128 __PRI128 "o"
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation » scanf » hexadecimal ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define SCNx8 __PRI8 "x"
#define SCNx16 __PRI16 "x"
#define SCNx32 __PRI32 "x"
#define SCNx64 __PRI64 "x"
#define SCNx128 __PRI128 "x"
#define SCNxLEAST8 __PRI8 "x"
#define SCNxLEAST16 __PRI16 "x"
#define SCNxLEAST32 __PRI32 "x"
#define SCNxLEAST64 __PRI64 "x"
#define SCNxLEAST128 __PRI128 "x"
#define SCNxFAST8 __PRI8 "x"
#define SCNxFAST16 __PRI32 "x"
#define SCNxFAST32 __PRI32 "x"
#define SCNxFAST64 __PRI64 "x"
#define SCNxFAST128 __PRI128 "x"
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation » scanf » binary ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define SCNb8 __PRI8 "b"
#define SCNb16 __PRI16 "b"
#define SCNb32 __PRI32 "b"
#define SCNb64 __PRI64 "b"
#define SCNb128 __PRI128 "b"
#define SCNbLEAST8 __PRI8 "b"
#define SCNbLEAST16 __PRI16 "b"
#define SCNbLEAST32 __PRI32 "b"
#define SCNbLEAST64 __PRI64 "b"
#define SCNbLEAST128 __PRI128 "b"
#define SCNbFAST8 __PRI8 "b"
#define SCNbFAST16 __PRI32 "b"
#define SCNbFAST32 __PRI32 "b"
#define SCNbFAST64 __PRI64 "b"
#define SCNbFAST128 __PRI128 "b"
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dismal format notation » scanf » miscellaneous ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define SCNdMAX "jd"
#define SCNiMAX "ji"
#define SCNoMAX "jo"
#define SCNuMAX "ju"
#define SCNxMAX "jx"
#define SCNdPTR __PRIPTR "d"
#define SCNiPTR __PRIPTR "i"
#define SCNoPTR __PRIPTR "o"
#define SCNuPTR __PRIPTR "u"
#define SCNxPTR __PRIPTR "x"
#endif /* COSMOPOLITAN_LIBC_INTTYPES_H_ */
| 17,397 | 407 | jart/cosmopolitan | false |
cosmopolitan/libc/mem/tarjan.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/limits.h"
#include "libc/macros.internal.h"
#include "libc/mem/alg.h"
#include "libc/mem/mem.h"
/**
* @fileoverview Tarjan's Strongly Connected Components Algorithm.
*
* âThe data structures that [Tarjan] devised for this problem fit
* together in an amazingly beautiful way, so that the quantities
* you need to look at while exploring a directed graph are always
* magically at your fingertips. And his algorithm also does
* topological sorting as a byproduct.â ââD.E. Knuth
*/
struct Tarjan {
int Vn, En, Ci, Ri, *R, *C, index;
const int (*E)[2];
struct Vertex {
int Vi;
int Ei;
int index;
int lowlink;
bool onstack;
bool selfreferential;
} * V;
struct TarjanStack {
int i;
int n;
int *p;
} S;
};
static bool TarjanPush(struct Tarjan *t, int v) {
int *q;
_unassert(t->S.i >= 0);
_unassert(t->S.n >= 0);
_unassert(0 <= v && v < t->Vn);
if (t->S.i == t->S.n) {
if ((q = realloc(t->S.p, (t->S.n + (t->S.n >> 1) + 8) * sizeof(*t->S.p)))) {
t->S.p = q;
} else {
return false;
}
}
t->S.p[t->S.i++] = v;
return true;
}
static int TarjanPop(struct Tarjan *t) {
_unassert(t->S.i > 0);
return t->S.p[--t->S.i];
}
static bool TarjanConnect(struct Tarjan *t, int v) {
int fs, w, e;
_unassert(0 <= v && v < t->Vn);
t->V[v].index = t->index;
t->V[v].lowlink = t->index;
t->V[v].onstack = true;
t->index++;
if (!TarjanPush(t, v)) return false;
fs = t->V[v].Ei;
if (fs != -1) {
for (e = fs; e < t->En && v == t->E[e][0]; ++e) {
w = t->E[e][1];
if (!t->V[w].index) {
if (!TarjanConnect(t, t->V[w].Vi)) return false;
t->V[v].lowlink = MIN(t->V[v].lowlink, t->V[w].lowlink);
} else if (t->V[w].onstack) {
t->V[v].lowlink = MIN(t->V[v].lowlink, t->V[w].index);
}
if (w == v) {
t->V[w].selfreferential = true;
}
}
}
if (t->V[v].lowlink == t->V[v].index) {
do {
w = TarjanPop(t);
t->V[w].onstack = false;
t->R[t->Ri++] = t->V[w].Vi;
} while (w != v);
if (t->C) t->C[t->Ci++] = t->Ri;
}
return true;
}
/**
* Determines order of things in network and finds tangled clusters too.
*
* @param vertices is an array of vertex values, which isn't passed to
* this function, since the algorithm only needs to consider indices
* @param vertex_count is the number of items in the vertices array
* @param edges are grouped directed links between indices of vertices,
* which can be thought of as "edge[i][0] depends on edge[i][1]" or
* "edge[i][1] must come before edge[i][0]" in topological order
* @param edge_count is the number of items in edges, which may be 0 if
* there aren't any connections between vertices in the graph
* @param out_sorted receives indices into the vertices array in
* topologically sorted order, and must be able to store
* vertex_count items, and that's always how many are stored
* @param out_opt_components receives indices into the out_sorted array,
* indicating where each strongly-connected component ends; must be
* able to store vertex_count items; and it may be NULL
* @param out_opt_componentcount receives the number of cycle indices
* written to out_opt_components, which will be vertex_count if
* there aren't any cycles in the graph; and may be NULL if
* out_opt_components is NULL
* @return 0 on success or -1 w/ errno
* @error ENOMEM
* @note Tarjan's Algorithm is O(|V|+|E|)
*/
int _tarjan(int vertex_count, const int (*edges)[2], int edge_count,
int out_sorted[], int out_opt_components[],
int *out_opt_componentcount) {
int i, rc, v, e;
struct Tarjan *t;
_unassert(0 <= edge_count && edge_count <= INT_MAX);
_unassert(0 <= vertex_count && vertex_count <= INT_MAX);
for (i = 0; i < edge_count; ++i) {
if (i) _unassert(edges[i - 1][0] <= edges[i][0]);
_unassert(edges[i][0] < vertex_count);
_unassert(edges[i][1] < vertex_count);
}
if (!(t = calloc(1, (sizeof(struct Tarjan) +
sizeof(struct Vertex) * vertex_count)))) {
return -1;
}
t->V = (struct Vertex *)((char *)t + sizeof(struct Tarjan));
t->Vn = vertex_count;
t->E = edges;
t->En = edge_count;
t->R = out_sorted;
t->C = out_opt_components;
t->index = 1;
for (v = 0; v < t->Vn; ++v) {
t->V[v].Vi = v;
t->V[v].Ei = -1;
}
for (e = 0, v = -1; e < t->En; ++e) {
if (t->E[e][0] == v) continue;
v = t->E[e][0];
t->V[v].Ei = e;
}
rc = 0;
for (v = 0; v < t->Vn; ++v) {
if (!t->V[v].index) {
if (!TarjanConnect(t, v)) {
free(t->S.p);
free(t);
return -1;
}
}
}
if (out_opt_components) {
*out_opt_componentcount = t->Ci;
}
_unassert(t->Ri == vertex_count);
free(t->S.p);
free(t);
return rc;
}
| 6,746 | 183 | jart/cosmopolitan | false |
cosmopolitan/libc/mem/critbit0.h | #ifndef COSMOPOLITAN_LIBC_ALG_CRITBIT0_H_
#define COSMOPOLITAN_LIBC_ALG_CRITBIT0_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § data structures » critical bit tree (for c strings) ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
struct critbit0 {
void *root;
size_t count;
};
bool critbit0_contains(struct critbit0 *, const char *) dontthrow nosideeffect
paramsnonnull();
int critbit0_insert(struct critbit0 *, const char *) paramsnonnull();
bool critbit0_delete(struct critbit0 *, const char *) dontthrow paramsnonnull();
void critbit0_clear(struct critbit0 *) dontthrow paramsnonnull();
char *critbit0_get(struct critbit0 *, const char *);
intptr_t critbit0_allprefixed(struct critbit0 *, const char *,
intptr_t (*)(const char *, void *), void *)
paramsnonnull((1, 2, 3)) dontthrow;
int critbit0_emplace(struct critbit0 *, char *, size_t) paramsnonnull();
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_ALG_CRITBIT0_H_ */
| 1,501 | 28 | jart/cosmopolitan | false |
cosmopolitan/libc/mem/mem.h | #ifndef COSMOPOLITAN_LIBC_MEM_MEM_H_
#define COSMOPOLITAN_LIBC_MEM_MEM_H_
#define M_TRIM_THRESHOLD (-1)
#define M_GRANULARITY (-2)
#define M_MMAP_THRESHOLD (-3)
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § dynamic memory ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
void free(void *) libcesque;
void *malloc(size_t) attributeallocsize((1)) mallocesque;
void *calloc(size_t, size_t) attributeallocsize((1, 2)) mallocesque;
void *memalign(size_t, size_t) attributeallocalign((1))
attributeallocsize((2)) returnspointerwithnoaliases libcesque dontdiscard;
void *realloc(void *, size_t) reallocesque;
void *realloc_in_place(void *, size_t) reallocesque;
void *reallocarray(void *, size_t, size_t) dontdiscard;
void *valloc(size_t) attributeallocsize((1)) vallocesque;
void *pvalloc(size_t) vallocesque;
char *strdup(const char *) paramsnonnull() mallocesque;
char *strndup(const char *, size_t) paramsnonnull() mallocesque;
void *aligned_alloc(size_t, size_t) attributeallocalign((1))
attributeallocsize((2)) returnspointerwithnoaliases libcesque dontdiscard;
int posix_memalign(void **, size_t, size_t);
bool __grow(void *, size_t *, size_t, size_t) paramsnonnull((1, 2)) libcesque;
int malloc_trim(size_t);
size_t bulk_free(void **, size_t);
size_t malloc_usable_size(void *);
void **independent_calloc(size_t, size_t, void **);
void **independent_comalloc(size_t, size_t *, void **);
wchar_t *wcsdup(const wchar_t *) strlenesque dontdiscard;
struct mallinfo {
size_t arena; /* non-mmapped space allocated from system */
size_t ordblks; /* number of free chunks */
size_t smblks; /* always 0 */
size_t hblks; /* always 0 */
size_t hblkhd; /* space in mmapped regions */
size_t usmblks; /* maximum total allocated space */
size_t fsmblks; /* always 0 */
size_t uordblks; /* total allocated space */
size_t fordblks; /* total free space */
size_t keepcost; /* releasable (via malloc_trim) space */
};
struct mallinfo mallinfo(void);
size_t malloc_footprint(void);
size_t malloc_max_footprint(void);
size_t malloc_footprint_limit(void);
size_t malloc_set_footprint_limit(size_t);
void malloc_inspect_all(void (*handler)(void *, void *, size_t, void *),
void *);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_MEM_MEM_H_ */
| 2,866 | 64 | jart/cosmopolitan | false |
cosmopolitan/libc/mem/radix_sort_int64.c | /*-*- 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 2023 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/mem/alg.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
// Credit: Andrew Schein. 2009. Open-source C++ implementation of Radix
// Sort for double-precision floating points. (2009).
#define HIST_SIZE (size_t)2048
#define get_byte_0(v) ((v)&0x7FF)
#define get_byte_1(v) (((v) >> 11) & 0x7FF)
#define get_byte_2(v) (((v) >> 22) & 0x7FF)
#define get_byte_3(v) (((v) >> 33) & 0x7FF)
#define get_byte_4(v) (((v) >> 44) & 0x7FF)
#define get_byte_5(v) (((v) >> 55) & 0x7FF)
#define get_byte_2_flip_sign(v) (((unsigned)(v) >> 22) ^ 0x200)
#define get_byte_5_flip_sign(v) ((((v) >> 55) & 0x7FF) ^ 0x400)
bool radix_sort_int64(int64_t *A, size_t n) {
int64_t *T, *reader, *writer;
size_t *b0, *b1, *b2, *b3, *b4, *b5;
size_t i, pos, sum0, sum1, sum2, sum3, sum4, sum5, tsum;
if (n < HIST_SIZE) {
_longsort(A, n);
return true;
}
if (!(T = (int64_t *)malloc(n * sizeof(int64_t)))) {
return false;
}
if (!(b0 = (size_t *)calloc(HIST_SIZE * 6, sizeof(size_t)))) {
free(T);
return false;
}
b1 = b0 + HIST_SIZE;
b2 = b1 + HIST_SIZE;
b3 = b2 + HIST_SIZE;
b4 = b3 + HIST_SIZE;
b5 = b4 + HIST_SIZE;
for (i = 0; i < n; i++) {
b0[get_byte_0(A[i])]++;
b1[get_byte_1(A[i])]++;
b2[get_byte_2(A[i])]++;
b3[get_byte_3(A[i])]++;
b4[get_byte_4(A[i])]++;
b5[get_byte_5_flip_sign(A[i])]++;
}
sum0 = sum1 = sum2 = sum3 = sum4 = sum5 = tsum = 0;
for (i = 0; i < HIST_SIZE; i++) {
tsum = b0[i] + sum0;
b0[i] = sum0 - 1;
sum0 = tsum;
tsum = b1[i] + sum1;
b1[i] = sum1 - 1;
sum1 = tsum;
tsum = b2[i] + sum2;
b2[i] = sum2 - 1;
sum2 = tsum;
tsum = b3[i] + sum3;
b3[i] = sum3 - 1;
sum3 = tsum;
tsum = b4[i] + sum4;
b4[i] = sum4 - 1;
sum4 = tsum;
tsum = b5[i] + sum5;
b5[i] = sum5 - 1;
sum5 = tsum;
}
writer = T;
reader = A;
for (i = 0; i < n; i++) {
pos = get_byte_0(reader[i]);
writer[++b0[pos]] = reader[i];
}
writer = A;
reader = T;
for (i = 0; i < n; i++) {
pos = get_byte_1(reader[i]);
writer[++b1[pos]] = reader[i];
}
writer = T;
reader = A;
for (i = 0; i < n; i++) {
pos = get_byte_2(reader[i]);
writer[++b2[pos]] = reader[i];
}
writer = A;
reader = T;
for (i = 0; i < n; i++) {
pos = get_byte_3(reader[i]);
writer[++b3[pos]] = reader[i];
}
writer = T;
reader = A;
for (i = 0; i < n; i++) {
pos = get_byte_4(reader[i]);
writer[++b4[pos]] = reader[i];
}
writer = A;
reader = T;
for (i = 0; i < n; i++) {
pos = get_byte_5_flip_sign(reader[i]);
writer[++b5[pos]] = reader[i];
}
free(b0);
free(T);
return true;
}
| 4,630 | 145 | jart/cosmopolitan | false |
cosmopolitan/libc/mem/free.c | /*-*- 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 2023 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/mem/hook.internal.h"
#include "libc/mem/mem.h"
#include "third_party/dlmalloc/dlmalloc.h"
void (*hook_free)(void *) = dlfree;
/**
* Free memory returned by malloc() & co.
*
* Releases the chunk of memory pointed to by p, that had been
* previously allocated using malloc or a related routine such as
* realloc. It has no effect if p is null. If p was not malloced or
* already freed, free(p) will by default cause the current program to
* abort.
*
* @param p is allocation address, which may be NULL
* @see dlfree()
* @threadsafe
*/
void free(void *p) {
hook_free(p);
}
| 2,437 | 41 | jart/cosmopolitan | false |
cosmopolitan/libc/mem/heapsort.c | /*-*- 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) 1991, 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/mem/alg.h"
#include "libc/mem/mem.h"
#include "libc/sysv/errfuns.h"
// clang-format off
/*
* Swap two areas of size number of bytes. Although qsort(3) permits random
* blocks of memory to be sorted, sorting pointers is almost certainly the
* common case (and, were it not, could easily be made so). Regardless, it
* isn't worth optimizing; the SWAP's get sped up by the cache, and pointer
* arithmetic gets lost in the time required for comparison function calls.
*/
#define SWAP(a, b, count, size, tmp) { \
count = size; \
do { \
tmp = *a; \
*a++ = *b; \
*b++ = tmp; \
} while (--count); \
}
/* Copy one block of size size to another. */
#define COPY(a, b, count, size, tmp1, tmp2) { \
count = size; \
tmp1 = a; \
tmp2 = b; \
do { \
*tmp1++ = *tmp2++; \
} while (--count); \
}
/*
* Build the list into a heap, where a heap is defined such that for
* the records K1 ... KN, Kj/2 >= Kj for 1 <= j/2 <= j <= N.
*
* There are two cases. If j == nmemb, select largest of Ki and Kj. If
* j < nmemb, select largest of Ki, Kj and Kj+1.
*/
#define CREATE(initval, nmemb, par_i, child_i, par, child, size, count, tmp) { \
for (par_i = initval; (child_i = par_i * 2) <= nmemb; \
par_i = child_i) { \
child = base + child_i * size; \
if (child_i < nmemb && compar(child, child + size, z) < 0) { \
child += size; \
++child_i; \
} \
par = base + par_i * size; \
if (compar(child, par, z) <= 0) \
break; \
SWAP(par, child, count, size, tmp); \
} \
}
/*
* Select the top of the heap and 'heapify'. Since by far the most expensive
* action is the call to the compar function, a considerable optimization
* in the average case can be achieved due to the fact that k, the displaced
* element, is usually quite small, so it would be preferable to first
* heapify, always maintaining the invariant that the larger child is copied
* over its parent's record.
*
* Then, starting from the *bottom* of the heap, finding k's correct place,
* again maintaining the invariant. As a result of the invariant no element
* is 'lost' when k is assigned its correct place in the heap.
*
* The time savings from this optimization are on the order of 15-20% for the
* average case. See Knuth, Vol. 3, page 158, problem 18.
*
* XXX Don't break the #define SELECT line, below. Reiser cpp gets upset.
*/
#define SELECT(par_i, child_i, nmemb, par, child, size, k, count, tmp1, tmp2) { \
for (par_i = 1; (child_i = par_i * 2) <= nmemb; par_i = child_i) { \
child = base + child_i * size; \
if (child_i < nmemb && compar(child, child + size, z) < 0) { \
child += size; \
++child_i; \
} \
par = base + par_i * size; \
COPY(par, child, count, size, tmp1, tmp2); \
} \
for (;;) { \
child_i = par_i; \
par_i = child_i / 2; \
child = base + child_i * size; \
par = base + par_i * size; \
if (child_i == 1 || compar(k, par, z) < 0) { \
COPY(child, k, count, size, tmp1, tmp2); \
break; \
} \
COPY(child, par, count, size, tmp1, tmp2); \
} \
}
/**
* Sorts array w/ optional callback argument.
*
* @param vbase is base of array
* @param nmemb is item count
* @param size is item width
* @param compar is a callback returning <0, 0, or >0
* @param z will optionally be passed as the third argument to cmp
* @see heapsort()
*/
int
heapsort_r(void *vbase, size_t nmemb, size_t size,
int (*compar)(const void *, const void *, void *), void *z)
{
size_t cnt, i, j, l;
char tmp, *tmp1, *tmp2;
char *base, *k, *p, *t;
if (nmemb <= 1)
return (0);
if (!size)
return (einval());
if ((k = malloc(size)) == NULL)
return (-1);
/*
* Items are numbered from 1 to nmemb, so offset from size bytes
* below the starting address.
*/
base = (char *)vbase - size;
for (l = nmemb / 2 + 1; --l;)
CREATE(l, nmemb, i, j, t, p, size, cnt, tmp);
/*
* For each element of the heap, save the largest element into its
* final slot, save the displaced element (k), then recreate the
* heap.
*/
while (nmemb > 1) {
COPY(k, base + nmemb * size, cnt, size, tmp1, tmp2);
COPY(base + nmemb * size, base + size, cnt, size, tmp1, tmp2);
--nmemb;
SELECT(i, j, nmemb, t, p, size, k, cnt, tmp1, tmp2);
}
free(k);
return (0);
}
/**
* Sorts array.
*
* Runs in O (N lg N), both average and worst. While heapsort is faster
* than the worst case of quicksort, the BSD quicksort does median
* selection so that the chance of finding a data set that will trigger
* the worst case is nonexistent. Heapsort's only advantage over
* quicksort is that it requires little additional memory.
*
* @param vbase is base of array
* @param nmemb is item count
* @param size is item width
* @param compar is a callback returning <0, 0, or >0
* @see Knuth, Vol. 3, page 145.
* @see heapsort_r()
* @see mergesort()
* @see qsort()
*/
int
heapsort(void *vbase, size_t nmemb, size_t size,
int (*compar)(const void *, const void *))
{
return heapsort_r(vbase, nmemb, size, (void *)compar, 0);
}
| 7,861 | 199 | jart/cosmopolitan | false |
cosmopolitan/libc/mem/copyfd.internal.h | #ifndef COSMOPOLITAN_LIBC_MEM_IO_H_
#define COSMOPOLITAN_LIBC_MEM_IO_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
ssize_t _copyfd(int, int, size_t);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_MEM_IO_H_ */
| 277 | 11 | jart/cosmopolitan | false |
cosmopolitan/libc/mem/bsearch_r.c | /*-*- 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/mem/alg.h"
#include "libc/mem/bisect.internal.h"
/**
* Searches sorted array for exact item in logarithmic time.
* @see bsearch(), bisectcarleft()
*/
void *bsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
int cmp(const void *a, const void *b, void *arg), void *arg) {
return bisect(key, base, nmemb, size, cmp, arg);
}
| 2,215 | 30 | jart/cosmopolitan | false |
cosmopolitan/libc/mem/alloca.h | #ifndef COSMOPOLITAN_LIBC_MEM_ALLOCA_H_
#define COSMOPOLITAN_LIBC_MEM_ALLOCA_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
#define alloca(size) __builtin_alloca(size)
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_MEM_ALLOCA_H_ */
| 256 | 9 | jart/cosmopolitan | false |
cosmopolitan/libc/mem/critbit0_clear.c | /*-*- 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/mem/critbit0.h"
#include "libc/mem/internal.h"
#include "libc/mem/mem.h"
static void critbit0_clear_traverse(void *top) {
unsigned char *p = top;
if (1 & (intptr_t)p) {
struct CritbitNode *q = (void *)(p - 1);
critbit0_clear_traverse(q->child[0]);
critbit0_clear_traverse(q->child[1]);
free(q), q = NULL;
} else {
free(p), p = NULL;
}
}
/**
* Removes all items from ð¡.
* @param t tree
* @note h/t djb and agl
*/
void critbit0_clear(struct critbit0 *t) {
if (t->root) {
critbit0_clear_traverse(t->root);
t->root = NULL;
}
t->count = 0;
}
| 2,439 | 47 | jart/cosmopolitan | false |
cosmopolitan/libc/mem/arraylist2.internal.h | #ifndef COSMOPOLITAN_LIBC_ALG_ARRAYLIST2_H_
#define COSMOPOLITAN_LIBC_ALG_ARRAYLIST2_H_
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
/* TODO(jart): Fully develop these better macros. */
#define APPEND(LIST_P, LIST_I, LIST_N, ITEM) \
CONCAT(LIST_P, LIST_I, LIST_N, ITEM, 1)
#ifndef CONCAT
#define CONCAT(LIST_P, LIST_I, LIST_N, ITEM, COUNT) \
({ \
autotype(LIST_P) ListP = (LIST_P); \
autotype(LIST_I) ListI = (LIST_I); \
autotype(LIST_N) ListN = (LIST_N); \
typeof(&(*ListP)[0]) Item = (ITEM); \
size_t SizE = sizeof(*Item); \
size_t Count = (COUNT); \
ssize_t Entry = -1; \
/* NOTE: We use `<` to guarantee one additional slot */ \
/* grow() will memset(0) extended memory, thus */ \
/* you get a nul-terminator for free sometimes */ \
/* the exception is if you list.i=0 and re-use */ \
/* so you need concat(...); list.p[list.i++]=0 */ \
if (*ListI + Count < *ListN || __grow(ListP, ListN, SizE, Count)) { \
memcpy(&(*ListP)[*ListI], Item, (SizE) * (Count)); \
Entry = *ListI; \
*ListI += Count; /* happens after copy in case signal */ \
} \
Entry; \
})
#endif /* CONCAT */
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_ALG_ARRAYLIST2_H_ */
| 1,982 | 40 | jart/cosmopolitan | false |