cosmopolitan/third_party/chibicc/chibicc.c

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

806 lines
22 KiB
C
Raw Permalink Normal View History

2023-06-18 12:39:31 +00:00
#include "third_party/chibicc/chibicc.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/siginfo.h"
#include "libc/calls/ucontext.h"
2023-06-18 12:39:31 +00:00
#include "libc/fmt/libgen.h"
#include "libc/mem/gc.h"
#include "libc/runtime/runtime.h"
#include "libc/sysv/consts/sig.h"
#include "libc/x/xasprintf.h"
2020-12-01 11:43:40 +00:00
Release Cosmopolitan v3.3 This change upgrades to GCC 12.3 and GNU binutils 2.42. The GNU linker appears to have changed things so that only a single de-duplicated str table is present in the binary, and it gets placed wherever the linker wants, regardless of what the linker script says. To cope with that we need to stop using .ident to embed licenses. As such, this change does significant work to revamp how third party licenses are defined in the codebase, using `.section .notice,"aR",@progbits`. This new GCC 12.3 toolchain has support for GNU indirect functions. It lets us support __target_clones__ for the first time. This is used for optimizing the performance of libc string functions such as strlen and friends so far on x86, by ensuring AVX systems favor a second codepath that uses VEX encoding. It shaves some latency off certain operations. It's a useful feature to have for scientific computing for the reasons explained by the test/libcxx/openmp_test.cc example which compiles for fifteen different microarchitectures. Thanks to the upgrades, it's now also possible to use newer instruction sets, such as AVX512FP16, VNNI. Cosmo now uses the %gs register on x86 by default for TLS. Doing it is helpful for any program that links `cosmo_dlopen()`. Such programs had to recompile their binaries at startup to change the TLS instructions. That's not great, since it means every page in the executable needs to be faulted. The work of rewriting TLS-related x86 opcodes, is moved to fixupobj.com instead. This is great news for MacOS x86 users, since we previously needed to morph the binary every time for that platform but now that's no longer necessary. The only platforms where we need fixup of TLS x86 opcodes at runtime are now Windows, OpenBSD, and NetBSD. On Windows we morph TLS to point deeper into the TIB, based on a TlsAlloc assignment, and on OpenBSD/NetBSD we morph %gs back into %fs since the kernels do not allow us to specify a value for the %gs register. OpenBSD users are now required to use APE Loader to run Cosmo binaries and assimilation is no longer possible. OpenBSD kernel needs to change to allow programs to specify a value for the %gs register, or it needs to stop marking executable pages loaded by the kernel as mimmutable(). This release fixes __constructor__, .ctor, .init_array, and lastly the .preinit_array so they behave the exact same way as glibc. We no longer use hex constants to define math.h symbols like M_PI.
2024-02-20 19:12:09 +00:00
__notice(chibicc_notice, "\
chibicc (MIT/ISC License)\n\
Copyright 2019 Rui Ueyama\n\
Copyright 2020 Justine Alexandra Roberts Tunney");
2020-12-01 11:43:40 +00:00
typedef enum {
FILE_NONE,
FILE_C,
FILE_ASM,
FILE_ASM_CPP,
2020-12-01 11:43:40 +00:00
FILE_OBJ,
FILE_AR,
FILE_DSO,
} FileType;
2020-12-09 12:00:48 +00:00
bool opt_common = true;
bool opt_data_sections;
bool opt_fentry;
bool opt_function_sections;
bool opt_no_builtin;
bool opt_nop_mcount;
bool opt_pg;
2020-12-09 12:00:48 +00:00
bool opt_pic;
bool opt_popcnt;
bool opt_record_mcount;
bool opt_sse3;
bool opt_sse4;
bool opt_verbose;
2020-12-01 11:43:40 +00:00
2020-12-09 12:00:48 +00:00
static bool opt_A;
2020-12-01 11:43:40 +00:00
static bool opt_E;
2020-12-26 10:09:07 +00:00
static bool opt_J;
static bool opt_P;
2020-12-01 11:43:40 +00:00
static bool opt_M;
static bool opt_MD;
static bool opt_MMD;
static bool opt_MP;
static bool opt_S;
static bool opt_c;
static bool opt_cc1;
static bool opt_hash_hash_hash;
static bool opt_static;
2020-12-24 07:42:56 +00:00
static bool opt_save_temps;
2020-12-01 11:43:40 +00:00
static char *opt_MF;
static char *opt_MT;
static char *opt_o;
static FileType opt_x;
static StringArray opt_include;
2020-12-01 11:43:40 +00:00
StringArray include_paths;
2020-12-01 11:43:40 +00:00
static StringArray ld_extra_args;
static StringArray as_extra_args;
2020-12-01 11:43:40 +00:00
static StringArray std_include_paths;
char *base_file;
static char *output_file;
static StringArray input_paths;
char **chibicc_tmpfiles;
2020-12-01 11:43:40 +00:00
static const char kChibiccVersion[] = "\
chibicc (cosmopolitan) 9.0.0\n\
copyright 2019 rui ueyama\n\
copyright 2020 justine alexandra roberts tunney\n";
static void chibicc_version(void) {
xwrite(1, kChibiccVersion, sizeof(kChibiccVersion) - 1);
_Exit(0);
}
static void chibicc_usage(int status) {
char *p;
size_t n;
p = xslurp("/zip/third_party/chibicc/help.txt", &n);
__paginate(1, p);
_Exit(status);
2020-12-01 11:43:40 +00:00
}
void chibicc_cleanup(void) {
size_t i;
if (chibicc_tmpfiles && !opt_save_temps) {
for (i = 0; chibicc_tmpfiles[i]; i++) {
unlink(chibicc_tmpfiles[i]);
}
}
2020-12-09 12:00:48 +00:00
}
2020-12-01 11:43:40 +00:00
static bool take_arg(char *arg) {
char *x[] = {"-o", "-I", "-idirafter", "-include",
"-x", "-MF", "-MT", "-Xlinker"};
for (int i = 0; i < sizeof(x) / sizeof(*x); i++) {
if (!strcmp(arg, x[i])) {
return true;
}
}
2020-12-01 11:43:40 +00:00
return false;
}
static void add_default_include_paths(char *argv0) {
// We expect that chibicc-specific include files are installed
// to ./include relative to argv[0].
/* char *buf = calloc(1, strlen(argv0) + 10); */
/* sprintf(buf, "%s/include", dirname(strdup(argv0))); */
/* strarray_push(&include_paths, buf); */
2020-12-01 11:43:40 +00:00
// Add standard include paths.
/* strarray_push(&include_paths, "."); */
strarray_push(&include_paths, "/zip/.c");
2020-12-01 11:43:40 +00:00
// Keep a copy of the standard include paths for -MMD option.
for (int i = 0; i < include_paths.len; i++) {
2020-12-01 11:43:40 +00:00
strarray_push(&std_include_paths, include_paths.data[i]);
}
2020-12-01 11:43:40 +00:00
}
static void define(char *str) {
char *eq = strchr(str, '=');
if (eq) {
2020-12-01 11:43:40 +00:00
define_macro(strndup(str, eq - str), eq + 1);
} else {
2020-12-01 11:43:40 +00:00
define_macro(str, "1");
}
2020-12-01 11:43:40 +00:00
}
static FileType parse_opt_x(char *s) {
if (!strcmp(s, "c")) return FILE_C;
if (!strcmp(s, "assembler")) return FILE_ASM;
if (!strcmp(s, "assembler-with-cpp")) return FILE_ASM_CPP;
2020-12-01 11:43:40 +00:00
if (!strcmp(s, "none")) return FILE_NONE;
error("<command line>: unknown argument for -x: %s", s);
}
static char *quote_makefile(char *s) {
char *buf = calloc(1, strlen(s) * 2 + 1);
for (int i = 0, j = 0; s[i]; i++) {
switch (s[i]) {
case '$':
buf[j++] = '$';
buf[j++] = '$';
break;
case '#':
buf[j++] = '\\';
buf[j++] = '#';
break;
case ' ':
case '\t':
for (int k = i - 1; k >= 0 && s[k] == '\\'; k--) buf[j++] = '\\';
buf[j++] = '\\';
buf[j++] = s[i];
break;
default:
buf[j++] = s[i];
break;
}
}
return buf;
}
static void PrintMemoryUsage(void) {
struct mallinfo mi;
2020-12-24 07:42:56 +00:00
malloc_trim(0);
mi = mallinfo();
2020-12-09 21:53:02 +00:00
fprintf(stderr, "\n");
fprintf(stderr, "allocated %,ld bytes of memory\n", mi.arena);
2020-12-09 21:53:02 +00:00
fprintf(stderr, "allocated %,ld nodes (%,ld bytes)\n", alloc_node_count,
sizeof(Node) * alloc_node_count);
fprintf(stderr, "allocated %,ld tokens (%,ld bytes)\n", alloc_token_count,
sizeof(Token) * alloc_token_count);
fprintf(stderr, "allocated %,ld objs (%,ld bytes)\n", alloc_obj_count,
sizeof(Obj) * alloc_obj_count);
fprintf(stderr, "allocated %,ld types (%,ld bytes)\n", alloc_type_count,
sizeof(Type) * alloc_type_count);
fprintf(stderr, "chibicc hashmap hits %,ld\n", chibicc_hashmap_hits);
fprintf(stderr, "chibicc hashmap miss %,ld\n", chibicc_hashmap_miss);
fprintf(stderr, "as hashmap hits %,ld\n", as_hashmap_hits);
fprintf(stderr, "as hashmap miss %,ld\n", as_hashmap_miss);
}
2020-12-09 12:00:48 +00:00
static void strarray_push_comma(StringArray *a, char *s) {
char *p;
for (; *s++ == ','; s = p) {
p = strchrnul(s, ',');
strarray_push(a, strndup(s, p - s));
}
}
2020-12-01 11:43:40 +00:00
static void parse_args(int argc, char **argv) {
// Make sure that all command line options that take an argument
// have an argument.
2020-12-09 12:00:48 +00:00
for (int i = 1; i < argc; i++) {
if (take_arg(argv[i])) {
if (!argv[++i]) {
chibicc_usage(1);
2020-12-09 12:00:48 +00:00
}
}
}
StringArray idirafter = {0};
2020-12-01 11:43:40 +00:00
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-###")) {
opt_verbose = opt_hash_hash_hash = true;
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-cc1")) {
2020-12-01 11:43:40 +00:00
opt_cc1 = true;
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "--help")) {
chibicc_usage(0);
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "--version")) {
chibicc_version();
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-v")) {
opt_verbose = true;
atexit(PrintMemoryUsage);
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-o")) {
2020-12-01 11:43:40 +00:00
opt_o = argv[++i];
} else if (startswith(argv[i], "-o")) {
2020-12-01 11:43:40 +00:00
opt_o = argv[i] + 2;
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-S")) {
2020-12-01 11:43:40 +00:00
opt_S = true;
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-fcommon")) {
opt_common = true;
} else if (!strcmp(argv[i], "-fno-common")) {
opt_common = false;
} else if (!strcmp(argv[i], "-fno-builtin")) {
opt_no_builtin = true;
} else if (!strcmp(argv[i], "-save-temps")) {
opt_save_temps = true;
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-c")) {
2020-12-01 11:43:40 +00:00
opt_c = true;
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-E")) {
2020-12-01 11:43:40 +00:00
opt_E = true;
2020-12-26 10:09:07 +00:00
} else if (!strcmp(argv[i], "-J")) {
opt_J = true;
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-A")) {
opt_A = true;
} else if (!strcmp(argv[i], "-P")) {
opt_P = true;
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-I")) {
strarray_push(&include_paths, argv[++i]);
} else if (startswith(argv[i], "-I")) {
2020-12-01 11:43:40 +00:00
strarray_push(&include_paths, argv[i] + 2);
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-iquote")) {
strarray_push(&include_paths, argv[++i]);
} else if (startswith(argv[i], "-iquote")) {
2020-12-09 12:00:48 +00:00
strarray_push(&include_paths, argv[i] + strlen("-iquote"));
} else if (!strcmp(argv[i], "-isystem")) {
strarray_push(&include_paths, argv[++i]);
} else if (startswith(argv[i], "-isystem")) {
2020-12-09 12:00:48 +00:00
strarray_push(&include_paths, argv[i] + strlen("-isystem"));
} else if (!strcmp(argv[i], "-D")) {
2020-12-01 11:43:40 +00:00
define(argv[++i]);
} else if (startswith(argv[i], "-D")) {
2020-12-01 11:43:40 +00:00
define(argv[i] + 2);
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-U")) {
2020-12-01 11:43:40 +00:00
undef_macro(argv[++i]);
2020-12-09 12:00:48 +00:00
} else if (!strncmp(argv[i], "-U", 2)) {
2020-12-01 11:43:40 +00:00
undef_macro(argv[i] + 2);
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-include")) {
2020-12-01 11:43:40 +00:00
strarray_push(&opt_include, argv[++i]);
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-x")) {
2020-12-01 11:43:40 +00:00
opt_x = parse_opt_x(argv[++i]);
2020-12-09 12:00:48 +00:00
} else if (!strncmp(argv[i], "-x", 2)) {
2020-12-01 11:43:40 +00:00
opt_x = parse_opt_x(argv[i] + 2);
} else if (startswith(argv[i], "-Wa")) {
strarray_push_comma(&as_extra_args, argv[i] + 3);
} else if (startswith(argv[i], "-Wl")) {
strarray_push_comma(&ld_extra_args, argv[i] + 3);
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-Xassembler")) {
strarray_push(&as_extra_args, argv[++i]);
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-Xlinker")) {
2020-12-01 11:43:40 +00:00
strarray_push(&ld_extra_args, argv[++i]);
2020-12-09 12:00:48 +00:00
} else if (!strncmp(argv[i], "-l", 2) || !strncmp(argv[i], "-Wl,", 4)) {
strarray_push(&input_paths, argv[i]);
} else if (!strcmp(argv[i], "-s")) {
2020-12-01 11:43:40 +00:00
strarray_push(&ld_extra_args, "-s");
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-M")) {
2020-12-01 11:43:40 +00:00
opt_M = true;
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-MF")) {
2020-12-01 11:43:40 +00:00
opt_MF = argv[++i];
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-MP")) {
2020-12-01 11:43:40 +00:00
opt_MP = true;
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-MT")) {
if (!opt_MT) {
2020-12-01 11:43:40 +00:00
opt_MT = argv[++i];
2020-12-09 12:00:48 +00:00
} else {
opt_MT = xasprintf("%s %s", opt_MT, argv[++i]);
2020-12-09 12:00:48 +00:00
}
} else if (!strcmp(argv[i], "-MD")) {
2020-12-01 11:43:40 +00:00
opt_MD = true;
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-MQ")) {
if (!opt_MT) {
2020-12-01 11:43:40 +00:00
opt_MT = quote_makefile(argv[++i]);
2020-12-09 12:00:48 +00:00
} else {
opt_MT = xasprintf("%s %s", opt_MT, quote_makefile(argv[++i]));
2020-12-09 12:00:48 +00:00
}
} else if (!strcmp(argv[i], "-MMD")) {
2020-12-01 11:43:40 +00:00
opt_MD = opt_MMD = true;
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-fpie") || !strcmp(argv[i], "-fpic") ||
!strcmp(argv[i], "-fPIC")) {
opt_pic = true;
} else if (!strcmp(argv[i], "-pg")) {
opt_pg = true;
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-mfentry")) {
opt_fentry = true;
} else if (!strcmp(argv[i], "-ffunction-sections")) {
opt_function_sections = true;
} else if (!strcmp(argv[i], "-fdata-sections")) {
opt_data_sections = true;
} else if (!strcmp(argv[i], "-mrecord-mcount")) {
opt_record_mcount = true;
} else if (!strcmp(argv[i], "-mnop-mcount")) {
opt_nop_mcount = true;
} else if (!strcmp(argv[i], "-msse3")) {
opt_sse3 = true;
} else if (!strcmp(argv[i], "-msse4") || !strcmp(argv[i], "-msse4.2") ||
!strcmp(argv[i], "-msse4.1")) {
opt_sse4 = true;
} else if (!strcmp(argv[i], "-mpopcnt")) {
opt_popcnt = true;
} else if (!strcmp(argv[i], "-cc1-input")) {
2020-12-01 11:43:40 +00:00
base_file = argv[++i];
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-cc1-output")) {
2020-12-01 11:43:40 +00:00
output_file = argv[++i];
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-idirafter")) {
2020-12-01 11:43:40 +00:00
strarray_push(&idirafter, argv[i++]);
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-static")) {
2020-12-01 11:43:40 +00:00
opt_static = true;
strarray_push(&ld_extra_args, "-static");
2020-12-09 12:00:48 +00:00
} else if (!strcmp(argv[i], "-shared")) {
error("-shared not supported");
} else if (!strcmp(argv[i], "-L")) {
2020-12-01 11:43:40 +00:00
strarray_push(&ld_extra_args, "-L");
strarray_push(&ld_extra_args, argv[++i]);
} else if (startswith(argv[i], "-L")) {
2020-12-01 11:43:40 +00:00
strarray_push(&ld_extra_args, "-L");
strarray_push(&ld_extra_args, argv[i] + 2);
2020-12-09 12:00:48 +00:00
} else {
if (argv[i][0] == '-' && argv[i][1]) {
/* compiler should not whine about the flags race */
if (opt_verbose) {
fprintf(stderr, "unknown argument: %s\n", argv[i]);
}
} else {
strarray_push(&input_paths, argv[i]);
}
}
2020-12-01 11:43:40 +00:00
}
2020-12-09 12:00:48 +00:00
for (int i = 0; i < idirafter.len; i++) {
2020-12-01 11:43:40 +00:00
strarray_push(&include_paths, idirafter.data[i]);
2020-12-09 12:00:48 +00:00
}
if (!input_paths.len) {
error("no input files");
}
2020-12-01 11:43:40 +00:00
// -E implies that the input is the C macro language.
if (opt_E) opt_x = FILE_C;
}
static FILE *open_file(char *path) {
if (!path || strcmp(path, "-") == 0) return stdout;
FILE *out = fopen(path, "w");
if (!out) error("cannot open output file: %s: %s", path, strerror(errno));
return out;
}
// Replace file extension
static char *replace_extn(char *tmpl, char *extn) {
char *filename = basename(strdup(tmpl));
int len1 = strlen(filename);
int len2 = strlen(extn);
char *buf = calloc(1, len1 + len2 + 2);
char *dot = strrchr(filename, '.');
if (dot) *dot = '\0';
sprintf(buf, "%s%s", filename, extn);
return buf;
}
static char *create_tmpfile(void) {
Make improvements - Every unit test now passes on Apple Silicon. The final piece of this puzzle was porting our POSIX threads cancelation support, since that works differently on ARM64 XNU vs. AMD64. Our semaphore support on Apple Silicon is also superior now compared to AMD64, thanks to the grand central dispatch library which lets *NSYNC locks go faster. - The Cosmopolitan runtime is now more stable, particularly on Windows. To do this, thread local storage is mandatory at all runtime levels, and the innermost packages of the C library is no longer being built using ASAN. TLS is being bootstrapped with a 128-byte TIB during the process startup phase, and then later on the runtime re-allocates it either statically or dynamically to support code using _Thread_local. fork() and execve() now do a better job cooperating with threads. We can now check how much stack memory is left in the process or thread when functions like kprintf() / execve() etc. call alloca(), so that ENOMEM can be raised, reduce a buffer size, or just print a warning. - POSIX signal emulation is now implemented the same way kernels do it with pthread_kill() and raise(). Any thread can interrupt any other thread, regardless of what it's doing. If it's blocked on read/write then the killer thread will cancel its i/o operation so that EINTR can be returned in the mark thread immediately. If it's doing a tight CPU bound operation, then that's also interrupted by the signal delivery. Signal delivery works now by suspending a thread and pushing context data structures onto its stack, and redirecting its execution to a trampoline function, which calls SetThreadContext(GetCurrentThread()) when it's done. - We're now doing a better job managing locks and handles. On NetBSD we now close semaphore file descriptors in forked children. Semaphores on Windows can now be canceled immediately, which means mutexes/condition variables will now go faster. Apple Silicon semaphores can be canceled too. We're now using Apple's pthread_yield() funciton. Apple _nocancel syscalls are now used on XNU when appropriate to ensure pthread_cancel requests aren't lost. The MbedTLS library has been updated to support POSIX thread cancelations. See tool/build/runitd.c for an example of how it can be used for production multi-threaded tls servers. Handles on Windows now leak less often across processes. All i/o operations on Windows are now overlapped, which means file pointers can no longer be inherited across dup() and fork() for the time being. - We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4() which means, for example, that posix_spawn() now goes 3x faster. POSIX spawn is also now more correct. Like Musl, it's now able to report the failure code of execve() via a pipe although our approach favors using shared memory to do that on systems that have a true vfork() function. - We now spawn a thread to deliver SIGALRM to threads when setitimer() is used. This enables the most precise wakeups the OS makes possible. - The Cosmopolitan runtime now uses less memory. On NetBSD for example, it turned out the kernel would actually commit the PT_GNU_STACK size which caused RSS to be 6mb for every process. Now it's down to ~4kb. On Apple Silicon, we reduce the mandatory upstream thread size to the smallest possible size to reduce the memory overhead of Cosmo threads. The examples directory has a program called greenbean which can spawn a web server on Linux with 10,000 worker threads and have the memory usage of the process be ~77mb. The 1024 byte overhead of POSIX-style thread-local storage is now optional; it won't be allocated until the pthread_setspecific/getspecific functions are called. On Windows, the threads that get spawned which are internal to the libc implementation use reserve rather than commit memory, which shaves a few hundred kb. - sigaltstack() is now supported on Windows, however it's currently not able to be used to handle stack overflows, since crash signals are still generated by WIN32. However the crash handler will still switch to the alt stack, which is helpful in environments with tiny threads. - Test binaries are now smaller. Many of the mandatory dependencies of the test runner have been removed. This ensures many programs can do a better job only linking the the thing they're testing. This caused the test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb - long double is no longer used in the implementation details of libc, except in the APIs that define it. The old code that used long double for time (instead of struct timespec) has now been thoroughly removed. - ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing backtraces itself, it'll just print a command you can run on the shell using our new `cosmoaddr2line` program to view the backtrace. - Crash report signal handling now works in a much better way. Instead of terminating the process, it now relies on SA_RESETHAND so that the default SIG_IGN behavior can terminate the process if necessary. - Our pledge() functionality has now been fully ported to AARCH64 Linux.
2023-09-19 03:44:45 +00:00
char *path = xjoinpaths(__get_tmpdir(), "chibicc-XXXXXX");
2020-12-01 11:43:40 +00:00
int fd = mkstemp(path);
Prove that Makefile is fully defined The whole repository is now buildable with GNU Make Landlock sandboxing. This proves that no Makefile targets exist which touch files other than their declared prerequisites. In order to do this, we had to: 1. Stop code morphing GCC output in package.com and instead run a newly introduced FIXUPOBJ.COM command after GCC invocations. 2. Disable all the crumby Python unit tests that do things like create files in the current directory, or rename() files between folders. This ended up being a lot of tests, but most of them are still ok. 3. Introduce an .UNSANDBOXED variable to GNU Make to disable Landlock. We currently only do this for things like `make tags`. 4. This change deletes some GNU Make code that was preventing the execve() optimization from working. This means it should no longer be necessary in most cases for command invocations to be indirected through the cocmd interpreter. 5. Missing dependencies had to be declared in certain places, in cases where they couldn't be automatically determined by MKDEPS.COM 6. The libcxx header situation has finally been tamed. One of the things that makes this difficult is MKDEPS.COM only wants to consider the first 64kb of a file, in order to go fast. But libcxx likes to have #include lines buried after huge documentation. 7. An .UNVEIL variable has been introduced to GNU Make just in case we ever wish to explicitly specify additional things that need to be whitelisted which aren't strictly prerequisites. This works in a manner similar to the recently introduced .EXTRA_PREREQS feature. There's now a new build/bootstrap/make.com prebuilt binary available. It should no longer be possible to write invalid Makefile code.
2022-08-06 10:51:50 +00:00
if (fd == -1) error("%s: mkstemp failed: %s", path, strerror(errno));
2020-12-01 11:43:40 +00:00
close(fd);
static int len = 2;
chibicc_tmpfiles = realloc(chibicc_tmpfiles, sizeof(char *) * len);
chibicc_tmpfiles[len - 2] = path;
chibicc_tmpfiles[len - 1] = NULL;
2020-12-01 11:43:40 +00:00
len++;
return path;
}
2020-12-26 10:09:07 +00:00
static void handle_exit(bool ok) {
if (!ok) {
opt_save_temps = true;
exit(1);
}
}
static bool NeedsShellQuotes(const char *s) {
if (*s) {
for (;;) {
switch (*s++ & 255) {
case 0:
return false;
case '-':
case '.':
case '/':
case '_':
case '0' ... '9':
case 'A' ... 'Z':
case 'a' ... 'z':
break;
default:
return true;
}
}
} else {
return true;
}
}
2020-12-26 10:09:07 +00:00
static bool run_subprocess(char **argv) {
int rc, ws;
size_t i, j;
if (opt_verbose) {
for (i = 0; argv[i]; i++) {
fputc(' ', stderr);
if (opt_hash_hash_hash && NeedsShellQuotes(argv[i])) {
fputc('\'', stderr);
for (j = 0; argv[i][j]; ++j) {
if (argv[i][j] != '\'') {
fputc(argv[i][j], stderr);
} else {
fputs("'\"'\"'", stderr);
}
}
fputc('\'', stderr);
} else {
fputs(argv[i], stderr);
}
}
fputc('\n', stderr);
2020-12-01 11:43:40 +00:00
}
if (!vfork()) {
2020-12-01 11:43:40 +00:00
// Child process. Run a new command.
execvp(argv[0], argv);
_Exit(1);
2020-12-01 11:43:40 +00:00
}
// Wait for the child process to finish.
do rc = wait(&ws);
while (rc == -1 && errno == EINTR);
return WIFEXITED(ws) && WEXITSTATUS(ws) == 0;
2020-12-01 11:43:40 +00:00
}
2020-12-26 10:09:07 +00:00
static bool run_cc1(int argc, char **argv, char *input, char *output) {
2020-12-01 11:43:40 +00:00
char **args = calloc(argc + 10, sizeof(char *));
memcpy(args, argv, argc * sizeof(char *));
args[argc++] = "-cc1";
if (input) {
args[argc++] = "-cc1-input";
args[argc++] = input;
}
if (output) {
args[argc++] = "-cc1-output";
args[argc++] = output;
}
2020-12-26 10:09:07 +00:00
return run_subprocess(args);
2020-12-01 11:43:40 +00:00
}
2020-12-09 12:00:48 +00:00
static void print_token(FILE *out, Token *tok) {
switch (tok->kind) {
case TK_STR:
switch (tok->ty->base->size) {
case 1:
fprintf(out, "%`'.*s", tok->ty->array_len - 1, tok->str);
break;
case 2:
fprintf(out, "%`'.*hs", tok->ty->array_len - 1, tok->str);
break;
case 4:
fprintf(out, "%`'.*ls", tok->ty->array_len - 1, tok->str);
break;
default:
UNREACHABLE();
}
break;
default:
fprintf(out, "%.*s", tok->len, tok->loc);
break;
}
}
2020-12-01 11:43:40 +00:00
static void print_tokens(Token *tok) {
FILE *out = open_file(opt_o ? opt_o : "-");
int line = 1;
for (; tok->kind != TK_EOF; tok = tok->next) {
if (line > 1 && tok->at_bol) fprintf(out, "\n");
if (tok->has_space && !tok->at_bol) fprintf(out, " ");
2020-12-09 12:00:48 +00:00
print_token(out, tok);
2020-12-01 11:43:40 +00:00
line++;
}
fprintf(out, "\n");
}
static bool in_std_include_path(char *path) {
for (int i = 0; i < std_include_paths.len; i++) {
char *dir = std_include_paths.data[i];
int len = strlen(dir);
if (strncmp(dir, path, len) == 0 && path[len] == '/') return true;
}
return false;
}
// If -M options is given, the compiler write a list of input files to
// stdout in a format that "make" command can read. This feature is
// used to automate file dependency management.
static void print_dependencies(void) {
char *path;
if (opt_MF) {
2020-12-01 11:43:40 +00:00
path = opt_MF;
} else if (opt_MD) {
2020-12-01 11:43:40 +00:00
path = replace_extn(opt_o ? opt_o : base_file, ".d");
} else if (opt_o) {
2020-12-01 11:43:40 +00:00
path = opt_o;
} else {
2020-12-01 11:43:40 +00:00
path = "-";
}
2020-12-01 11:43:40 +00:00
FILE *out = open_file(path);
if (opt_MT)
fprintf(out, "%s:", opt_MT);
else
fprintf(out, "%s:", quote_makefile(replace_extn(base_file, ".o")));
File **files = get_input_files();
for (int i = 0; files[i]; i++) {
if (opt_MMD && in_std_include_path(files[i]->name)) continue;
fprintf(out, " \\\n\t%s", files[i]->name);
2020-12-01 11:43:40 +00:00
}
fprintf(out, "\n\n");
if (opt_MP) {
for (int i = 1; files[i]; i++) {
if (opt_MMD && in_std_include_path(files[i]->name)) continue;
fprintf(out, "%s:\n\n", quote_makefile(files[i]->name));
}
}
}
static Token *must_tokenize_file(char *path) {
Token *tok = tokenize_file(path);
if (!tok) error("%s: %s", path, strerror(errno));
return tok;
}
static Token *append_tokens(Token *tok1, Token *tok2) {
if (!tok1 || tok1->kind == TK_EOF) return tok2;
Token *t = tok1;
while (t->next->kind != TK_EOF) t = t->next;
t->next = tok2;
return tok1;
}
static FileType get_file_type(const char *filename) {
if (opt_x != FILE_NONE) return opt_x;
if (endswith(filename, ".a")) return FILE_AR;
if (endswith(filename, ".o")) return FILE_OBJ;
if (endswith(filename, ".c")) return FILE_C;
if (endswith(filename, ".s")) return FILE_ASM;
if (endswith(filename, ".S")) return FILE_ASM_CPP;
error("<command line>: unknown file extension: %s", filename);
}
2020-12-01 11:43:40 +00:00
static void cc1(void) {
FileType ft;
2020-12-01 11:43:40 +00:00
Token *tok = NULL;
ft = get_file_type(base_file);
if (opt_J && (ft == FILE_ASM || ft == FILE_ASM_CPP)) {
output_javadown_asm(output_file, base_file);
return;
}
2020-12-01 11:43:40 +00:00
// Process -include option
for (int i = 0; i < opt_include.len; i++) {
char *incl = opt_include.data[i];
char *path;
if (fileexists(incl)) {
2020-12-01 11:43:40 +00:00
path = incl;
} else {
path = search_include_paths(incl);
if (!path) error("-include: %s: %s", incl, strerror(errno));
}
Token *tok2 = must_tokenize_file(path);
tok = append_tokens(tok, tok2);
}
// Tokenize and parse.
Token *tok2 = must_tokenize_file(base_file);
tok = append_tokens(tok, tok2);
tok = preprocess(tok);
// If -M or -MD are given, print file dependencies.
if (opt_M || opt_MD) {
print_dependencies();
if (opt_M) return;
}
// If -E is given, print out preprocessed C code as a result.
if (opt_E || ft == FILE_ASM_CPP) {
2020-12-01 11:43:40 +00:00
print_tokens(tok);
return;
}
Obj *prog = parse(tok);
2020-12-09 12:00:48 +00:00
if (opt_A) {
print_ast(stdout, prog);
return;
}
2020-12-26 10:09:07 +00:00
if (opt_J) {
output_javadown(output_file, prog);
return;
}
if (opt_P) {
output_bindings_python(output_file, prog, tok2);
return;
}
2020-12-01 11:43:40 +00:00
FILE *out = open_file(output_file);
codegen(prog, out);
fclose(out);
}
static int CountArgv(char **argv) {
int n = 0;
while (*argv++) ++n;
return n;
}
2020-12-01 11:43:40 +00:00
static void assemble(char *input, char *output) {
char *as = getenv("AS");
if (!as || !*as) as = "as";
StringArray arr = {0};
strarray_push(&arr, as);
strarray_push(&arr, "-W");
strarray_push(&arr, "-I.");
strarray_push(&arr, "-c");
for (int i = 0; i < as_extra_args.len; i++) {
strarray_push(&arr, as_extra_args.data[i]);
}
strarray_push(&arr, input);
strarray_push(&arr, "-o");
strarray_push(&arr, output);
if (1) {
bool kludge = opt_save_temps;
opt_save_temps = true;
Assembler(CountArgv(arr.data), arr.data);
opt_save_temps = kludge;
} else {
handle_exit(run_subprocess(arr.data));
}
2020-12-01 11:43:40 +00:00
}
static void run_linker(StringArray *inputs, char *output) {
char *ld = getenv("LD");
if (!ld || !*ld) ld = "ld";
StringArray arr = {0};
strarray_push(&arr, ld);
2020-12-01 11:43:40 +00:00
strarray_push(&arr, "-m");
strarray_push(&arr, "elf_x86_64");
strarray_push(&arr, "-z");
strarray_push(&arr, "max-page-size=0x1000");
strarray_push(&arr, "-static");
2020-12-09 12:00:48 +00:00
strarray_push(&arr, "-nostdlib");
strarray_push(&arr, "--gc-sections");
strarray_push(&arr, "--build-id=none");
strarray_push(&arr, "--no-dynamic-linker");
/* strarray_push(&arr, "-T"); */
/* strarray_push(&arr, LDS); */
/* strarray_push(&arr, APE); */
/* strarray_push(&arr, CRT); */
for (int i = 0; i < ld_extra_args.len; i++) {
2020-12-01 11:43:40 +00:00
strarray_push(&arr, ld_extra_args.data[i]);
}
for (int i = 0; i < inputs->len; i++) {
strarray_push(&arr, inputs->data[i]);
}
strarray_push(&arr, "-o");
strarray_push(&arr, output);
2020-12-26 10:09:07 +00:00
handle_exit(run_subprocess(arr.data));
2020-12-01 11:43:40 +00:00
}
static void OnCtrlC(int sig, siginfo_t *si, void *ctx) {
exit(1);
}
2020-12-19 19:21:04 +00:00
int chibicc(int argc, char **argv) {
#ifndef NDEBUG
ShowCrashReports();
#endif
atexit(chibicc_cleanup);
sigaction(SIGINT, &(struct sigaction){.sa_sigaction = OnCtrlC}, NULL);
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-cc1")) {
opt_cc1 = true;
break;
}
}
if (opt_cc1) init_macros();
2020-12-01 11:43:40 +00:00
parse_args(argc, argv);
if (opt_cc1) {
init_macros_conditional();
2020-12-01 11:43:40 +00:00
add_default_include_paths(argv[0]);
cc1();
return 0;
}
2020-12-09 12:00:48 +00:00
if (input_paths.len > 1 && opt_o && (opt_c || opt_S | opt_E)) {
2020-12-01 11:43:40 +00:00
error("cannot specify '-o' with '-c,' '-S' or '-E' with multiple files");
2020-12-09 12:00:48 +00:00
}
StringArray ld_args = {0};
StringArray dox_args = {0};
2020-12-01 11:43:40 +00:00
for (int i = 0; i < input_paths.len; i++) {
char *input = input_paths.data[i];
if (!strncmp(input, "-l", 2)) {
strarray_push(&ld_args, input);
continue;
}
if (!strncmp(input, "-Wl,", 4)) {
char *s = strdup(input + 4);
char *arg = strtok(s, ",");
while (arg) {
strarray_push(&ld_args, arg);
arg = strtok(NULL, ",");
}
continue;
}
char *output;
if (opt_o) {
2020-12-01 11:43:40 +00:00
output = opt_o;
} else if (opt_S) {
2020-12-01 11:43:40 +00:00
output = replace_extn(input, ".s");
} else {
2020-12-01 11:43:40 +00:00
output = replace_extn(input, ".o");
}
2020-12-01 11:43:40 +00:00
FileType type = get_file_type(input);
// Handle .o or .a
if (type == FILE_OBJ || type == FILE_AR || type == FILE_DSO) {
strarray_push(&ld_args, input);
continue;
}
// Dox
if (opt_J) {
if (opt_c) {
handle_exit(run_cc1(argc, argv, input, output));
} else {
char *tmp = create_tmpfile();
if (run_cc1(argc, argv, input, tmp)) {
strarray_push(&dox_args, tmp);
}
}
continue;
}
2020-12-01 11:43:40 +00:00
// Handle .s
if (type == FILE_ASM) {
if (!opt_S) {
assemble(input, output);
}
2020-12-01 11:43:40 +00:00
continue;
}
2020-12-09 12:00:48 +00:00
assert(type == FILE_C || type == FILE_ASM_CPP);
// Just print ast.
if (opt_A) {
handle_exit(run_cc1(argc, argv, input, NULL));
continue;
}
2020-12-01 11:43:40 +00:00
// Just preprocess
if (opt_E || opt_M) {
2020-12-26 10:09:07 +00:00
handle_exit(run_cc1(argc, argv, input, NULL));
2020-12-01 11:43:40 +00:00
continue;
}
// Python Bindings
if (opt_P) {
handle_exit(run_cc1(argc, argv, input, opt_o ? opt_o : "/dev/stdout"));
continue;
}
2020-12-01 11:43:40 +00:00
// Compile
if (opt_S) {
2020-12-26 10:09:07 +00:00
handle_exit(run_cc1(argc, argv, input, output));
2020-12-01 11:43:40 +00:00
continue;
}
// Compile and assemble
if (opt_c) {
char *tmp = create_tmpfile();
2020-12-26 10:09:07 +00:00
handle_exit(run_cc1(argc, argv, input, tmp));
2020-12-01 11:43:40 +00:00
assemble(tmp, output);
continue;
}
// Compile, assemble and link
char *tmp1 = create_tmpfile();
char *tmp2 = create_tmpfile();
2020-12-26 10:09:07 +00:00
handle_exit(run_cc1(argc, argv, input, tmp1));
2020-12-01 11:43:40 +00:00
assemble(tmp1, tmp2);
strarray_push(&ld_args, tmp2);
continue;
}
if (ld_args.len > 0) {
run_linker(&ld_args, opt_o ? opt_o : "a.out");
}
2020-12-26 10:09:07 +00:00
if (dox_args.len > 0) {
drop_dox(&dox_args, opt_o ? opt_o : "/dev/stdout");
}
2020-12-01 11:43:40 +00:00
return 0;
}