scc

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

cc.c (11463B)


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