driver.c (17011B)
1 #define _POSIX_C_SOURCE 200809L 2 #include <errno.h> 3 #include <stdarg.h> 4 #include <stdbool.h> 5 #include <stdint.h> 6 #include <stdio.h> 7 #include <stdlib.h> 8 #include <string.h> 9 10 #include <fcntl.h> 11 #include <limits.h> 12 #include <signal.h> 13 #include <spawn.h> 14 #include <sys/stat.h> 15 #include <sys/wait.h> 16 #include <unistd.h> 17 18 #include "util.h" 19 #include "paths.h" 20 #include "proc.h" 21 22 enum filetype { 23 NONE, /* detect based on file extension */ 24 ASM, /* assembly source */ 25 ASMPP, /* assembly source requiring preprocessing */ 26 C, /* c source */ 27 CHDR, /* c header */ 28 CPPOUT, /* preprocessed c source */ 29 OBJ, /* object file */ 30 QBE, /* QBE IL */ 31 }; 32 33 enum stage { 34 PREPROCESS, 35 COMPILE, 36 CODEGEN, 37 ASSEMBLE, 38 LINK, 39 }; 40 41 #include "config.h" 42 43 struct stageinfo { 44 const char *name; 45 struct array cmd; 46 size_t cmdbase; 47 pid_t pid; 48 }; 49 50 struct input { 51 char *name; 52 unsigned stages; 53 enum filetype filetype; 54 bool lib; 55 }; 56 57 static struct { 58 bool nostdlib; 59 bool verbose; 60 } flags; 61 62 static struct stageinfo stages[] = { 63 [PREPROCESS] = {.name = "preprocess"}, 64 [COMPILE] = {.name = "compile"}, 65 [CODEGEN] = {.name = "codegen"}, 66 [ASSEMBLE] = {.name = "assemble"}, 67 [LINK] = {.name = "link"}, 68 }; 69 70 static const char *const ignoreflags[] = { 71 "fno-builtin", "ffreestanding", "pedantic", "pedantic-errors", "pipe" 72 }; 73 74 static void 75 usage(const char *fmt, ...) 76 { 77 va_list ap; 78 79 if (fmt) { 80 fprintf(stderr, "%s: ", argv0); 81 va_start(ap, fmt); 82 vfprintf(stderr, fmt, ap); 83 va_end(ap); 84 fputc('\n', stderr); 85 } 86 fprintf( 87 stderr, 88 "usage: %s [-c|-S|-E] [-D name[=value]] [-U name] [-I dir] " 89 "[-isystem dir] [-iquote dir] [-idirafter dir] [-std=standard] " 90 "[-nostdinc] [-L dir] [-l library] [-static] [-pthread] [-P] [-s] " 91 92 "[-g] [-o output] input...\n", 93 argv0 94 ); 95 exit(2); 96 } 97 98 static enum filetype 99 detectfiletype(const char *name) 100 { 101 const char *dot; 102 103 dot = strrchr(name, '.'); 104 if (dot) { 105 ++dot; 106 if (strcmp(dot, "c") == 0) 107 return C; 108 if (strcmp(dot, "h") == 0) 109 return CHDR; 110 if (strcmp(dot, "i") == 0) 111 return CPPOUT; 112 if (strcmp(dot, "qbe") == 0) 113 return QBE; 114 if (strcmp(dot, "s") == 0) 115 return ASM; 116 if (strcmp(dot, "S") == 0) 117 return ASMPP; 118 } 119 120 return OBJ; 121 } 122 123 static char * 124 changeext(const char *name, const char *ext) 125 { 126 const char *slash, *dot; 127 char *result; 128 size_t baselen; 129 130 slash = strrchr(name, '/'); 131 if (slash) 132 name = slash + 1; 133 dot = strrchr(name, '.'); 134 baselen = dot ? (size_t)(dot - name) : strlen(name); 135 result = xmalloc(baselen + strlen(ext) + 2); 136 memcpy(result, name, baselen); 137 result[baselen] = '.'; 138 strcpy(result + baselen + 1, ext); 139 140 return result; 141 } 142 143 static int 144 spawn(pid_t *pid, struct array *args, posix_spawn_file_actions_t *actions) 145 { 146 extern char **environ; 147 char **arg; 148 149 if (flags.verbose) { 150 fprintf(stderr, "%s: spawning", argv0); 151 for (arg = args->val; *arg; ++arg) 152 fprintf(stderr, " %s", *arg); 153 fputc('\n', stderr); 154 } 155 return posix_spawnp(pid, *(char **)args->val, actions, NULL, args->val, environ); 156 } 157 158 static int 159 spawnphase(struct stageinfo *phase, int *fd, char *input, char *output, bool last) 160 { 161 int ret, pipefd[2]; 162 posix_spawn_file_actions_t actions; 163 164 phase->cmd.len = phase->cmdbase; 165 if (last && output) { 166 arrayaddptr(&phase->cmd, "-o"); 167 arrayaddptr(&phase->cmd, output); 168 } 169 arrayaddptr(&phase->cmd, input && *fd == -1 ? input : "-"); 170 arrayaddptr(&phase->cmd, NULL); 171 172 ret = posix_spawn_file_actions_init(&actions); 173 if (ret) 174 goto err0; 175 if (*fd != -1) 176 ret = posix_spawn_file_actions_adddup2(&actions, *fd, 0); 177 if (!last) { 178 if (pipe(pipefd) < 0) { 179 ret = errno; 180 goto err1; 181 } 182 if (fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) < 0) { 183 ret = errno; 184 goto err2; 185 } 186 if (fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) < 0) { 187 ret = errno; 188 goto err2; 189 } 190 ret = posix_spawn_file_actions_adddup2(&actions, pipefd[1], 1); 191 if (ret) 192 goto err2; 193 } 194 195 ret = spawn(&phase->pid, &phase->cmd, &actions); 196 if (ret) 197 goto err2; 198 if (!last) { 199 *fd = pipefd[0]; 200 close(pipefd[1]); 201 } 202 posix_spawn_file_actions_destroy(&actions); 203 204 return 0; 205 206 err2: 207 if (!last) { 208 close(pipefd[0]); 209 close(pipefd[1]); 210 } 211 err1: 212 posix_spawn_file_actions_destroy(&actions); 213 err0: 214 return ret; 215 } 216 217 static bool 218 succeeded(const char *phase, pid_t pid, int status) 219 { 220 if (WIFEXITED(status)) { 221 if (WEXITSTATUS(status) == 0) 222 return true; 223 warn("%s: process %ju exited with status %d", phase, (uintmax_t)pid, WEXITSTATUS(status)); 224 } else if (WIFSIGNALED(status)) { 225 warn("%s: process signaled: %s", phase, strsignal(WTERMSIG(status))); 226 } else { 227 warn("%s: process failed", phase); 228 } 229 return false; 230 } 231 232 static void 233 buildobj(struct input *input, char *output) 234 { 235 const char *phase; 236 size_t i, npids; 237 pid_t pid; 238 int status, ret, fd; 239 bool success = true; 240 241 if (input->filetype == OBJ) 242 return; 243 if (input->stages & 1 << LINK) { 244 input->stages &= ~(1 << LINK); 245 output = xmalloc(strlen(ARUU_PATH_TMP) + sizeof("/cproc-XXXXXX")); 246 sprintf(output, "%s/cproc-XXXXXX", ARUU_PATH_TMP); 247 fd = mkstemp(output); 248 if (fd < 0) 249 fatal("mkstemp:"); 250 close(fd); 251 } else if (output) { 252 if (strcmp(output, "-") == 0) 253 output = NULL; 254 } else if (input->stages & 1 << ASSEMBLE) { 255 output = changeext(input->name, "o"); 256 } else if (input->stages & 1 << CODEGEN) { 257 output = changeext(input->name, "s"); 258 } else if (input->stages & 1 << COMPILE) { 259 output = changeext(input->name, "qbe"); 260 } 261 if (strcmp(input->name, "-") == 0) 262 input->name = NULL; 263 264 npids = 0; 265 for (i = PREPROCESS, fd = -1; input->stages; ++i) { 266 if (!(input->stages & 1 << i)) 267 continue; 268 input->stages &= ~(1 << i); 269 ret = spawnphase(&stages[i], &fd, input->name, output, !input->stages); 270 if (ret) { 271 warn("%s: spawn \"%s\": %s", stages[i].name, *(char **)stages[i].cmd.val, strerror(ret)); 272 goto kill; 273 } 274 ++npids; 275 } 276 input->name = output; 277 278 while (npids > 0) { 279 pid = wait(&status); 280 if (pid < 0) 281 fatal("waitpid:"); 282 for (i = 0; i < countof(stages); ++i) { 283 if (pid == stages[i].pid) { 284 --npids; 285 stages[i].pid = 0; 286 phase = stages[i].name; 287 break; 288 } 289 } 290 if (i == countof(stages)) 291 continue; 292 if (!succeeded(phase, pid, status)) { 293 kill: 294 if (success && npids > 0) { 295 for (i = 0; i < countof(stages); ++i) { 296 if (stages[i].pid) 297 kill(stages[i].pid, SIGTERM); 298 } 299 } 300 success = false; 301 } 302 } 303 if (!success) { 304 if (output) 305 unlink(output); 306 exit(1); 307 } 308 } 309 310 static void 311 buildexe(struct input *inputs, size_t ninputs, char *output) 312 { 313 struct stageinfo *s = &stages[LINK]; 314 size_t i; 315 int ret, status; 316 pid_t pid; 317 318 arrayaddptr(&s->cmd, "-o"); 319 arrayaddptr(&s->cmd, output); 320 if (!flags.nostdlib && startfiles[0]) 321 arrayaddbuf(&s->cmd, startfiles, sizeof(startfiles)); 322 for (i = 0; i < ninputs; ++i) { 323 if (inputs[i].lib) 324 arrayaddptr(&s->cmd, "-l"); 325 arrayaddptr(&s->cmd, inputs[i].name); 326 } 327 if (!flags.nostdlib && endfiles[0]) 328 arrayaddbuf(&s->cmd, endfiles, sizeof(endfiles)); 329 arrayaddptr(&s->cmd, NULL); 330 331 ret = spawn(&pid, &s->cmd, NULL); 332 if (ret) 333 fatal("%s: spawn \"%s\": %s", s->name, *(char **)s->cmd.val, strerror(errno)); 334 if (waitpid(pid, &status, 0) < 0) 335 fatal("waitpid %ju:", (uintmax_t)pid); 336 for (i = 0; i < ninputs; ++i) { 337 if (inputs[i].filetype != OBJ) 338 unlink(inputs[i].name); 339 } 340 exit(!succeeded(s->name, pid, status)); 341 } 342 343 static char * 344 nextarg(char ***argv) 345 { 346 if ((**argv)[2] != '\0') 347 return &(**argv)[2]; 348 ++*argv; 349 if (!**argv) 350 usage(NULL); 351 return **argv; 352 } 353 354 static char * 355 resolvepath(const char *arg0, const char *binname, const char *devrelpath) 356 { 357 char self[PATH_MAX], *dir, *path; 358 size_t n; 359 struct stat st; 360 361 n = proc_selfexe(self, sizeof(self) - 1); 362 if (n == (size_t)-1) { 363 n = strlen(arg0); 364 if (n > sizeof(self) - 1) 365 n = sizeof(self) - 1; 366 memcpy(self, arg0, n); 367 } 368 self[n] = '\0'; 369 370 dir = strrchr(self, '/'); 371 if (dir) { 372 *dir = '\0'; 373 } else { 374 strcpy(self, "."); 375 } 376 377 path = xmalloc(strlen(self) + strlen(devrelpath) + 2); 378 sprintf(path, "%s/%s", self, devrelpath); 379 if (stat(path, &st) == 0) 380 return path; 381 382 free(path); 383 384 path = xmalloc(strlen(self) + strlen(binname) + 2); 385 sprintf(path, "%s/%s", self, binname); 386 return path; 387 } 388 389 static int 390 hasprefix(const char *str, const char *pfx) 391 { 392 return memcmp(str, pfx, strlen(pfx)) == 0; 393 } 394 395 int 396 main(int argc, char *argv[]) 397 { 398 enum stage last = LINK; 399 enum filetype filetype = 0; 400 char *arg, *end, *output = NULL, *arch, *qbearch; 401 struct array inputs = {0}, *cmd; 402 struct input *input; 403 size_t i; 404 405 argv0 = progname(argv[0], "cc"); 406 407 char *cpp_path = resolvepath(argv[0], "cpp", "cpp"); 408 char *cc1_path = resolvepath(argv[0], "cc1", "cc1"); 409 char *qbe_path = resolvepath(argv[0], "qbe", "../../../externalRepos/qbe/qbe"); 410 char *as_path = resolvepath(argv[0], "as", "../../../cmd/dev/as/as"); 411 char *ld_path = resolvepath(argv[0], "ld", "../ld/ld"); 412 413 arrayaddptr(&stages[PREPROCESS].cmd, cpp_path); 414 if (countof(preprocesscmd) > 1) { 415 arrayaddbuf( 416 &stages[PREPROCESS].cmd, preprocesscmd + 1, sizeof(preprocesscmd) - sizeof(preprocesscmd[0]) 417 ); 418 } 419 420 arrayaddptr(&stages[COMPILE].cmd, cc1_path); 421 422 arrayaddptr(&stages[CODEGEN].cmd, qbe_path); 423 if (countof(codegencmd) > 1) { 424 arrayaddbuf(&stages[CODEGEN].cmd, codegencmd + 1, sizeof(codegencmd) - sizeof(codegencmd[0])); 425 } 426 427 arrayaddptr(&stages[ASSEMBLE].cmd, as_path); 428 if (countof(assemblecmd) > 1) { 429 arrayaddbuf( 430 &stages[ASSEMBLE].cmd, assemblecmd + 1, sizeof(assemblecmd) - sizeof(assemblecmd[0]) 431 ); 432 } 433 434 arrayaddptr(&stages[LINK].cmd, ld_path); 435 if (countof(linkcmd) > 1) { 436 arrayaddbuf(&stages[LINK].cmd, linkcmd + 1, sizeof(linkcmd) - sizeof(linkcmd[0])); 437 } 438 439 if (hasprefix(target, "x86_64-apple-")) { 440 arch = "x86_64-sysv"; 441 qbearch = "amd64_apple"; 442 } else if (hasprefix(target, "x86_64-") || hasprefix(target, "amd64-")) { 443 arch = "x86_64-sysv"; 444 qbearch = "amd64_sysv"; 445 } else if (hasprefix(target, "aarch64-")) { 446 arch = "aarch64"; 447 qbearch = "arm64"; 448 } else if (hasprefix(target, "riscv64-")) { 449 arch = "riscv64"; 450 qbearch = "rv64"; 451 } else { 452 fatal("unsupported target '%s'", target); 453 } 454 arrayaddptr(&stages[COMPILE].cmd, "-t"); 455 arrayaddptr(&stages[COMPILE].cmd, arch); 456 arrayaddptr(&stages[CODEGEN].cmd, "-t"); 457 arrayaddptr(&stages[CODEGEN].cmd, qbearch); 458 459 for (;;) { 460 ignore: 461 ++argv, --argc; 462 arg = *argv; 463 if (!arg) 464 break; 465 if (arg[0] != '-' || arg[1] == '\0') { 466 input = arrayadd(&inputs, sizeof(*input)); 467 input->name = arg; 468 input->lib = false; 469 input->filetype = filetype == NONE && arg[1] ? detectfiletype(arg) : filetype; 470 switch (input->filetype) { 471 case ASM: 472 input->stages = 1 << ASSEMBLE | 1 << LINK; 473 break; 474 case ASMPP: 475 input->stages = 1 << PREPROCESS | 1 << ASSEMBLE | 1 << LINK; 476 break; 477 case C: 478 input->stages = 1 << PREPROCESS | 1 << COMPILE | 1 << CODEGEN | 1 << ASSEMBLE | 1 << LINK; 479 break; 480 case CHDR: 481 input->stages = 1 << PREPROCESS; 482 break; 483 case CPPOUT: 484 input->stages = 1 << COMPILE | 1 << CODEGEN | 1 << ASSEMBLE | 1 << LINK; 485 break; 486 case QBE: 487 input->stages = 1 << CODEGEN | 1 << ASSEMBLE | 1 << LINK; 488 break; 489 case OBJ: 490 input->stages = 1 << LINK; 491 break; 492 default: 493 usage( 494 "reading from standard input requires " 495 "-x" 496 ); 497 } 498 continue; 499 } 500 501 for (i = 0; i < countof(ignoreflags); ++i) { 502 if (strcmp(arg + 1, ignoreflags[i]) == 0) 503 goto ignore; 504 } 505 506 if (strcmp(arg, "-nostdlib") == 0) { 507 flags.nostdlib = true; 508 } else if (strcmp(arg, "-nostdinc") == 0) { 509 arrayaddptr(&stages[PREPROCESS].cmd, arg); 510 } else if (strcmp(arg, "-static") == 0) { 511 arrayaddptr(&stages[LINK].cmd, arg); 512 } else if (strcmp(arg, "-emit-qbe") == 0) { 513 if (last > COMPILE) 514 last = COMPILE; 515 } else if ( 516 strcmp(arg, "-idirafter") == 0 || strcmp(arg, "-isystem") == 0 517 || strcmp(arg, "-iquote") == 0 518 ) { 519 if (!--argc) 520 usage(NULL); 521 arrayaddptr(&stages[PREPROCESS].cmd, arg); 522 arrayaddptr(&stages[PREPROCESS].cmd, *++argv); 523 } else if (strncmp(arg, "-std=", 5) == 0) { 524 arrayaddptr(&stages[PREPROCESS].cmd, arg); 525 } else if (strcmp(arg, "-pthread") == 0) { 526 arrayaddptr(&stages[LINK].cmd, "-l"); 527 arrayaddptr(&stages[LINK].cmd, "pthread"); 528 } else if (strcmp(arg, "-dumpmachine") == 0) { 529 puts(target); 530 return 0; 531 } else { 532 if (arg[2] != '\0' && strchr("cESsv", arg[1])) 533 usage(NULL); 534 switch (arg[1]) { 535 case 'c': 536 if (last > ASSEMBLE) 537 last = ASSEMBLE; 538 break; 539 case 'D': 540 arrayaddptr(&stages[PREPROCESS].cmd, "-D"); 541 arrayaddptr(&stages[PREPROCESS].cmd, nextarg(&argv)); 542 break; 543 case 'E': 544 if (last > PREPROCESS) 545 last = PREPROCESS; 546 break; 547 case 'g': 548 break; 549 case 'I': 550 arrayaddptr(&stages[PREPROCESS].cmd, "-I"); 551 arrayaddptr(&stages[PREPROCESS].cmd, nextarg(&argv)); 552 break; 553 case 'L': 554 arrayaddptr(&stages[LINK].cmd, "-L"); 555 arrayaddptr(&stages[LINK].cmd, nextarg(&argv)); 556 break; 557 case 'l': 558 input = arrayadd(&inputs, sizeof(*input)); 559 input->name = nextarg(&argv); 560 input->lib = true; 561 input->filetype = OBJ; 562 input->stages = 1 << LINK; 563 break; 564 case 'O': 565 break; 566 case 'o': 567 output = nextarg(&argv); 568 break; 569 case 'P': 570 arrayaddptr(&stages[PREPROCESS].cmd, "-P"); 571 break; 572 case 'S': 573 if (last > CODEGEN) 574 last = CODEGEN; 575 break; 576 case 's': 577 arrayaddptr(&stages[LINK].cmd, "-s"); 578 break; 579 case 'U': 580 arrayaddptr(&stages[PREPROCESS].cmd, "-U"); 581 arrayaddptr(&stages[PREPROCESS].cmd, nextarg(&argv)); 582 break; 583 case 'v': 584 flags.verbose = true; 585 break; 586 case 'W': 587 if (arg[2] && arg[3] == ',') { 588 switch (arg[2]) { 589 case 'p': 590 cmd = &stages[PREPROCESS].cmd; 591 break; 592 case 'a': 593 cmd = &stages[ASSEMBLE].cmd; 594 break; 595 case 'l': 596 cmd = &stages[LINK].cmd; 597 break; 598 default: 599 usage(NULL); 600 } 601 for (arg += 4; arg; arg = end ? end + 1 : NULL) { 602 end = strchr(arg, ','); 603 if (end) 604 *end = '\0'; 605 arrayaddptr(cmd, arg); 606 } 607 } 608 break; 609 case 'x': 610 arg = nextarg(&argv); 611 if (strcmp(arg, "none") == 0) 612 filetype = NONE; 613 else if (strcmp(arg, "c") == 0) 614 filetype = C; 615 else if (strcmp(arg, "c-header") == 0) 616 filetype = CHDR; 617 else if (strcmp(arg, "cpp-output") == 0) 618 filetype = CPPOUT; 619 else if (strcmp(arg, "qbe") == 0) 620 filetype = QBE; 621 else if (strcmp(arg, "assembler") == 0) 622 filetype = ASM; 623 else if (strcmp(arg, "assembler-with-cpp") == 0) 624 filetype = ASMPP; 625 else 626 usage("unknown language '%s'", arg); 627 break; 628 default: 629 usage("unknown option '%s'", arg); 630 } 631 } 632 } 633 634 for (i = 0; i < countof(stages); ++i) 635 stages[i].cmdbase = stages[i].cmd.len; 636 if (inputs.len == 0) 637 usage(NULL); 638 if (output) { 639 if (strcmp(output, "-") == 0) { 640 if (last >= ASSEMBLE) 641 usage("cannot write object to stdout"); 642 } else if (last != LINK && inputs.len > sizeof(*input)) { 643 usage( 644 "cannot specify -o with multiple input files " 645 "without linking" 646 ); 647 } 648 } 649 arrayforeach(&inputs, input) 650 { 651 if (!(input->stages & 1 << last)) 652 continue; 653 input->stages &= (1 << (last + 1)) - 1; 654 buildobj(input, output); 655 } 656 if (last == LINK) { 657 if (!output) 658 output = "a.out"; 659 buildexe(inputs.val, inputs.len / sizeof(*input), output); 660 } 661 return 0; 662 }