scc

simple c99 compiler
git clone git://git.simple-cc.org/scc
Log | Files | Refs | README | LICENSE

cc.c (11970B)


      1 /*
      2  * FIXME: scc is a pure C99 source code, except this file that is
      3  * intended for a POSIX.2008 environment. This situation  creates
      4  * a problem where some systems require the macro _ANSI_SOURCE to
      5  * limit the namespace to a pure ISO namespace. NetBSD has a  bug
      6  * and using POSIX_C_SOURCE  and  _ANSI_SOURCE  at  the same time
      7  * generates a syntax  error in the system headers. A  patch  was
      8  * sent to NetBSD, but this temporary fix is added here until the
      9  * patch  arrives to the stable release.
     10  */
     11 #define _POSIX_C_SOURCE 200809L
     12 #undef _ANSI_SOURCE
     13 
     14 #include <fcntl.h>
     15 #include <sys/types.h>
     16 #include <sys/wait.h>
     17 #include <unistd.h>
     18 
     19 #include <errno.h>
     20 #include <limits.h>
     21 #include <signal.h>
     22 #include <stdio.h>
     23 #include <stdlib.h>
     24 #include <string.h>
     25 
     26 #include "config.h"
     27 #include <scc/arg.h>
     28 #include <scc/scc.h>
     29 #include <scc/syscrts.h>
     30 #include <scc/sysincludes.h>
     31 #include <scc/syslibs.h>
     32 #include <scc/ldflags.h>
     33 
     34 enum {
     35 	CC1,
     36 	TEEIR,
     37 	CC2,
     38 	TEEQBE,
     39 	QBE,
     40 	TEEAS,
     41 	AS,
     42 	LD,
     43 	STRIP,
     44 	LAST_TOOL,
     45 };
     46 
     47 static struct tool {
     48 	char   cmd[PATH_MAX];
     49 	char   bin[32];
     50 	char  *outfile;
     51 	struct items args;
     52 	unsigned nparams;
     53 	int    in, out, init;
     54 	pid_t  pid;
     55 } tools[] = {
     56 	[CC1]    = {.cmd = "cc1"},
     57 	[TEEIR]  = {.bin = "tee",   .cmd = "tee"},
     58 	[CC2]    = {.cmd = "cc2"},
     59 	[TEEQBE] = {.bin = "tee",   .cmd = "tee"},
     60 	[QBE]    = {.bin = "qbe",   .cmd = "qbe"},
     61 	[TEEAS]  = {.bin = "tee",   .cmd = "tee"},
     62 	[AS]     = {.bin = "as",    .cmd = "as"},
     63 	[LD]     = {.bin = "ld",    .cmd = "ld"},
     64 	[STRIP]  = {.bin = "strip", .cmd = "strip"},
     65 };
     66 
     67 char *argv0;
     68 static char *arch, *sys, *abi, *format;
     69 static char *prefix, *objfile, *outfile;
     70 static char *tmpdir;
     71 static size_t tmpdirln;
     72 static struct items objtmp, objout;
     73 static int Mflag, Eflag, Sflag, Wflag,
     74            cflag, dflag, kflag, sflag, Qflag = 1; /* TODO: Remove Qflag */
     75 static int devnullfd = -1;
     76 
     77 extern int failure;
     78 
     79 static void
     80 terminate(void)
     81 {
     82 	unsigned i;
     83 
     84 	if (!kflag) {
     85 		for (i = 0; i < objtmp.n; ++i)
     86 			unlink(objtmp.s[i]);
     87 	}
     88 }
     89 
     90 static char *
     91 path(char *s)
     92 {
     93 	char *arg, buff[FILENAME_MAX];
     94 	size_t len, cnt;
     95 
     96 	for (cnt = 0 ; *s && cnt < FILENAME_MAX; ++s) {
     97 		if (*s != '%') {
     98 			buff[cnt++] = *s;
     99 			continue;
    100 		}
    101 
    102 		switch (*++s) {
    103 		case 'a':
    104 			arg = arch;
    105 			break;
    106 		case 's':
    107 			arg = sys;
    108 			break;
    109 		case 'p':
    110 			arg = prefix;
    111 			break;
    112 		case 'b':
    113 			arg = abi;
    114 			break;
    115 		default:
    116 			buff[cnt++] = *s;
    117 			continue;
    118 		}
    119 
    120 		len = strlen(arg);
    121 		if (len + cnt >= FILENAME_MAX)
    122 			die("cc: pathname too long");
    123 		memcpy(buff+cnt, arg, len);
    124 		cnt += len;
    125 	}
    126 
    127 	if (cnt < FILENAME_MAX) {
    128 		buff[cnt] = '\0';
    129 		return xstrdup(buff);
    130 	}
    131 }
    132 
    133 static void
    134 addarg(int tool, char *arg)
    135 {
    136 	struct tool *t = &tools[tool];
    137 
    138 	if (t->args.n < 1)
    139 		t->args.n = 1;
    140 
    141 	newitem(&t->args, arg);
    142 }
    143 
    144 static void
    145 setargv0(int tool, char *arg)
    146 {
    147 	struct tool *t = &tools[tool];
    148 
    149 	if (t->args.n > 0)
    150 		t->args.s[0] = arg;
    151 	else
    152 		newitem(&t->args, arg);
    153 }
    154 
    155 static char *
    156 cc12fmt(int tool)
    157 {
    158 	if (tool == CC1)
    159 		return "%s";
    160 	if (Qflag && !strcmp(arch, "amd64") && !strcmp(abi, "sysv"))
    161 		return "%s-qbe_%s-%s";
    162 	return "%s-%s-%s";
    163 }
    164 
    165 static int
    166 inittool(int tool)
    167 {
    168 	struct tool *t = &tools[tool];
    169 	char *crt, *fmt;
    170 	int n;
    171 
    172 	if (t->init)
    173 		return tool;
    174 
    175 	switch (tool) {
    176 	case CC1:
    177 		if (Wflag)
    178 			addarg(tool, "-w");
    179 		for (n = 0; sysincludes[n]; ++n) {
    180 			addarg(tool, "-I");
    181 			addarg(tool, path(sysincludes[n]));
    182 		}
    183 	case CC2:
    184 		fmt = cc12fmt(tool);
    185 		n = snprintf(t->bin, sizeof(t->bin), fmt, t->cmd, arch, abi);
    186 		if (n < 0 || n >= sizeof(t->bin))
    187 			die("cc: target tool name is too long");
    188 
    189 		n = snprintf(t->cmd, sizeof(t->cmd),
    190 		             "%s/libexec/scc/%s", prefix, t->bin);
    191 		if (n < 0 || n >= sizeof(t->cmd))
    192 			die("cc: target tool path is too long");
    193 		break;
    194 	case LD:
    195 		for (n = 0; ldflags[n]; ++n)
    196 			addarg(tool, ldflags[n]);
    197 		addarg(tool, "-o");
    198 		t->outfile = outfile ? outfile : xstrdup("a.out");
    199 		addarg(tool, t->outfile);
    200 		for (n = 0; syslibs[n]; ++n) {
    201 			addarg(tool, "-L");
    202 			addarg(tool, path(syslibs[n]));
    203 		}
    204 		for (n = 0; syscrts[n]; ++n)
    205 			addarg(tool, path(syscrts[n]));
    206 		break;
    207 	case AS:
    208 		addarg(tool, "-o");
    209 		break;
    210 	default:
    211 		break;
    212 	}
    213 
    214 	setargv0(tool, t->bin);
    215 	t->nparams = t->args.n;
    216 	t->init = 1;
    217 
    218 	return tool;
    219 }
    220 
    221 static char *
    222 outfname(char *path, char *type)
    223 {
    224 	char *new, sep, *p;
    225 	size_t newsz, pathln;
    226 	int tmpfd, n;
    227 
    228 	if (path) {
    229 		sep = '.';
    230 		if (p = strrchr(path, '/'))
    231 			path = p + 1;
    232 		pathln = strlen(path);
    233 		if (p = strrchr(path, '.'))
    234 			pathln -= strlen(p);
    235 	} else {
    236 		sep = '/';
    237 		type = "scc-XXXXXX";
    238 		path = tmpdir;
    239 		pathln = tmpdirln;
    240 	}
    241 
    242 	newsz = pathln + 1 + strlen(type) + 1;
    243 	new = xmalloc(newsz);
    244 	n = snprintf(new, newsz, "%.*s%c%s", (int)pathln, path, sep, type);
    245 	if (n < 0 || n >= newsz)
    246 		die("cc: wrong output filename");
    247 	if (sep == '/') {
    248 		if ((tmpfd = mkstemp(new)) < 0)
    249 			die("cc: could not create output file '%s': %s",
    250 			    new, strerror(errno));
    251 		close(tmpfd);
    252 	}
    253 
    254 	return new;
    255 }
    256 
    257 static int
    258 settool(int tool, char *infile, int nexttool)
    259 {
    260 	struct tool *t = &tools[tool];
    261 	unsigned i;
    262 	int fds[2];
    263 	static int fdin = -1;
    264 
    265 	switch (tool) {
    266 	case TEEIR:
    267 		t->outfile = outfname(infile, "ir");
    268 		addarg(tool, t->outfile);
    269 		break;
    270 	case TEEQBE:
    271 		t->outfile = outfname(infile, "qbe");
    272 		addarg(tool, t->outfile);
    273 		break;
    274 	case TEEAS:
    275 		t->outfile = outfname(infile, "s");
    276 		addarg(tool, t->outfile);
    277 		break;
    278 	case AS:
    279 		if (cflag && outfile) {
    280 			objfile = outfile;
    281 		} else {
    282 			objfile = (cflag || kflag) ? infile : NULL;
    283 			objfile = outfname(objfile, "o");
    284 		}
    285 		t->outfile = xstrdup(objfile);
    286 		addarg(tool, t->outfile);
    287 		break;
    288 	case STRIP:
    289 		if (cflag || kflag) {
    290 			for (i = 0; i < objout.n; ++i)
    291 				addarg(tool, xstrdup(objout.s[i]));
    292 		}
    293 		if (!cflag && tools[LD].outfile)
    294 			addarg(tool, tools[LD].outfile);
    295 		break;
    296 	default:
    297 		break;
    298 	}
    299 
    300 	if (fdin > -1) {
    301 		t->in = fdin;
    302 		fdin = -1;
    303 	} else {
    304 		t->in = -1;
    305 		if (infile)
    306 			addarg(tool, xstrdup(infile));
    307 	}
    308 
    309 	if (nexttool < LAST_TOOL) {
    310 		if (pipe(fds))
    311 			die("cc: pipe: %s", strerror(errno));
    312 		t->out = fds[1];
    313 		fdin = fds[0];
    314 	} else {
    315 		t->out = -1;
    316 	}
    317 
    318 	addarg(tool, NULL);
    319 
    320 	return tool;
    321 }
    322 
    323 static void
    324 spawn(int tool)
    325 {
    326 	char **ap;
    327 	struct tool *t = &tools[tool];
    328 
    329 	switch (t->pid = fork()) {
    330 	case -1:
    331 		die("cc: %s: %s", t->bin, strerror(errno));
    332 	case 0:
    333 		if (t->out > -1)
    334 			dup2(t->out, 1);
    335 		if (t->in > -1)
    336 			dup2(t->in, 0);
    337 		if (!dflag && tool != CC1 && tool != LD)
    338 			dup2(devnullfd, 2);
    339 		if (dflag) {
    340 			for (ap = t->args.s; *ap; ap++)
    341 				fprintf(stderr, " %s", *ap);
    342 			putc('\n', stderr);
    343 		}
    344 		execvp(t->cmd, t->args.s);
    345 		if (dflag) {
    346 			fprintf(stderr,
    347 			        "cc: execvp %s: %s\n",
    348 				t->cmd,
    349 			        strerror(errno));
    350 		}
    351 		abort();
    352 	default:
    353 		if (t->in > -1)
    354 			close(t->in);
    355 		if (t->out > -1)
    356 			close(t->out);
    357 		break;
    358 	}
    359 }
    360 
    361 static int
    362 toolfor(char *file)
    363 {
    364 	char *dot = strrchr(file, '.');
    365 
    366 	if (Eflag)
    367 		return CC1;
    368 
    369 	if (dot) {
    370 		if (!strcmp(dot, ".c"))
    371 			return CC1;
    372 		if (!strcmp(dot, ".ir"))
    373 			return CC2;
    374 		if (!strcmp(dot, ".qbe"))
    375 			return QBE;
    376 		if (!strcmp(dot, ".s"))
    377 			return AS;
    378 		if (!strcmp(dot, ".o"))
    379 			return LD;
    380 		if (!strcmp(dot, ".a"))
    381 			return LD;
    382 	} else if (!strcmp(file, "-")) {
    383 		return CC1;
    384 	}
    385 
    386 	die("cc: unrecognized filetype of %s", file);
    387 }
    388 
    389 static int
    390 valid(int tool, struct tool *t)
    391 {
    392 	int st;
    393 
    394 	if (waitpid(t->pid, &st, 0) == -1 || WIFSIGNALED(st))
    395 		goto internal;
    396 	if (WIFEXITED(st) && WEXITSTATUS(st) == 0)
    397 		return 1;
    398 	if (!failure && (tool == CC1 || tool == LD))
    399 		goto fail;
    400 
    401 internal:
    402 	if (!failure)
    403 		fprintf(stderr, "cc:%s: internal error\n", t->bin);
    404 fail:
    405 	failure = 1;
    406 	return 0;
    407 }
    408 
    409 static int
    410 validatetools(void)
    411 {
    412 	struct tool *t;
    413 	unsigned i;
    414 	int tool, st, failed = LAST_TOOL;
    415 
    416 	for (tool = 0; tool < LAST_TOOL; ++tool) {
    417 		t = &tools[tool];
    418 		if (!t->pid)
    419 			continue;
    420 		if (!valid(tool, t))
    421 			failed = tool;
    422 		if (tool >= failed && t->outfile)
    423 			unlink(t->outfile);
    424 		for (i = t->nparams; i < t->args.n; ++i)
    425 			free(t->args.s[i]);
    426 		t->args.n = t->nparams;
    427 		t->pid = 0;
    428 	}
    429 	if (failed < LAST_TOOL) {
    430 		unlink(objfile);
    431 		free(objfile);
    432 		objfile = NULL;
    433 		return 0;
    434 	}
    435 
    436 	return 1;
    437 }
    438 
    439 static int
    440 buildfile(char *file, int tool)
    441 {
    442 	int nexttool;
    443 
    444 	for (; tool < LAST_TOOL; tool = nexttool) {
    445 		switch (tool) {
    446 		case CC1:
    447 			if (Eflag || Mflag)
    448 				nexttool = LAST_TOOL;
    449 			else
    450 				nexttool = kflag ? TEEIR : CC2;
    451 			break;
    452 		case TEEIR:
    453 			nexttool = CC2;
    454 			break;
    455 		case CC2:
    456 			if (Qflag)
    457 				nexttool = kflag ? TEEQBE : QBE;
    458 			else
    459 				nexttool = (Sflag || kflag) ? TEEAS : AS;
    460 			break;
    461 		case TEEQBE:
    462 			nexttool = QBE;
    463 			break;
    464 		case QBE:
    465 			nexttool = (Sflag || kflag) ? TEEAS : AS;
    466 			break;
    467 		case TEEAS:
    468 			nexttool = Sflag ? LAST_TOOL : AS;
    469 			break;
    470 		case AS:
    471 			nexttool = LAST_TOOL;
    472 			break;
    473 		default:
    474 			nexttool = LAST_TOOL;
    475 			continue;
    476 		}
    477 
    478 		spawn(settool(inittool(tool), file, nexttool));
    479 	}
    480 
    481 	return validatetools();
    482 }
    483 
    484 static void
    485 build(struct items *chain, int link)
    486 {
    487 	int i, tool;
    488 
    489 	if (link)
    490 		inittool(LD);
    491 
    492 	for (i = 0; i < chain->n; ++i) {
    493 		if (!strcmp(chain->s[i], "-l")) {
    494 			if (link) {
    495 				addarg(LD, xstrdup(chain->s[i++]));
    496 				addarg(LD, xstrdup(chain->s[i]));
    497 			} else {
    498 				++i;
    499 			}
    500 			continue;
    501 		}
    502 		tool = toolfor(chain->s[i]);
    503 		if (tool == LD) {
    504 			if (link)
    505 				addarg(LD, xstrdup(chain->s[i]));
    506 			continue;
    507 		}
    508 		if (buildfile(chain->s[i], tool)) {
    509 			if (link)
    510 				addarg(LD, xstrdup(objfile));
    511 			newitem((!link || kflag) ? &objout : &objtmp, objfile);
    512 		}
    513 	}
    514 }
    515 
    516 static void
    517 usage(void)
    518 {
    519 	fputs("usage: cc [options] file...\n", stderr);
    520 	exit(1);
    521 }
    522 
    523 int
    524 main(int argc, char *argv[])
    525 {
    526 	struct items linkchain = { .n = 0, };
    527 	int link;
    528 
    529 	atexit(terminate);
    530 
    531 	if (!(arch = getenv("ARCH")))
    532 		arch = ARCH;
    533 	if (!(sys = getenv("SYS")))
    534 		sys = SYS;
    535 	if (!(abi = getenv("ABI")))
    536 		abi = ABI;
    537 	if (!(format = getenv("FORMAT")))
    538 		format = FORMAT;
    539 	if (!(prefix = getenv("SCCPREFIX")))
    540 		prefix = PREFIX;
    541 
    542 	ARGBEGIN {
    543 	case 'D':
    544 		addarg(CC1, "-D");
    545 		addarg(CC1, EARGF(usage()));
    546 		break;
    547 	case 'M':
    548 		Mflag = 1;
    549 		addarg(CC1, "-M");
    550 		break;
    551 	case 'E':
    552 		Eflag = 1;
    553 		addarg(CC1, "-E");
    554 		break;
    555 	case 'I':
    556 		addarg(CC1, "-I");
    557 		addarg(CC1, EARGF(usage()));
    558 		break;
    559 	case 'L':
    560 		addarg(LD, "-L");
    561 		addarg(LD, EARGF(usage()));
    562 		break;
    563 	case 'O':
    564 		EARGF(usage());
    565 		break;
    566 	case 'S':
    567 		Sflag = 1;
    568 		break;
    569 	case 'U':
    570 		addarg(CC1, "-U");
    571 		addarg(CC1, EARGF(usage()));
    572 		break;
    573 	case 'c':
    574 		cflag = 1;
    575 		break;
    576 	case 'd':
    577 		dflag = 1;
    578 		break;
    579 	case 'g':
    580 		addarg(AS, "-g");
    581 		addarg(LD, "-g");
    582 		break;
    583 	case 'k':
    584 		kflag = 1;
    585 		break;
    586 	case 'l':
    587 		newitem(&linkchain, "-l");
    588 		newitem(&linkchain, EARGF(usage()));
    589 		break;
    590 	case 'm':
    591 		arch = EARGF(usage());
    592 		break;
    593 	case 'o':
    594 		outfile = xstrdup(EARGF(usage()));
    595 		break;
    596 	case 's':
    597 		sflag = 1;
    598 		break;
    599 	case 't':
    600 		sys = EARGF(usage());
    601 		break;
    602 	case 'w':
    603 		Wflag = 0;
    604 		break;
    605 	case 'W':
    606 		Wflag = 1;
    607 		break;
    608 	case 'q':
    609 		Qflag = 0;
    610 		break;
    611 	case 'Q':
    612 		Qflag = 1;
    613 		break;
    614 	case '-':
    615 		fprintf(stderr,
    616 		        "cc: ignored parameter --%s\n", EARGF(usage()));
    617 		break;
    618 	default:
    619 		usage();
    620 	} ARGOPERAND {
    621 operand:
    622 		newitem(&linkchain, ARGOP());
    623 	} ARGEND
    624 
    625 	for (; *argv; --argc, ++argv)
    626 		goto operand;
    627 
    628 	if (Eflag && linkchain.n == 0)
    629 		newitem(&linkchain, "-");
    630 
    631 	if (Eflag && Mflag ||
    632             (Eflag || Mflag) && (Sflag || kflag) ||
    633 	    linkchain.n == 0 ||
    634 	    linkchain.n > 1 && cflag && outfile)
    635 		usage();
    636 
    637 	if (!dflag) {
    638 		if ((devnullfd = open("/dev/null", O_WRONLY)) < 0)
    639 			fputs("cc: could not open /dev/null\n", stderr);
    640 	}
    641 
    642 	if (!(tmpdir = getenv("TMPDIR")) || !tmpdir[0])
    643 		tmpdir = ".";
    644 	tmpdirln = strlen(tmpdir);
    645 
    646 	build(&linkchain, (link = !(Mflag || Eflag || Sflag || cflag)));
    647 
    648 	if (!(link || cflag))
    649 		return failure;
    650 
    651 	if (link && !failure) {
    652 		addarg(LD, xstrdup("-lc"));
    653 		addarg(LD, xstrdup("-lcrt"));
    654 		spawn(settool(LD, NULL, LAST_TOOL));
    655 		validatetools();
    656 	}
    657 
    658 	if (sflag) {
    659 		spawn(settool(inittool(STRIP), NULL, LAST_TOOL));
    660 		validatetools();
    661 	}
    662 
    663 	return failure;
    664 }