Validate privileged code relationships

- Work towards improving non-optimized build support
- Introduce MODE=zero which is -O0 without ASAN/UBSAN
- Use system GCC when ~/.cosmo.mk has USE_SYSTEM_TOOLCHAIN=1
- Have package.com check .privileged code doesn't call non-privileged
This commit is contained in:
Justine Tunney 2023-06-08 04:37:05 -07:00
parent 01fd655097
commit daf4454a06
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
82 changed files with 808 additions and 850 deletions

View file

@ -183,6 +183,18 @@ o/$(MODE)/libc/calls/timeval_frommicros.o: private \
CFLAGS += \
-O2
# privileged functions
o/$(MODE)/libc/calls/sigenter-freebsd.o \
o/$(MODE)/libc/calls/sigenter-netbsd.o \
o/$(MODE)/libc/calls/sigenter-openbsd.o \
o/$(MODE)/libc/calls/sigenter-linux.o \
o/$(MODE)/libc/calls/sigenter-xnu.o \
o/$(MODE)/libc/calls/pledge-linux.o \
o/$(MODE)/libc/calls/siginfo2cosmo.o: private \
CFLAGS += \
-ffreestanding \
-fno-sanitize=all
o/$(MODE)/libc/calls/pledge-linux.o \
o/$(MODE)/libc/calls/unveil.o: private \
CFLAGS += \

View file

@ -48,7 +48,7 @@
* @raise ESRCH if no such process existed
* @see setpriority()
*/
privileged int getpriority(int which, unsigned who) {
int getpriority(int which, unsigned who) {
int rc;
#ifdef __x86_64__
char cf;

View file

@ -21,7 +21,7 @@
#include "libc/runtime/runtime.h"
#include "libc/sysv/consts/pr.h"
privileged bool __is_linux_2_6_23(void) {
bool __is_linux_2_6_23(void) {
#ifdef __x86_64__
int rc;
if (!IsLinux()) return false;

View file

@ -34,7 +34,7 @@
* C library runtime won't have any awareness of this memory, so certain
* features like ASAN memory safety and kprintf() won't work as well.
*/
privileged void *sys_mremap(void *p, size_t n, size_t m, int f, void *q) {
void *sys_mremap(void *p, size_t n, size_t m, int f, void *q) {
#ifdef __x86_64__
bool cf;
uintptr_t res, rdi, rsi, rdx;

View file

@ -31,7 +31,7 @@
*
* @raise ENOSYS on non-Linux
*/
privileged int prctl(int operation, ...) {
int prctl(int operation, ...) {
int rc;
va_list va;
intptr_t a, b, c, d;

View file

@ -35,7 +35,7 @@
*
* @raise ENOSYS on non-Linux.
*/
privileged int seccomp(unsigned operation, unsigned flags, void *args) {
int seccomp(unsigned operation, unsigned flags, void *args) {
int rc;
if (IsLinux()) {
#ifdef __x86_64__

View file

@ -41,7 +41,7 @@ privileged void __sigenter_wsl(int sig, struct siginfo *info, ucontext_t *ctx) {
ctx->uc_mcontext.fpregs = &ctx->__fpustate;
for (i = 0; i < 8; ++i) {
long double nan = NAN;
memcpy(ctx->__fpustate.st + i, &nan, 16);
__builtin_memcpy(ctx->__fpustate.st + i, &nan, 16);
}
}
((sigaction_f)(__executable_start + rva))(sig, info, ctx);

View file

@ -3,20 +3,18 @@
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
enum FdKind {
kFdEmpty,
kFdFile,
kFdSocket,
kFdProcess,
kFdConsole,
kFdSerial,
kFdZip,
kFdEpoll,
kFdReserved
};
#define kFdEmpty 0
#define kFdFile 1
#define kFdSocket 2
#define kFdProcess 3
#define kFdConsole 4
#define kFdSerial 5
#define kFdZip 6
#define kFdEpoll 7
#define kFdReserved 8
struct Fd {
enum FdKind kind;
int kind;
unsigned flags;
unsigned mode;
int64_t handle;

View file

@ -24,6 +24,7 @@
#include "libc/dce.h"
#include "libc/intrin/strace.internal.h"
#include "libc/nt/files.h"
#include "libc/sysv/consts/termios.h"
#include "libc/sysv/errfuns.h"
static textwindows int sys_tcdrain_nt(int fd) {

View file

@ -1,9 +1,7 @@
#ifndef COSMOPOLITAN_LIBC_CALLS_TERMIOS_H_
#define COSMOPOLITAN_LIBC_CALLS_TERMIOS_H_
#include "libc/calls/ioctl.h"
#include "libc/calls/struct/termios.h"
#include "libc/calls/struct/winsize.h"
#include "libc/sysv/consts/termios.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
@ -38,25 +36,6 @@ uint32_t cfgetispeed(const struct termios *);
int tcsetwinsize(int, const struct winsize *);
int tcgetwinsize(int, struct winsize *);
/*───────────────────────────────────────────────────────────────────────────│─╗
cosmopolitan § teletypewriter » undiamonding
*/
#if defined(__GNUC__) && !defined(__STRICT_ANSI__)
#define tcsetattr(FD, OPT, TIO) tcsetattr_dispatch(FD, OPT, TIO)
forceinline int tcsetattr_dispatch(int fd, int opt, const struct termios *tio) {
if (__EQUIVALENT(opt, TCSANOW)) return ioctl(fd, TCSETS, (void *)tio);
if (__EQUIVALENT(opt, TCSADRAIN)) return ioctl(fd, TCSETSW, (void *)tio);
if (__EQUIVALENT(opt, TCSAFLUSH)) return ioctl(fd, TCSETSF, (void *)tio);
return (tcsetattr)(fd, opt, tio);
}
#define tcgetattr(FD, TIO) tcgetattr_dispatch(FD, TIO)
forceinline int tcgetattr_dispatch(int fd, const struct termios *tio) {
return ioctl(fd, TCGETS, (void *)tio);
}
#endif /* GNUC && !ANSI */
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_TERMIOS_H_ */

View file

@ -36,7 +36,7 @@
#ifdef __x86_64__
privileged unsigned __wincrash(struct NtExceptionPointers *ep) {
unsigned __wincrash(struct NtExceptionPointers *ep) {
int64_t rip;
int sig, code;
ucontext_t ctx;

View file

@ -36,12 +36,6 @@
#define IsModeDbg() 0
#endif
#ifdef __MFENTRY__
#define HaveFentry() 1
#else
#define HaveFentry() 0
#endif
#ifdef TRUSTWORTHY
#define IsTrustworthy() 1
#else
@ -72,12 +66,6 @@
#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)

View file

@ -17,15 +17,16 @@
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/elf/elf.h"
#include "libc/intrin/kprintf.h"
#include "libc/runtime/runtime.h"
void CheckElfAddress(const Elf64_Ehdr *elf, size_t mapsize, intptr_t addr,
size_t addrsize) {
#if !(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); // */
kprintf("%p-%p falls outside interval %p-%p", //
addr, addr + addrsize, //
elf, (char *)elf + mapsize); //
abort();
}
#endif

View file

@ -14,14 +14,13 @@
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int snprintf(char *, size_t, const char *, ...) printfesque(3)
paramsnonnull((3)) dontthrow nocallback;
int snprintf(char *, size_t, const char *, ...)
printfesque(3) dontthrow nocallback;
int vsnprintf(char *, size_t, const char *, va_list)
paramsnonnull((3)) dontthrow nocallback;
int sprintf(char *, const char *, ...) printfesque(2)
paramsnonnull((2)) dontthrow nocallback frownedupon(snprintf);
dontthrow nocallback;
int sprintf(char *, const char *, ...) printfesque(2) dontthrow nocallback;
int vsprintf(char *, const char *, va_list)
paramsnonnull((2)) dontthrow nocallback frownedupon(vsnprintf);
dontthrow nocallback;
int sscanf(const char *, const char *, ...) scanfesque(2);
int vsscanf(const char *, const char *, va_list);
int vcscanf(int (*)(void *), int (*)(int, void *), void *, const char *,

View file

@ -729,6 +729,7 @@ void abort(void) wontreturn;
#if __GNUC__ >= 11
#pragma GCC diagnostic ignored /* annoying */ "-Wattributes"
#pragma GCC diagnostic ignored /* orwellian */ "-Wold-style-definition"
#pragma GCC diagnostic ignored /* what? */ "-Wformat-overflow"
#endif /* GCC11+ */
#endif /* GCC9+ */
#endif /* !C++ */
@ -834,10 +835,10 @@ void abort(void) wontreturn;
#if !defined(__STRICT_ANSI__) && !defined(__APPLE__) && defined(__x86_64__)
#define YOINK(SYMBOL) \
asm(".section .yoink\n\tnopl\t%a0\n\t.previous" : : "X"(SYMBOL))
asm(".section .yoink\n\tnopl\t%0\n\t.previous" : : "m"(SYMBOL))
#elif defined(__aarch64__)
#define YOINK(SYMBOL) \
asm(".section .yoink\n\tb\t%a0\n\t.previous" : : "X"(SYMBOL))
asm(".section .yoink\n\tb\t%0\n\t.previous" : : "m"(SYMBOL))
#else
#define YOINK(SYMBOL) (void)0
#endif

View file

@ -24,7 +24,7 @@
* @param p needs at least 12 bytes
* @return pointer to nul byte
*/
dontinline char *FormatUint32(char p[hasatleast 12], uint32_t x) {
privileged dontinline char *FormatUint32(char p[hasatleast 12], uint32_t x) {
char t;
size_t i, a, b;
i = 0;
@ -49,7 +49,7 @@ dontinline char *FormatUint32(char p[hasatleast 12], uint32_t x) {
* @param p needs at least 12 bytes
* @return pointer to nul byte
*/
char *FormatInt32(char p[hasatleast 12], int32_t x) {
privileged char *FormatInt32(char p[hasatleast 12], int32_t x) {
if (x < 0) *p++ = '-', x = -(uint32_t)x;
return FormatUint32(p, x);
}

View file

@ -18,7 +18,7 @@
*/
#include "libc/fmt/magnumstrs.internal.h"
char *GetMagnumStr(const struct MagnumStr *ms, int x) {
privileged char *GetMagnumStr(const struct MagnumStr *ms, int x) {
int i;
for (i = 0; ms[i].x != MAGNUM_TERMINATOR; ++i) {
if (x == MAGNUM_NUMBER(ms, i)) {

View file

@ -72,6 +72,7 @@ o/$(MODE)/libc/intrin/mman.greg.o: private \
o/$(MODE)/libc/intrin/asan.o \
o/$(MODE)/libc/intrin/ubsan.o: private \
CFLAGS += \
-ffreestanding \
-fno-sanitize=all \
-fno-stack-protector
@ -84,7 +85,6 @@ o/$(MODE)/libc/intrin/asan.o: private \
o/$(MODE)/libc/intrin/asanthunk.o: private \
CFLAGS += \
-x-no-pg \
$(MNO_FENTRY) \
-ffreestanding \
-fno-sanitize=all \
-fno-stack-protector
@ -100,7 +100,6 @@ o/$(MODE)/libc/intrin/kprintf.greg.o: private \
-fpie \
-fwrapv \
-x-no-pg \
$(MNO_FENTRY) \
-ffreestanding \
-fno-sanitize=all \
-fno-stack-protector
@ -115,7 +114,6 @@ o/$(MODE)/libc/intrin/_spinlock_debug_4.o: private \
CFLAGS += \
-fwrapv \
-x-no-pg \
$(MNO_FENTRY) \
-ffreestanding \
-fno-sanitize=all \
-mgeneral-regs-only \
@ -187,6 +185,17 @@ o/$(MODE)/libc/intrin/wsawaitformultipleevents.o: private\
-fno-stack-protector \
-fno-sanitize=all
# privileged functions
o/$(MODE)/libc/intrin/dos2errno.o \
o/$(MODE)/libc/intrin/have_fsgsbase.o \
o/$(MODE)/libc/intrin/getmagnumstr.o \
o/$(MODE)/libc/intrin/formatint32.o \
o/$(MODE)/libc/intrin/strsignal_r.o \
o/$(MODE)/libc/intrin/strerror_wr.o: private \
CFLAGS += \
-ffreestanding \
-fno-sanitize=all
o//libc/intrin/memmove.o: private \
CFLAGS += \
-fno-toplevel-reorder

View file

@ -16,7 +16,6 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/assert.h"
#include "libc/dce.h"
#include "libc/nt/version.h"
@ -26,6 +25,5 @@
* This function may only be called if IsWindows() is true.
*/
privileged bool(IsAtLeastWindows10)(void) {
_unassert(IsWindows());
return IsAtLeastWindows10();
}

View file

@ -287,6 +287,7 @@ privileged static size_t kformat(char *b, size_t n, const char *fmt,
cols = 0;
zero = 0;
uppr = 0;
ansi = 0;
abet = "0123456789abcdef";
for (;;) {
switch ((c = *f++)) {
@ -392,7 +393,7 @@ privileged static size_t kformat(char *b, size_t n, const char *fmt,
*p++ = '3';
*p++ = '0' + x % 8;
*p++ = 'm';
ansi = true;
ansi = 1;
}
} else {
x = 666;
@ -527,10 +528,10 @@ privileged static size_t kformat(char *b, size_t n, const char *fmt,
unixerr = errno;
winerr = 0;
if (IsWindows()) {
if (type == 1 && _weaken(WSAGetLastError)) {
winerr = _weaken(WSAGetLastError)();
} else if (_weaken(GetLastError)) {
winerr = _weaken(GetLastError)();
if (type == 1 && _weaken(__imp_WSAGetLastError)) {
winerr = (*_weaken(__imp_WSAGetLastError))();
} else if (_weaken(__imp_GetLastError)) {
winerr = (*_weaken(__imp_GetLastError))();
}
}
if (!unixerr && sign == ' ') {
@ -777,7 +778,7 @@ privileged static size_t kformat(char *b, size_t n, const char *fmt,
*p++ = '0';
*p++ = 'm';
}
ansi = false;
ansi = 0;
}
break;
}

View file

@ -2,7 +2,7 @@
#define COSMOPOLITAN_LIBC_INTRIN_NOPL_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0) && defined(__x86_64__) && \
defined(__GNUC__) && !defined(__llvm__) && !defined(__chibicc__) && \
!defined(__STRICT_ANSI__)
defined(__MNO_RED_ZONE__) && !defined(__STRICT_ANSI__)
/**
* @fileoverview Turns CALLs into NOPs that are fixupable at runtime.
@ -35,34 +35,39 @@
".equ\t\"" SECTION "_end\",.\n\t" \
".previous\n\t"
#define _NOPL0(SECTION, FUNC) \
#define _NOPL0(SECTION, FUNC) __NOPL0(SECTION, FUNC, IMAGE_BASE_VIRTUAL)
#define __NOPL0(SECTION, FUNC, GARDEN) ___NOPL0(SECTION, FUNC, GARDEN)
#define ___NOPL0(SECTION, FUNC, GARDEN) \
({ \
asm volatile(_NOPL_PROLOGUE(SECTION) /* */ \
_NOPL_EPILOGUE(SECTION) /* */ \
".section \".sort.rodata." SECTION ".2\",\"a\",@progbits\n\t" \
".balign\t4\n\t" \
".long\t353f-%a1\n\t" \
".long\t353f-" #GARDEN "\n\t" \
".previous\n353:\t" \
"nopl\t%a0" \
"nopl\t" #FUNC "(%%rip)" \
: /* no inputs */ \
: "X"(FUNC), "X"(IMAGE_BASE_VIRTUAL) \
: /* no outputs */ \
: "rax", "rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", \
"r11", "memory", "cc"); \
(void)0; \
})
#define _NOPL1(SECTION, FUNC, ARG) \
#define _NOPL1(SECTION, FUNC, ARG) \
__NOPL1(SECTION, FUNC, ARG, IMAGE_BASE_VIRTUAL)
#define __NOPL1(SECTION, FUNC, ARG, GARDEN) ___NOPL1(SECTION, FUNC, ARG, GARDEN)
#define ___NOPL1(SECTION, FUNC, ARG, GARDEN) \
({ \
register autotype(ARG) __arg asm("rdi") = ARG; \
asm volatile(_NOPL_PROLOGUE(SECTION) /* */ \
_NOPL_EPILOGUE(SECTION) /* */ \
".section \".sort.rodata." SECTION ".2\",\"a\",@progbits\n\t" \
".balign\t4\n\t" \
".long\t353f-%a2\n\t" \
".long\t353f-" #GARDEN "\n\t" \
".previous\n353:\t" \
"nopl\t%a1" \
"nopl\t" #FUNC "(%%rip)" \
: "+D"(__arg) \
: "X"(FUNC), "X"(IMAGE_BASE_VIRTUAL) \
: /* no inputs */ \
: "rax", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", \
"memory", "cc"); \
(void)0; \

View file

@ -22,7 +22,7 @@
#include "libc/sysv/consts/at.h"
#include "libc/sysv/consts/o.h"
privileged void PrintSystemMappings(int outfd) {
void PrintSystemMappings(int outfd) {
int infd;
ssize_t rc;
char buf[64];

View file

@ -35,7 +35,7 @@ const unsigned char kConsoleHandles[3] = {
};
// Puts cmd.exe gui back the way it was.
noinstrument void _restorewintty(void) {
privileged noinstrument void _restorewintty(void) {
if (!IsWindows()) return;
if (__imp_GetCurrentProcessId() != __pid_exec) return;
for (int i = 0; i < 3; ++i) {

View file

@ -16,10 +16,10 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#define ShouldUseMsabiAttribute() 1
#include "libc/dce.h"
#include "libc/fmt/fmt.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/macros.internal.h"
#include "libc/nt/enum/formatmessageflags.h"
#include "libc/nt/enum/lang.h"
@ -39,8 +39,14 @@ privileged int strerror_wr(int err, uint32_t winerr, char *buf, size_t size) {
char16_t winmsg[256];
const char *sym, *msg;
wanting = false;
sym = firstnonnull(_strerrno(err), (wanting = true, "EUNKNOWN"));
msg = firstnonnull(_strerdoc(err), (wanting = true, "No error information"));
if (!(sym = _strerrno(err))) {
sym = "EUNKNOWN";
wanting = true;
}
if (!(msg = _strerdoc(err))) {
msg = "No error information";
wanting = true;
}
if (IsTiny()) {
if (!sym) sym = "EUNKNOWN";
for (; (c = *sym++); --size)
@ -49,7 +55,7 @@ privileged int strerror_wr(int err, uint32_t winerr, char *buf, size_t size) {
} else if (!IsWindows() || ((err == winerr || !winerr) && !wanting)) {
ksnprintf(buf, size, "%s/%d/%s", sym, err, msg);
} else {
if ((n = FormatMessage(
if ((n = __imp_FormatMessageW(
kNtFormatMessageFromSystem | kNtFormatMessageIgnoreInserts, 0,
winerr, MAKELANGID(kNtLangNeutral, kNtSublangDefault), winmsg,
ARRAYLEN(winmsg), 0))) {

View file

@ -36,7 +36,7 @@
* @asyncsignalsafe
* @threadsafe
*/
char *strsignal_r(int sig, char buf[hasatleast 15]) {
privileged char *strsignal_r(int sig, char buf[hasatleast 15]) {
int i;
char *p;
const char *s;

View file

@ -35,7 +35,6 @@ privileged int64_t __winerr(void) {
errno_t e;
if (IsWindows()) {
e = __dos2errno(__imp_GetLastError());
_npassert(e > 0);
} else {
e = ENOSYS;
}

View file

@ -28,7 +28,7 @@
/**
* Attaches GDB temporarily, to do something like print a variable.
*/
privileged int(gdbexec)(const char *cmd) {
relegated int(gdbexec)(const char *cmd) {
struct StackFrame *bp;
int pid, ttyin, ttyout;
intptr_t continuetoaddr;

View file

@ -19,6 +19,6 @@
#include "libc/log/log.h"
#include "libc/runtime/runtime.h"
privileged wontreturn void _log_exit(int exitcode) {
wontreturn void _log_exit(int exitcode) {
_Exitr(exitcode);
}

View file

@ -1,30 +0,0 @@
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│
vi: set et ft=asm ts=8 tw=8 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/macros.internal.h"
.real
.code16 # .code32 .code64
// Function entry hook stub.
//
// @note cc -pg -mfentry adds this to the start of every function
// @see libc/log/shadowargs.ncabi.c
// @mode long,legacy,real
__fentry__:
ret
.endfn __fentry__,weak

View file

@ -1,77 +0,0 @@
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│
vi: set et ft=asm ts=8 tw=8 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/macros.internal.h"
// @fileoverview Byte-order conversion functions.
//
// Endianness is deceptively complicated to the uninitiated. Many
// helpers have been written by our top minds to address perceived
// difficulties. These ones got through standardization processes.
// To protect their legacy, all 19 functions have been implemented
// in just 17 bytes.
//
// @see READ32LE(), READ32BE(), etc.
// @asyncsignalsafe
bswap_64:
htobe64:
htole64:
be64toh:
le64toh:mov %rdi,%rax
bswap %rax
ret
.endfn le64toh,globl
.endfn be64toh,globl
.endfn htole64,globl
.endfn htobe64,globl
.endfn bswap_64,globl
bswap_32:
htobe32:
htole32:
be32toh:
le32toh:
ntohl:
htonl: mov %edi,%eax
bswap %eax
ret
.endfn htonl,globl
.endfn htole32,globl
.endfn le32toh,globl
.endfn be32toh,globl
.endfn htobe32,globl
.endfn ntohl,globl
.endfn bswap_32,globl
bswap_16:
htobe16:
htole16:
be16toh:
le16toh:
ntohs:
htons: movzwl %di,%eax
xchg %al,%ah
ret
.endfn htobe16,globl
.endfn htons,globl
.endfn le16toh,globl
.endfn be16toh,globl
.endfn htole16,globl
.endfn ntohs,globl
.endfn bswap_16,globl

View file

@ -1,10 +1,10 @@
#define GetEnvironmentVariable(...) __imp_GetEnvironmentVariableW(__VA_ARGS__)
extern typeof(GetEnvironmentVariable) *const
__imp_GetEnvironmentVariableW __msabi;
extern typeof(GetEnvironmentVariable) *const __imp_GetEnvironmentVariableW
__msabi;
#define SetEnvironmentVariable(...) __imp_SetEnvironmentVariableW(__VA_ARGS__)
extern typeof(SetEnvironmentVariable) *const
__imp_SetEnvironmentVariableW __msabi;
extern typeof(SetEnvironmentVariable) *const __imp_SetEnvironmentVariableW
__msabi;
#define GetPriorityClass(...) __imp_GetPriorityClass(__VA_ARGS__)
extern typeof(GetPriorityClass) *const __imp_GetPriorityClass __msabi;
@ -17,3 +17,4 @@ extern typeof(GetCurrentProcessId) *const __imp_GetCurrentProcessId __msabi;
extern typeof(FormatMessage) *const __imp_FormatMessageW __msabi;
extern typeof(SetLastError) *const __imp_SetLastError __msabi;
extern typeof(FormatMessage) *const __imp_FormatMessage __msabi;

View file

@ -1,13 +1,13 @@
#define FreeEnvironmentStrings(...) __imp_FreeEnvironmentStringsW(__VA_ARGS__)
extern typeof(FreeEnvironmentStrings) *const
__imp_FreeEnvironmentStringsW __msabi;
extern typeof(FreeEnvironmentStrings) *const __imp_FreeEnvironmentStringsW
__msabi;
#define GetCommandLine(...) __imp_GetCommandLineW(__VA_ARGS__)
extern typeof(GetCommandLine) *const __imp_GetCommandLineW __msabi;
#define GetEnvironmentStrings(...) __imp_GetEnvironmentStringsW(__VA_ARGS__)
extern typeof(GetEnvironmentStrings) *const
__imp_GetEnvironmentStringsW __msabi;
extern typeof(GetEnvironmentStrings) *const __imp_GetEnvironmentStringsW
__msabi;
#define GetStdHandle(...) __imp_GetStdHandle(__VA_ARGS__)
extern typeof(GetStdHandle) *const __imp_GetStdHandle __msabi;
@ -23,8 +23,8 @@ extern typeof(WriteFile) *const __imp_WriteFile __msabi;
#define SetDefaultDllDirectories(...) \
__imp_SetDefaultDllDirectories(__VA_ARGS__)
extern typeof(SetDefaultDllDirectories) *const
__imp_SetDefaultDllDirectories __msabi;
extern typeof(SetDefaultDllDirectories) *const __imp_SetDefaultDllDirectories
__msabi;
#define GetCurrentProcess(...) __imp_GetCurrentProcess(__VA_ARGS__)
extern typeof(GetCurrentProcess) *const __imp_GetCurrentProcess __msabi;

View file

@ -0,0 +1 @@
extern typeof(WSAGetLastError) *const __imp_WSAGetLastError __msabi;

View file

@ -6,6 +6,7 @@
#include "libc/nt/struct/overlapped.h"
#include "libc/nt/struct/pollfd.h"
#include "libc/nt/struct/timeval.h"
#include "libc/nt/thunk/msabi.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
/* ░▓█████████████████████████████████████████████▓▒
@ -513,6 +514,9 @@ void GetAcceptExSockaddrs(
bool32 DisconnectEx(int64_t s, struct NtOverlapped *inout_opt_lpOverlapped,
uint32_t dwFlags, uint32_t dwReserved);
#if ShouldUseMsabiAttribute()
#include "libc/nt/thunk/winsock.inc"
#endif /* ShouldUseMsabiAttribute() */
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_NT_WINSOCK_H_ */

View file

@ -127,7 +127,7 @@ static int arch_prctl_xnu(int code, int64_t addr) {
}
}
static privileged dontinline int arch_prctl_openbsd(int code, int64_t addr) {
static dontinline int arch_prctl_openbsd(int code, int64_t addr) {
bool failed;
int64_t rax;
switch (code) {

View file

@ -1,7 +1,7 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2022 Justine Alexandra Roberts Tunney
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
@ -16,12 +16,22 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/intrin/bswap.h"
#include "libc/sock/sock.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/kprintf.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/stack.h"
#include "libc/runtime/symbols.internal.h"
/**
* Converts network to host short.
*/
uint16_t(ntohs)(uint16_t x) {
return bswap_16(x);
void ftrace_hook(void);
_Hide int ftrace_stackdigs;
textstartup int ftrace_install(void) {
if (GetSymbolTable()) {
ftrace_stackdigs = LengthInt64Thousands(GetStackSize());
return __hook(ftrace_hook, GetSymbolTable());
} else {
kprintf("error: --ftrace failed to open symbol table\n");
return -1;
}
}

View file

@ -27,7 +27,6 @@
#include "libc/runtime/internal.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/stack.h"
#include "libc/runtime/symbols.internal.h"
#include "libc/thread/tls.h"
#include "libc/thread/tls2.h"
@ -47,9 +46,7 @@
#define DETOUR_SKEW 8
#endif
void ftrace_hook(void);
static int g_stackdigs;
extern _Hide int ftrace_stackdigs;
static struct CosmoFtrace g_ftrace;
static privileged inline int GetNestingLevelImpl(struct StackFrame *frame) {
@ -73,9 +70,11 @@ static privileged inline int GetNestingLevel(struct CosmoFtrace *ft,
/**
* Prints name of function being called.
*
* We insert CALL instructions that point to this function, in the
* prologues of other functions. We assume those functions behave
* according to the System Five NexGen32e ABI.
* Whenever a function is called, ftrace_hook() will be called from the
* function prologue which saves the parameter registers and calls this
* function, which is responsible for logging the function call.
*
* @see ftrace_install()
*/
privileged void ftracer(void) {
uintptr_t fn;
@ -101,20 +100,10 @@ privileged void ftracer(void) {
fn = sf->addr + DETOUR_SKEW;
if (fn != ft->ft_lastaddr) {
stackuse = GetStackAddr() + GetStackSize() - (intptr_t)sf;
kprintf("%rFUN %6P %'13T %'*ld %*s%t\n", g_stackdigs, stackuse,
kprintf("%rFUN %6P %'13T %'*ld %*s%t\n", ftrace_stackdigs, stackuse,
GetNestingLevel(ft, sf) * 2, "", fn);
ft->ft_lastaddr = fn;
}
ft->ft_noreentry = false;
}
}
textstartup int ftrace_install(void) {
if (GetSymbolTable()) {
g_stackdigs = LengthInt64Thousands(GetStackSize());
return __hook(ftrace_hook, GetSymbolTable());
} else {
kprintf("error: --ftrace failed to open symbol table\n");
return -1;
}
}

View file

@ -1,7 +1,7 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2022 Justine Alexandra Roberts Tunney
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
@ -16,12 +16,41 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/intrin/bswap.h"
#include "libc/sock/sock.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/symbols.internal.h"
extern _Hide struct SymbolTable *__symtab;
/**
* Converts network to host long.
* Returns low index into symbol table for address.
*
* @param t if null will be auto-populated only if already open
* @return index or -1 if nothing found
*/
uint32_t(ntohl)(uint32_t x) {
return bswap_32(x);
noinstrument privileged int __get_symbol(struct SymbolTable *t, intptr_t a) {
// we need privileged because:
// kprintf is privileged and it depends on this
// we don't want function tracing because:
// function tracing depends on this function via kprintf
unsigned l, m, r, n, k;
if (!t && __symtab) {
t = __symtab;
}
if (t) {
l = 0;
r = n = t->count;
k = a - t->addr_base;
while (l < r) {
m = (l + r) >> 1;
if (t->symbols[m].y < k) {
l = m + 1;
} else {
r = m;
}
}
if (l < n && t->symbols[l].x <= k && k <= t->symbols[l].y) {
return l;
}
}
return -1;
}

View file

@ -142,37 +142,3 @@ struct SymbolTable *GetSymbolTable(void) {
pthread_spin_unlock(&g_lock);
return __symtab;
}
/**
* Returns low index into symbol table for address.
*
* @param t if null will be auto-populated only if already open
* @return index or -1 if nothing found
*/
noinstrument privileged int __get_symbol(struct SymbolTable *t, intptr_t a) {
// we need privileged because:
// kprintf is privileged and it depends on this
// we don't want function tracing because:
// function tracing depends on this function via kprintf
unsigned l, m, r, n, k;
if (!t && __symtab) {
t = __symtab;
}
if (t) {
l = 0;
r = n = t->count;
k = a - t->addr_base;
while (l < r) {
m = (l + r) >> 1;
if (t->symbols[m].y < k) {
l = m + 1;
} else {
r = m;
}
}
if (l < n && t->symbols[l].x <= k && k <= t->symbols[l].y) {
return l;
}
}
return -1;
}

View file

@ -68,7 +68,6 @@ static privileged void __morph_mprotect(void *addr, size_t size, int prot,
if (cf) ax = -ax;
if (ax == -EPERM) {
kprintf("error: need pledge(prot_exec) permission to code morph\n");
_Exit(26);
}
#endif
if (ax) notpossible;

View file

@ -78,7 +78,7 @@ void fpreset(void);
void *mmap(void *, uint64_t, int32_t, int32_t, int32_t, int64_t);
void *mremap(void *, size_t, size_t, int, ...);
int munmap(void *, uint64_t);
int mprotect(void *, uint64_t, int) privileged;
int mprotect(void *, uint64_t, int);
int msync(void *, size_t, int);
int mlock(const void *, size_t);
int munlock(const void *, size_t);

View file

@ -70,7 +70,6 @@ o/$(MODE)/libc/runtime/cosmo2.o: private \
o/$(MODE)/libc/runtime/ftracer.o: private \
CFLAGS += \
-x-no-pg \
$(MNO_FENTRY) \
-ffreestanding \
-fno-sanitize=all
@ -124,6 +123,14 @@ o/$(MODE)/libc/runtime/enable_tls.o: private \
-mcmodel=large
endif
# privileged functions
o/$(MODE)/libc/runtime/getsymbol.o \
o/$(MODE)/libc/runtime/enable_threads.o \
o/$(MODE)/libc/runtime/morph_tls.o: private \
CFLAGS += \
-ffreestanding \
-fno-sanitize=all
# these assembly files are safe to build on aarch64
o/$(MODE)/libc/runtime/init.o: libc/runtime/init.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $<

View file

@ -17,9 +17,8 @@
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/intrin/kprintf.h"
#include "libc/runtime/internal.h"
privileged noasan noinstrument void __stack_chk_fail(void) {
kprintf("stack smashed\n");
_Exitr(207);
__builtin_trap();
}

View file

@ -1,27 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2022 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/intrin/bswap.h"
#include "libc/sock/sock.h"
/**
* Converts network to host short.
*/
uint32_t(htonl)(uint32_t x) {
return bswap_32(x);
}

View file

@ -1,27 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2022 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/intrin/bswap.h"
#include "libc/sock/sock.h"
/**
* Converts host to network short.
*/
uint16_t(htons)(uint16_t x) {
return bswap_16(x);
}

View file

@ -166,16 +166,6 @@ int vfprintf_unlocked(FILE *, const char *, va_list)
cosmopolitan § standard i/o » optimizations
*/
#define getc(f) fgetc(f)
#define getwc(f) fgetwc(f)
#define putc(c, f) fputc(c, f)
#define putwc(c, f) fputwc(c, f)
#define getc_unlocked(f) fgetc_unlocked(f)
#define getwc_unlocked(f) fgetwc_unlocked(f)
#define putc_unlocked(c, f) fputc_unlocked(c, f)
#define putwc_unlocked(c, f) fputwc_unlocked(c, f)
#if defined(__GNUC__) && !defined(__STRICT_ANSI__)
/* clang-format off */
#define printf(FMT, ...) (printf)(PFLINK(FMT), ##__VA_ARGS__)

View file

@ -22,7 +22,7 @@
/**
* Returns address of errno variable.
*/
nocallersavedregisters errno_t *(__errno_location)(void) {
privileged nocallersavedregisters errno_t *(__errno_location)(void) {
if (!__tls_enabled) return &__errno;
return &__get_tls_privileged()->tib_errno;
}

View file

@ -90,7 +90,7 @@
static unsigned short klog_y = 0, klog_x = 0;
privileged void _klog_vga(const char *b, size_t n) {
void _klog_vga(const char *b, size_t n) {
struct Tty tty;
_vga_reinit(&tty, klog_y, klog_x, kTtyKlog);
_TtyWrite(&tty, b, n);