xref: /illumos-gate/usr/src/tools/cw/cw.c (revision aecfc01d1bad84e66649703f7fc2926ef70b34ba)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * Wrapper for the GNU C compiler to make it accept the Sun C compiler
29  * arguments where possible.
30  *
31  * Since the translation is inexact, this is something of a work-in-progress.
32  *
33  */
34 
35 /* If you modify this file, you must increment CW_VERSION */
36 #define	CW_VERSION	"1.26"
37 
38 /*
39  * -#		Verbose mode
40  * -###		Show compiler commands built by driver, no compilation
41  * -A<name[(tokens)]>	Preprocessor predicate assertion
42  * -B<[static|dynamic]>	Specify dynamic or static binding
43  * -C		Prevent preprocessor from removing comments
44  * -c		Compile only - produce .o files, suppress linking
45  * -cg92	Alias for -xtarget=ss1000
46  * -D<name[=token]>	Associate name with token as if by #define
47  * -d[y|n]	dynamic [-dy] or static [-dn] option to linker
48  * -E		Compile source through preprocessor only, output to stdout
49  * -erroff=<t>	Suppress warnings specified by tags t(%none, %all, <tag list>)
50  * -errtags=<a>	Display messages with tags a(no, yes)
51  * -errwarn=<t>	Treats warnings specified by tags t(%none, %all, <tag list>)
52  *		as errors
53  * -fast	Optimize using a selection of options
54  * -fd		Report old-style function definitions and declarations
55  * -flags	Show this summary of compiler options
56  * -fnonstd	Initialize floating-point hardware to non-standard preferences
57  * -fns[=<yes|no>] Select non-standard floating point mode
58  * -fprecision=<p> Set FP rounding precision mode p(single, double, extended)
59  * -fround=<r>	Select the IEEE rounding mode in effect at startup
60  * -fsimple[=<n>] Select floating-point optimization preferences <n>
61  * -fsingle	Use single-precision arithmetic (-Xt and -Xs modes only)
62  * -ftrap=<t>	Select floating-point trapping mode in effect at startup
63  * -fstore	force floating pt. values to target precision on assignment
64  * -G		Build a dynamic shared library
65  * -g		Compile for debugging
66  * -H		Print path name of each file included during compilation
67  * -h <name>	Assign <name> to generated dynamic shared library
68  * -I<dir>	Add <dir> to preprocessor #include file search path
69  * -i		Passed to linker to ignore any LD_LIBRARY_PATH setting
70  * -keeptmp	Keep temporary files created during compilation
71  * -KPIC	Compile position independent code with 32-bit addresses
72  * -Kpic	Compile position independent code
73  * -L<dir>	Pass to linker to add <dir> to the library search path
74  * -l<name>	Link with library lib<name>.a or lib<name>.so
75  * -mc		Remove duplicate strings from .comment section of output files
76  * -mr		Remove all strings from .comment section of output files
77  * -mr,"string"	Remove all strings and append "string" to .comment section
78  * -mt		Specify options needed when compiling multi-threaded code
79  * -native	Find available processor, generate code accordingly
80  * -nofstore	Do not force floating pt. values to target precision
81  *		on assignment
82  * -nolib	Same as -xnolib
83  * -noqueue	Disable queuing of compiler license requests
84  * -norunpath	Do not build in a runtime path for shared libraries
85  * -O		Use default optimization level (-xO2 or -xO3. Check man page.)
86  * -o <outputfile> Set name of output file to <outputfile>
87  * -P		Compile source through preprocessor only, output to .i  file
88  * -PIC		Alias for -KPIC or -xcode=pic32
89  * -p		Compile for profiling with prof
90  * -pic		Alias for -Kpic or -xcode=pic13
91  * -Q[y|n]	Emit/don't emit identification info to output file
92  * -qp		Compile for profiling with prof
93  * -R<dir[:dir]> Build runtime search path list into executable
94  * -S		Compile and only generate assembly code (.s)
95  * -s		Strip symbol table from the executable file
96  * -t		Turn off duplicate symbol warnings when linking
97  * -U<name>	Delete initial definition of preprocessor symbol <name>
98  * -V		Report version number of each compilation phase
99  * -v		Do stricter semantic checking
100  * -W<c>,<arg>	Pass <arg> to specified component <c> (a,l,m,p,0,2,h,i,u)
101  * -w		Suppress compiler warning messages
102  * -Xa		Compile assuming ANSI C conformance, allow K & R extensions
103  *		(default mode)
104  * -Xc		Compile assuming strict ANSI C conformance
105  * -Xs		Compile assuming (pre-ANSI) K & R C style code
106  * -Xt		Compile assuming K & R conformance, allow ANSI C
107  * -x386	Generate code for the 80386 processor
108  * -x486	Generate code for the 80486 processor
109  * -xarch=<a>	Specify target architecture instruction set
110  * -xbuiltin[=<b>] When profitable inline, or substitute intrinisic functions
111  *		for system functions, b={%all,%none}
112  * -xCC		Accept C++ style comments
113  * -xchar_byte_order=<o> Specify multi-char byte order <o> (default, high, low)
114  * -xchip=<c>	Specify the target processor for use by the optimizer
115  * -xcode=<c>	Generate different code for forming addresses
116  * -xcrossfile[=<n>] Enable optimization and inlining across source files,
117  *		n={0|1}
118  * -xe		Perform only syntax/semantic checking, no code generation
119  * -xF		Compile for later mapfile reordering or unused section
120  *		elimination
121  * -xhelp=<f>	Display on-line help information f(flags, readme, errors)
122  * -xildoff	Cancel -xildon
123  * -xildon	Enable use of the incremental linker, ild
124  * -xinline=[<a>,...,<a>]  Attempt inlining of specified user routines,
125  *		<a>={%auto,func,no%func}
126  * -xlibmieee	Force IEEE 754 return values for math routines in
127  *		exceptional cases
128  * -xlibmil	Inline selected libm math routines for optimization
129  * -xlic_lib=sunperf	Link in the Sun supplied performance libraries
130  * -xlicinfo	Show license server information
131  * -xM		Generate makefile dependencies
132  * -xM1		Generate makefile dependencies, but exclude /usr/include
133  * -xmaxopt=[off,1,2,3,4,5] maximum optimization level allowed on #pragma opt
134  * -xnolib	Do not link with default system libraries
135  * -xnolibmil	Cancel -xlibmil on command line
136  * -xO<n>	Generate optimized code (n={1|2|3|4|5})
137  * -xP		Print prototypes for function definitions
138  * -xpentium	Generate code for the pentium processor
139  * -xpg		Compile for profiling with gprof
140  * -xprofile=<p> Collect data for a profile or use a profile to optimize
141  *		<p>={{collect,use}[:<path>],tcov}
142  * -xregs=<r>	Control register allocation
143  * -xs		Allow debugging without object (.o) files
144  * -xsb		Compile for use with the WorkShop source browser
145  * -xsbfast	Generate only WorkShop source browser info, no compilation
146  * -xsfpconst	Represent unsuffixed floating point constants as single
147  *		precision
148  * -xspace	Do not do optimizations that increase code size
149  * -xstrconst	Place string literals into read-only data segment
150  * -xtarget=<t>	Specify target system for optimization
151  * -xtemp=<dir>	Set directory for temporary files to <dir>
152  * -xtime	Report the execution time for each compilation phase
153  * -xtransition	Emit warnings for differences between K&R C and ANSI C
154  * -xtrigraphs[=<yes|no>] Enable|disable trigraph translation
155  * -xunroll=n	Enable unrolling loops n times where possible
156  * -Y<c>,<dir>	Specify <dir> for location of component <c> (a,l,m,p,0,h,i,u)
157  * -YA,<dir>	Change default directory searched for components
158  * -YI,<dir>	Change default directory searched for include files
159  * -YP,<dir>	Change default directory for finding libraries files
160  * -YS,<dir>	Change default directory for startup object files
161  */
162 
163 /*
164  * Translation table:
165  */
166 /*
167  * -#				-v
168  * -###				error
169  * -A<name[(tokens)]>		pass-thru
170  * -B<[static|dynamic]>		pass-thru (syntax error for anything else)
171  * -C				pass-thru
172  * -c				pass-thru
173  * -cg92			-m32 -mcpu=v8 -mtune=supersparc (SPARC only)
174  * -D<name[=token]>		pass-thru
175  * -dy or -dn			-Wl,-dy or -Wl,-dn
176  * -E				pass-thru
177  * -erroff=E_EMPTY_TRANSLATION_UNIT ignore
178  * -errtags=%all		-Wall
179  * -errwarn=%all		-Werror else -Wno-error
180  * -fast			error
181  * -fd				error
182  * -flags			--help
183  * -fnonstd			error
184  * -fns[=<yes|no>]		error
185  * -fprecision=<p>		error
186  * -fround=<r>			error
187  * -fsimple[=<n>]		error
188  * -fsingle[=<n>]		error
189  * -ftrap=<t>			error
190  * -fstore			error
191  * -G				pass-thru
192  * -g				pass-thru
193  * -H				pass-thru
194  * -h <name>			pass-thru
195  * -I<dir>			pass-thru
196  * -i				pass-thru
197  * -keeptmp			-save-temps
198  * -KPIC			-fPIC
199  * -Kpic			-fpic
200  * -L<dir>			pass-thru
201  * -l<name>			pass-thru
202  * -mc				error
203  * -mr				error
204  * -mr,"string"			error
205  * -mt				-D_REENTRANT
206  * -native			error
207  * -nofstore			error
208  * -nolib			-nodefaultlibs
209  * -noqueue			ignore
210  * -norunpath			ignore
211  * -O				-O1 (Check the man page to be certain)
212  * -o <outputfile>		pass-thru
213  * -P				-E -o filename.i (or error)
214  * -PIC				-fPIC (C++ only)
215  * -p				pass-thru
216  * -pic				-fpic (C++ only)
217  * -Q[y|n]			error
218  * -qp				-p
219  * -R<dir[:dir]>		pass-thru
220  * -S				pass-thru
221  * -s				-Wl,-s
222  * -t				-Wl,-t
223  * -U<name>			pass-thru
224  * -V				--version
225  * -v				-Wall
226  * -Wa,<arg>			pass-thru
227  * -Wp,<arg>			pass-thru except -xc99=<a>
228  * -Wl,<arg>			pass-thru
229  * -W{m,0,2,h,i,u>		error/ignore
230  * -Wu,-xmodel=kernel		-ffreestanding -mcmodel=kernel -mno-red-zone
231  * -xmodel=kernel		-ffreestanding -mcmodel=kernel -mno-red-zone
232  * -Wu,-save_args		-msave-args
233  * -w				pass-thru
234  * -Xa				-std=iso9899:199409 or -ansi
235  * -Xc				-ansi -pedantic
236  * -Xt				error
237  * -Xs				-traditional -std=c89
238  * -x386			-march=i386 (x86 only)
239  * -x486			-march=i486 (x86 only)
240  * -xarch=<a>			table
241  * -xbuiltin[=<b>]		-fbuiltin (-fno-builtin otherwise)
242  * -xCC				ignore
243  * -xchar_byte_order=<o>	error
244  * -xchip=<c>			table
245  * -xcode=<c>			table
246  * -xdebugformat=<format>	ignore (always use dwarf-2 for gcc)
247  * -xcrossfile[=<n>]		ignore
248  * -xe				error
249  * -xF				error
250  * -xhelp=<f>			error
251  * -xildoff			ignore
252  * -xildon			ignore
253  * -xinline			ignore
254  * -xlibmieee			error
255  * -xlibmil			error
256  * -xlic_lib=sunperf		error
257  * -xM				-M
258  * -xM1				-MM
259  * -xmaxopt=[...]		error
260  * -xnolib			-nodefaultlibs
261  * -xnolibmil			error
262  * -xO<n>			-O<n>
263  * -xP				error
264  * -xpentium			-march=pentium (x86 only)
265  * -xpg				error
266  * -xprofile=<p>		error
267  * -xregs=<r>			table
268  * -xs				error
269  * -xsb				error
270  * -xsbfast			error
271  * -xsfpconst			error
272  * -xspace			ignore (-not -Os)
273  * -xstrconst			ignore
274  * -xtarget=<t>			table
275  * -xtemp=<dir>			error
276  * -xtime			error
277  * -xtransition			-Wtransition
278  * -xtrigraphs=<yes|no>		-trigraphs -notrigraphs
279  * -xunroll=n			error
280  * -W0,-xdbggen=no%usedonly	-fno-eliminate-unused-debug-symbols
281  *				-fno-eliminate-unused-debug-types
282  * -Y<c>,<dir>			error
283  * -YA,<dir>			error
284  * -YI,<dir>			-nostdinc -I<dir>
285  * -YP,<dir>			error
286  * -YS,<dir>			error
287  */
288 
289 #include <stdio.h>
290 #include <sys/types.h>
291 #include <unistd.h>
292 #include <string.h>
293 #include <stdlib.h>
294 #include <ctype.h>
295 #include <fcntl.h>
296 #include <errno.h>
297 #include <stdarg.h>
298 #include <sys/utsname.h>
299 #include <sys/param.h>
300 #include <sys/isa_defs.h>
301 #include <sys/wait.h>
302 #include <sys/stat.h>
303 
304 #define	CW_F_CXX	0x01
305 #define	CW_F_SHADOW	0x02
306 #define	CW_F_EXEC	0x04
307 #define	CW_F_ECHO	0x08
308 #define	CW_F_XLATE	0x10
309 #define	CW_F_PROG	0x20
310 
311 typedef enum cw_compiler {
312 	CW_C_CC = 0,
313 	CW_C_GCC
314 } cw_compiler_t;
315 
316 static const char *cmds[] = {
317 	"cc", "CC",
318 	"gcc", "g++"
319 };
320 
321 static const char *dirs[] = {
322 	DEFAULT_CC_DIR, DEFAULT_CPLUSPLUS_DIR,
323 	DEFAULT_GCC_DIR, DEFAULT_GPLUSPLUS_DIR
324 };
325 
326 #define	CC(ctx) \
327 	(((ctx)->i_flags & CW_F_SHADOW) ? \
328 	    ((ctx)->i_compiler == CW_C_CC ? CW_C_GCC : CW_C_CC) : \
329 	    (ctx)->i_compiler)
330 
331 #define	CIDX(compiler, flags)	\
332 	((int)(compiler) << 1) + ((flags) & CW_F_CXX ? 1 : 0)
333 
334 typedef enum cw_op {
335 	CW_O_NONE = 0,
336 	CW_O_PREPROCESS,
337 	CW_O_COMPILE,
338 	CW_O_LINK
339 } cw_op_t;
340 
341 struct aelist {
342 	struct ae {
343 		struct ae *ae_next;
344 		char *ae_arg;
345 	} *ael_head, *ael_tail;
346 	int ael_argc;
347 };
348 
349 typedef struct cw_ictx {
350 	cw_compiler_t	i_compiler;
351 	struct aelist	*i_ae;
352 	uint32_t	i_flags;
353 	int		i_oldargc;
354 	char		**i_oldargv;
355 	pid_t		i_pid;
356 	char		i_discard[MAXPATHLEN];
357 	char		*i_stderr;
358 } cw_ictx_t;
359 
360 /*
361  * Status values to indicate which Studio compiler and associated
362  * flags are being used.
363  */
364 #define	M32		0x01	/* -m32 - only on Studio 12 */
365 #define	M64		0x02	/* -m64 - only on Studio 12 */
366 #define	SS11		0x100	/* Studio 11 */
367 #define	SS12		0x200	/* Studio 12 */
368 
369 #define	TRANS_ENTRY	5
370 /*
371  * Translation table definition for the -xarch= flag. The "x_arg"
372  * value is translated into the appropriate gcc flags according
373  * to the values in x_trans[n]. The x_flags indicates what compiler
374  * is being used and what flags have been set via the use of
375  * "x_arg".
376  */
377 typedef struct xarch_table {
378 	char	*x_arg;
379 	int	x_flags;
380 	char	*x_trans[TRANS_ENTRY];
381 } xarch_table_t;
382 
383 /*
384  * The translation table for the -xarch= flag used in the Studio compilers.
385  */
386 static const xarch_table_t xtbl[] = {
387 #if defined(__x86)
388 	{ "generic",	SS11 },
389 	{ "generic64",	(SS11|M64), { "-m64", "-mtune=opteron" } },
390 	{ "amd64",	(SS11|M64), { "-m64", "-mtune=opteron" } },
391 	{ "386",	SS11,	{ "-march=i386" } },
392 	{ "pentium_pro", SS11,	{ "-march=pentiumpro" } },
393 #elif defined(__sparc)
394 	{ "generic",	(SS11|M32), { "-m32", "-mcpu=v8" } },
395 	{ "generic64",	(SS11|M64), { "-m64", "-mcpu=v9" } },
396 	{ "v8",		(SS11|M32), { "-m32", "-mcpu=v8", "-mno-v8plus" } },
397 	{ "v8plus",	(SS11|M32), { "-m32", "-mcpu=v9", "-mv8plus" } },
398 	{ "v8plusa",	(SS11|M32), { "-m32", "-mcpu=ultrasparc", "-mv8plus",
399 			"-mvis" } },
400 	{ "v8plusb",	(SS11|M32), { "-m32", "-mcpu=ultrasparc3", "-mv8plus",
401 			"-mvis" } },
402 	{ "v9",		(SS11|M64), { "-m64", "-mcpu=v9" } },
403 	{ "v9a",	(SS11|M64), { "-m64", "-mcpu=ultrasparc", "-mvis" } },
404 	{ "v9b",	(SS11|M64), { "-m64", "-mcpu=ultrasparc3", "-mvis" } },
405 	{ "sparc",	SS12, { "-mcpu=v9", "-mv8plus" } },
406 	{ "sparcvis",	SS12, { "-mcpu=ultrasparc", "-mvis" } },
407 	{ "sparcvis2",	SS12, { "-mcpu=ultrasparc3", "-mvis" } }
408 #endif
409 };
410 
411 static int xtbl_size = sizeof (xtbl) / sizeof (xarch_table_t);
412 
413 static const char *progname;
414 
415 static const char *xchip_tbl[] = {
416 #if defined(__x86)
417 	"386",		"-mtune=i386", NULL,
418 	"486",		"-mtune=i486", NULL,
419 	"pentium",	"-mtune=pentium", NULL,
420 	"pentium_pro",  "-mtune=pentiumpro", NULL,
421 #elif defined(__sparc)
422 	"super",	"-mtune=supersparc", NULL,
423 	"ultra",	"-mtune=ultrasparc", NULL,
424 	"ultra3",	"-mtune=ultrasparc3", NULL,
425 #endif
426 	NULL,		NULL
427 };
428 
429 static const char *xcode_tbl[] = {
430 #if defined(__sparc)
431 	"abs32",	"-fno-pic", "-mcmodel=medlow", NULL,
432 	"abs44",	"-fno-pic", "-mcmodel=medmid", NULL,
433 	"abs64",	"-fno-pic", "-mcmodel=medany", NULL,
434 	"pic13",	"-fpic", NULL,
435 	"pic32",	"-fPIC", NULL,
436 #endif
437 	NULL,		NULL
438 };
439 
440 static const char *xtarget_tbl[] = {
441 #if defined(__x86)
442 	"pentium_pro",	"-march=pentiumpro", NULL,
443 #endif	/* __x86 */
444 	NULL,		NULL
445 };
446 
447 static const char *xregs_tbl[] = {
448 #if defined(__sparc)
449 	"appl",		"-mapp-regs", NULL,
450 	"no%appl",	"-mno-app-regs", NULL,
451 	"float",	"-mfpu", NULL,
452 	"no%float",	"-mno-fpu", NULL,
453 #endif	/* __sparc */
454 	NULL,		NULL
455 };
456 
457 static void
458 nomem(void)
459 {
460 	(void) fprintf(stderr, "%s: error: out of memory\n", progname);
461 	exit(1);
462 }
463 
464 static void
465 cw_perror(const char *fmt, ...)
466 {
467 	va_list ap;
468 	int saved_errno = errno;
469 
470 	(void) fprintf(stderr, "%s: error: ", progname);
471 
472 	va_start(ap, fmt);
473 	(void) vfprintf(stderr, fmt, ap);
474 	va_end(ap);
475 
476 	(void) fprintf(stderr, " (%s)\n", strerror(saved_errno));
477 }
478 
479 static void
480 newae(struct aelist *ael, const char *arg)
481 {
482 	struct ae *ae;
483 
484 	if ((ae = calloc(sizeof (*ae), 1)) == NULL)
485 		nomem();
486 	ae->ae_arg = strdup(arg);
487 	if (ael->ael_tail == NULL)
488 		ael->ael_head = ae;
489 	else
490 		ael->ael_tail->ae_next = ae;
491 	ael->ael_tail = ae;
492 	ael->ael_argc++;
493 }
494 
495 static cw_ictx_t *
496 newictx(void)
497 {
498 	cw_ictx_t *ctx = calloc(sizeof (cw_ictx_t), 1);
499 	if (ctx)
500 		if ((ctx->i_ae = calloc(sizeof (struct aelist), 1)) == NULL) {
501 			free(ctx);
502 			return (NULL);
503 		}
504 
505 	return (ctx);
506 }
507 
508 static void
509 error(const char *arg)
510 {
511 	(void) fprintf(stderr,
512 	    "%s: error: mapping failed at or near arg '%s'\n", progname, arg);
513 	exit(2);
514 }
515 
516 /*
517  * Add the current favourite set of warnings to the gcc invocation.
518  */
519 static void
520 warnings(struct aelist *h)
521 {
522 	static int warningsonce;
523 
524 	if (warningsonce++)
525 		return;
526 
527 	newae(h, "-Wall");
528 	newae(h, "-Wno-unknown-pragmas");
529 	newae(h, "-Wno-missing-braces");
530 	newae(h, "-Wno-sign-compare");
531 	newae(h, "-Wno-parentheses");
532 	newae(h, "-Wno-uninitialized");
533 	newae(h, "-Wno-implicit-function-declaration");
534 	newae(h, "-Wno-unused");
535 	newae(h, "-Wno-trigraphs");
536 	newae(h, "-Wno-char-subscripts");
537 	newae(h, "-Wno-switch");
538 }
539 
540 static void
541 optim_disable(struct aelist *h, int level)
542 {
543 	if (level >= 2) {
544 		newae(h, "-fno-strict-aliasing");
545 		newae(h, "-fno-unit-at-a-time");
546 		newae(h, "-fno-optimize-sibling-calls");
547 	}
548 }
549 
550 /* ARGSUSED */
551 static void
552 Xamode(struct aelist *h)
553 {
554 }
555 
556 static void
557 Xcmode(struct aelist *h)
558 {
559 	static int xconce;
560 
561 	if (xconce++)
562 		return;
563 
564 	newae(h, "-ansi");
565 	newae(h, "-pedantic-errors");
566 }
567 
568 static void
569 Xsmode(struct aelist *h)
570 {
571 	static int xsonce;
572 
573 	if (xsonce++)
574 		return;
575 
576 	newae(h, "-traditional");
577 	newae(h, "-traditional-cpp");
578 }
579 
580 static void
581 usage()
582 {
583 	(void) fprintf(stderr,
584 	    "usage: %s { -_cc | -_gcc | -_CC | -_g++ } [ -_compiler | ... ]\n",
585 	    progname);
586 	exit(2);
587 }
588 
589 static int
590 xlate_xtb(struct aelist *h, const char *xarg)
591 {
592 	int	i, j;
593 
594 	for (i = 0; i < xtbl_size; i++) {
595 		if (strcmp(xtbl[i].x_arg, xarg) == 0)
596 			break;
597 	}
598 
599 	/*
600 	 * At the end of the table and so no matching "arg" entry
601 	 * found and so this must be a bad -xarch= flag.
602 	 */
603 	if (i == xtbl_size)
604 		error(xarg);
605 
606 	for (j = 0; j < TRANS_ENTRY; j++) {
607 		if (xtbl[i].x_trans[j] != NULL)
608 			newae(h, xtbl[i].x_trans[j]);
609 		else
610 			break;
611 	}
612 	return (xtbl[i].x_flags);
613 
614 }
615 
616 static void
617 xlate(struct aelist *h, const char *xarg, const char **table)
618 {
619 	while (*table != NULL && strcmp(xarg, *table) != 0) {
620 		while (*table != NULL)
621 			table++;
622 		table++;
623 	}
624 
625 	if (*table == NULL)
626 		error(xarg);
627 
628 	table++;
629 
630 	while (*table != NULL) {
631 		newae(h, *table);
632 		table++;
633 	}
634 }
635 
636 static void
637 do_gcc(cw_ictx_t *ctx)
638 {
639 	int c;
640 	int pic = 0, nolibc = 0;
641 	int in_output = 0, seen_o = 0, c_files = 0;
642 	cw_op_t op = CW_O_LINK;
643 	char *model = NULL;
644 	int	mflag = 0;
645 
646 	if (ctx->i_flags & CW_F_PROG) {
647 		newae(ctx->i_ae, "--version");
648 		return;
649 	}
650 
651 	newae(ctx->i_ae, "-fident");
652 	newae(ctx->i_ae, "-finline");
653 	newae(ctx->i_ae, "-fno-inline-functions");
654 	newae(ctx->i_ae, "-fno-builtin");
655 	newae(ctx->i_ae, "-fno-asm");
656 	newae(ctx->i_ae, "-nodefaultlibs");
657 
658 #if defined(__sparc)
659 	/*
660 	 * The SPARC ldd and std instructions require 8-byte alignment of
661 	 * their address operand.  gcc correctly uses them only when the
662 	 * ABI requires 8-byte alignment; unfortunately we have a number of
663 	 * pieces of buggy code that doesn't conform to the ABI.  This
664 	 * flag makes gcc work more like Studio with -xmemalign=4.
665 	 */
666 	newae(ctx->i_ae, "-mno-integer-ldd-std");
667 #endif
668 
669 	/*
670 	 * This is needed because 'u' is defined
671 	 * under a conditional on 'sun'.  Should
672 	 * probably just remove the conditional,
673 	 * or make it be dependent on '__sun'.
674 	 *
675 	 * -Dunix is also missing in enhanced ANSI mode
676 	 */
677 	newae(ctx->i_ae, "-D__sun");
678 
679 	/*
680 	 * Walk the argument list, translating as we go ..
681 	 */
682 
683 	while (--ctx->i_oldargc > 0) {
684 		char *arg = *++ctx->i_oldargv;
685 		size_t arglen = strlen(arg);
686 
687 		if (*arg == '-') {
688 			arglen--;
689 		} else {
690 			/*
691 			 * Discard inline files that gcc doesn't grok
692 			 */
693 			if (!in_output && arglen > 3 &&
694 			    strcmp(arg + arglen - 3, ".il") == 0)
695 				continue;
696 
697 			if (!in_output && arglen > 2 &&
698 			    arg[arglen - 2] == '.' &&
699 			    (arg[arglen - 1] == 'S' || arg[arglen - 1] == 's' ||
700 			    arg[arglen - 1] == 'c' || arg[arglen - 1] == 'i'))
701 				c_files++;
702 
703 			/*
704 			 * Otherwise, filenames and partial arguments
705 			 * are passed through for gcc to chew on.  However,
706 			 * output is always discarded for the secondary
707 			 * compiler.
708 			 */
709 			if ((ctx->i_flags & CW_F_SHADOW) && in_output)
710 				newae(ctx->i_ae, ctx->i_discard);
711 			else
712 				newae(ctx->i_ae, arg);
713 			in_output = 0;
714 			continue;
715 		}
716 
717 		if (ctx->i_flags & CW_F_CXX) {
718 			if (strncmp(arg, "-compat=", 8) == 0) {
719 				/* discard -compat=4 and -compat=5 */
720 				continue;
721 			}
722 			if (strcmp(arg, "-Qoption") == 0) {
723 				/* discard -Qoption and its two arguments */
724 				if (ctx->i_oldargc < 3)
725 					error(arg);
726 				ctx->i_oldargc -= 2;
727 				ctx->i_oldargv += 2;
728 				continue;
729 			}
730 			if (strcmp(arg, "-xwe") == 0) {
731 				/* turn warnings into errors */
732 				newae(ctx->i_ae, "-Werror");
733 				continue;
734 			}
735 			if (strcmp(arg, "-noex") == 0) {
736 				/* no exceptions */
737 				newae(ctx->i_ae, "-fno-exceptions");
738 				/* no run time type descriptor information */
739 				newae(ctx->i_ae, "-fno-rtti");
740 				continue;
741 			}
742 			if (strcmp(arg, "-pic") == 0) {
743 				newae(ctx->i_ae, "-fpic");
744 				pic = 1;
745 				continue;
746 			}
747 			if (strcmp(arg, "-PIC") == 0) {
748 				newae(ctx->i_ae, "-fPIC");
749 				pic = 1;
750 				continue;
751 			}
752 			if (strcmp(arg, "-norunpath") == 0) {
753 				/* gcc has no corresponding option */
754 				continue;
755 			}
756 			if (strcmp(arg, "-nolib") == 0) {
757 				/* -nodefaultlibs is on by default */
758 				nolibc = 1;
759 				continue;
760 			}
761 #if defined(__sparc)
762 			if (strcmp(arg, "-cg92") == 0) {
763 				mflag |= xlate_xtb(ctx->i_ae, "v8");
764 				xlate(ctx->i_ae, "super", xchip_tbl);
765 				continue;
766 			}
767 #endif	/* __sparc */
768 		}
769 
770 		switch ((c = arg[1])) {
771 		case '_':
772 			if (strcmp(arg, "-_noecho") == 0)
773 				ctx->i_flags &= ~CW_F_ECHO;
774 			else if (strncmp(arg, "-_cc=", 5) == 0 ||
775 			    strncmp(arg, "-_CC=", 5) == 0)
776 				/* EMPTY */;
777 			else if (strncmp(arg, "-_gcc=", 6) == 0 ||
778 			    strncmp(arg, "-_g++=", 6) == 0)
779 				newae(ctx->i_ae, arg + 6);
780 			else
781 				error(arg);
782 			break;
783 		case '#':
784 			if (arglen == 1) {
785 				newae(ctx->i_ae, "-v");
786 				break;
787 			}
788 			error(arg);
789 			break;
790 		case 'g':
791 			newae(ctx->i_ae, "-gdwarf-2");
792 			break;
793 		case 'E':
794 			if (arglen == 1) {
795 				newae(ctx->i_ae, "-xc");
796 				newae(ctx->i_ae, arg);
797 				op = CW_O_PREPROCESS;
798 				nolibc = 1;
799 				break;
800 			}
801 			error(arg);
802 			break;
803 		case 'c':
804 		case 'S':
805 			if (arglen == 1) {
806 				op = CW_O_COMPILE;
807 				nolibc = 1;
808 			}
809 			/* FALLTHROUGH */
810 		case 'C':
811 		case 'H':
812 		case 'p':
813 			if (arglen == 1) {
814 				newae(ctx->i_ae, arg);
815 				break;
816 			}
817 			error(arg);
818 			break;
819 		case 'A':
820 		case 'h':
821 		case 'I':
822 		case 'i':
823 		case 'L':
824 		case 'l':
825 		case 'R':
826 		case 'U':
827 		case 'u':
828 		case 'w':
829 			newae(ctx->i_ae, arg);
830 			break;
831 		case 'o':
832 			seen_o = 1;
833 			if (arglen == 1) {
834 				in_output = 1;
835 				newae(ctx->i_ae, arg);
836 			} else if (ctx->i_flags & CW_F_SHADOW) {
837 				newae(ctx->i_ae, "-o");
838 				newae(ctx->i_ae, ctx->i_discard);
839 			} else {
840 				newae(ctx->i_ae, arg);
841 			}
842 			break;
843 		case 'D':
844 			newae(ctx->i_ae, arg);
845 			/*
846 			 * XXX	Clearly a hack ... do we need _KADB too?
847 			 */
848 			if (strcmp(arg, "-D_KERNEL") == 0 ||
849 			    strcmp(arg, "-D_BOOT") == 0)
850 				newae(ctx->i_ae, "-ffreestanding");
851 			break;
852 		case 'd':
853 			if (arglen == 2) {
854 				if (strcmp(arg, "-dy") == 0) {
855 					newae(ctx->i_ae, "-Wl,-dy");
856 					break;
857 				}
858 				if (strcmp(arg, "-dn") == 0) {
859 					newae(ctx->i_ae, "-Wl,-dn");
860 					break;
861 				}
862 			}
863 			if (strcmp(arg, "-dalign") == 0) {
864 				/*
865 				 * -dalign forces alignment in some cases;
866 				 * gcc does not need any flag to do this.
867 				 */
868 				break;
869 			}
870 			error(arg);
871 			break;
872 		case 'e':
873 			if (strcmp(arg,
874 			    "-erroff=E_EMPTY_TRANSLATION_UNIT") == 0) {
875 				/*
876 				 * Accept but ignore this -- gcc doesn't
877 				 * seem to complain about empty translation
878 				 * units
879 				 */
880 				break;
881 			}
882 			/* XX64 -- ignore all -erroff= options, for now */
883 			if (strncmp(arg, "-erroff=", 8) == 0)
884 				break;
885 			if (strcmp(arg, "-errtags=yes") == 0) {
886 				warnings(ctx->i_ae);
887 				break;
888 			}
889 			if (strcmp(arg, "-errwarn=%all") == 0) {
890 				newae(ctx->i_ae, "-Werror");
891 				break;
892 			}
893 			error(arg);
894 			break;
895 		case 'f':
896 			if (strcmp(arg, "-flags") == 0) {
897 				newae(ctx->i_ae, "--help");
898 				break;
899 			}
900 			error(arg);
901 			break;
902 		case 'G':
903 			newae(ctx->i_ae, "-shared");
904 			nolibc = 1;
905 			break;
906 		case 'k':
907 			if (strcmp(arg, "-keeptmp") == 0) {
908 				newae(ctx->i_ae, "-save-temps");
909 				break;
910 			}
911 			error(arg);
912 			break;
913 		case 'K':
914 			if (arglen == 1) {
915 				if ((arg = *++ctx->i_oldargv) == NULL ||
916 				    *arg == '\0')
917 					error("-K");
918 				ctx->i_oldargc--;
919 			} else {
920 				arg += 2;
921 			}
922 			if (strcmp(arg, "pic") == 0) {
923 				newae(ctx->i_ae, "-fpic");
924 				pic = 1;
925 				break;
926 			}
927 			if (strcmp(arg, "PIC") == 0) {
928 				newae(ctx->i_ae, "-fPIC");
929 				pic = 1;
930 				break;
931 			}
932 			error("-K");
933 			break;
934 		case 'm':
935 			if (strcmp(arg, "-mt") == 0) {
936 				newae(ctx->i_ae, "-D_REENTRANT");
937 				break;
938 			}
939 			if (strcmp(arg, "-m64") == 0) {
940 				newae(ctx->i_ae, "-m64");
941 #if defined(__x86)
942 				newae(ctx->i_ae, "-mtune=opteron");
943 #endif
944 				mflag |= M64;
945 				break;
946 			}
947 			if (strcmp(arg, "-m32") == 0) {
948 				newae(ctx->i_ae, "-m32");
949 				mflag |= M32;
950 				break;
951 			}
952 			error(arg);
953 			break;
954 		case 'B':	/* linker options */
955 		case 'M':
956 		case 'z':
957 			{
958 				char *opt;
959 				size_t len;
960 				char *s;
961 
962 				if (arglen == 1) {
963 					opt = *++ctx->i_oldargv;
964 					if (opt == NULL || *opt == '\0')
965 						error(arg);
966 					ctx->i_oldargc--;
967 				} else {
968 					opt = arg + 2;
969 				}
970 				len = strlen(opt) + 7;
971 				if ((s = malloc(len)) == NULL)
972 					nomem();
973 				(void) snprintf(s, len, "-Wl,-%c%s", c, opt);
974 				newae(ctx->i_ae, s);
975 				free(s);
976 			}
977 			break;
978 		case 'n':
979 			if (strcmp(arg, "-noqueue") == 0) {
980 				/*
981 				 * Horrid license server stuff - n/a
982 				 */
983 				break;
984 			}
985 			error(arg);
986 			break;
987 		case 'O':
988 			if (arglen == 1) {
989 				newae(ctx->i_ae, "-O");
990 				break;
991 			}
992 			error(arg);
993 			break;
994 		case 'P':
995 			/*
996 			 * We could do '-E -o filename.i', but that's hard,
997 			 * and we don't need it for the case that's triggering
998 			 * this addition.  We'll require the user to specify
999 			 * -o in the Makefile.  If they don't they'll find out
1000 			 * in a hurry.
1001 			 */
1002 			newae(ctx->i_ae, "-E");
1003 			op = CW_O_PREPROCESS;
1004 			nolibc = 1;
1005 			break;
1006 		case 'q':
1007 			if (strcmp(arg, "-qp") == 0) {
1008 				newae(ctx->i_ae, "-p");
1009 				break;
1010 			}
1011 			error(arg);
1012 			break;
1013 		case 's':
1014 			if (arglen == 1) {
1015 				newae(ctx->i_ae, "-Wl,-s");
1016 				break;
1017 			}
1018 			error(arg);
1019 			break;
1020 		case 't':
1021 			if (arglen == 1) {
1022 				newae(ctx->i_ae, "-Wl,-t");
1023 				break;
1024 			}
1025 			error(arg);
1026 			break;
1027 		case 'V':
1028 			if (arglen == 1) {
1029 				ctx->i_flags &= ~CW_F_ECHO;
1030 				newae(ctx->i_ae, "--version");
1031 				break;
1032 			}
1033 			error(arg);
1034 			break;
1035 		case 'v':
1036 			if (arglen == 1) {
1037 				warnings(ctx->i_ae);
1038 				break;
1039 			}
1040 			error(arg);
1041 			break;
1042 		case 'W':
1043 			if (strncmp(arg, "-Wp,-xc99", 9) == 0) {
1044 				/*
1045 				 * gcc's preprocessor will accept c99
1046 				 * regardless, so accept and ignore.
1047 				 */
1048 				break;
1049 			}
1050 			if (strncmp(arg, "-Wa,", 4) == 0 ||
1051 			    strncmp(arg, "-Wp,", 4) == 0 ||
1052 			    strncmp(arg, "-Wl,", 4) == 0) {
1053 				newae(ctx->i_ae, arg);
1054 				break;
1055 			}
1056 			if (strcmp(arg, "-W0,-xc99=pragma") == 0) {
1057 				/* (undocumented) enables _Pragma */
1058 				break;
1059 			}
1060 			if (strcmp(arg, "-W0,-xc99=%none") == 0) {
1061 				/*
1062 				 * This is a polite way of saying
1063 				 * "no c99 constructs allowed!"
1064 				 * For now, just accept and ignore this.
1065 				 */
1066 				break;
1067 			}
1068 			if (strcmp(arg, "-W0,-noglobal") == 0 ||
1069 			    strcmp(arg, "-W0,-xglobalstatic") == 0) {
1070 				/*
1071 				 * gcc doesn't prefix local symbols
1072 				 * in debug mode, so this is not needed.
1073 				 */
1074 				break;
1075 			}
1076 			if (strcmp(arg, "-W0,-Lt") == 0) {
1077 				/*
1078 				 * Generate tests at the top of loops.
1079 				 * There is no direct gcc equivalent, ignore.
1080 				 */
1081 				break;
1082 			}
1083 			if (strcmp(arg, "-W0,-xdbggen=no%usedonly") == 0) {
1084 				newae(ctx->i_ae,
1085 				    "-fno-eliminate-unused-debug-symbols");
1086 				newae(ctx->i_ae,
1087 				    "-fno-eliminate-unused-debug-types");
1088 				break;
1089 			}
1090 			if (strcmp(arg, "-W2,-xwrap_int") == 0) {
1091 				/*
1092 				 * Use the legacy behaviour (pre-SS11)
1093 				 * for integer wrapping.
1094 				 * gcc does not need this.
1095 				 */
1096 				break;
1097 			}
1098 			if (strcmp(arg, "-W2,-Rcond_elim") == 0) {
1099 				/*
1100 				 * Elimination and expansion of conditionals;
1101 				 * gcc has no direct equivalent.
1102 				 */
1103 				break;
1104 			}
1105 			if (strcmp(arg, "-Wd,-xsafe=unboundsym") == 0) {
1106 				/*
1107 				 * Prevents optimizing away checks for
1108 				 * unbound weak symbol addresses.  gcc does
1109 				 * not do this, so it's not needed.
1110 				 */
1111 				break;
1112 			}
1113 			if (strncmp(arg, "-Wc,-xcode=", 11) == 0) {
1114 				xlate(ctx->i_ae, arg + 11, xcode_tbl);
1115 				if (strncmp(arg + 11, "pic", 3) == 0)
1116 					pic = 1;
1117 				break;
1118 			}
1119 			if (strncmp(arg, "-Wc,-Qiselect", 13) == 0) {
1120 				/*
1121 				 * Prevents insertion of register symbols.
1122 				 * gcc doesn't do this, so ignore it.
1123 				 */
1124 				break;
1125 			}
1126 			if (strcmp(arg, "-Wc,-Qassembler-ounrefsym=0") == 0) {
1127 				/*
1128 				 * Prevents optimizing away of static variables.
1129 				 * gcc does not do this, so it's not needed.
1130 				 */
1131 				break;
1132 			}
1133 #if defined(__x86)
1134 			if (strcmp(arg, "-Wu,-no_got_reloc") == 0) {
1135 				newae(ctx->i_ae, "-fno-jump-tables");
1136 				newae(ctx->i_ae, "-fno-constant-pools");
1137 				break;
1138 			}
1139 			if (strcmp(arg, "-Wu,-xmodel=kernel") == 0) {
1140 				newae(ctx->i_ae, "-ffreestanding");
1141 				newae(ctx->i_ae, "-mno-red-zone");
1142 				model = "-mcmodel=kernel";
1143 				nolibc = 1;
1144 				break;
1145 			}
1146 			if (strcmp(arg, "-Wu,-save_args") == 0) {
1147 				newae(ctx->i_ae, "-msave-args");
1148 				break;
1149 			}
1150 #endif	/* __x86 */
1151 			error(arg);
1152 			break;
1153 		case 'X':
1154 			if (strcmp(arg, "-Xa") == 0 ||
1155 			    strcmp(arg, "-Xt") == 0) {
1156 				Xamode(ctx->i_ae);
1157 				break;
1158 			}
1159 			if (strcmp(arg, "-Xc") == 0) {
1160 				Xcmode(ctx->i_ae);
1161 				break;
1162 			}
1163 			if (strcmp(arg, "-Xs") == 0) {
1164 				Xsmode(ctx->i_ae);
1165 				break;
1166 			}
1167 			error(arg);
1168 			break;
1169 		case 'x':
1170 			if (arglen == 1)
1171 				error(arg);
1172 			switch (arg[2]) {
1173 #if defined(__x86)
1174 			case '3':
1175 				if (strcmp(arg, "-x386") == 0) {
1176 					newae(ctx->i_ae, "-march=i386");
1177 					break;
1178 				}
1179 				error(arg);
1180 				break;
1181 			case '4':
1182 				if (strcmp(arg, "-x486") == 0) {
1183 					newae(ctx->i_ae, "-march=i486");
1184 					break;
1185 				}
1186 				error(arg);
1187 				break;
1188 #endif	/* __x86 */
1189 			case 'a':
1190 				if (strncmp(arg, "-xarch=", 7) == 0) {
1191 					mflag |= xlate_xtb(ctx->i_ae, arg + 7);
1192 					break;
1193 				}
1194 				error(arg);
1195 				break;
1196 			case 'b':
1197 				if (strncmp(arg, "-xbuiltin=", 10) == 0) {
1198 					if (strcmp(arg + 10, "%all"))
1199 						newae(ctx->i_ae, "-fbuiltin");
1200 					break;
1201 				}
1202 				error(arg);
1203 				break;
1204 			case 'C':
1205 				/* Accept C++ style comments -- ignore */
1206 				if (strcmp(arg, "-xCC") == 0)
1207 					break;
1208 				error(arg);
1209 				break;
1210 			case 'c':
1211 				if (strncmp(arg, "-xc99=%all", 10) == 0) {
1212 					newae(ctx->i_ae, "-std=gnu99");
1213 					break;
1214 				}
1215 				if (strncmp(arg, "-xc99=%none", 11) == 0) {
1216 					newae(ctx->i_ae, "-std=gnu89");
1217 					break;
1218 				}
1219 				if (strncmp(arg, "-xchip=", 7) == 0) {
1220 					xlate(ctx->i_ae, arg + 7, xchip_tbl);
1221 					break;
1222 				}
1223 				if (strncmp(arg, "-xcode=", 7) == 0) {
1224 					xlate(ctx->i_ae, arg + 7, xcode_tbl);
1225 					if (strncmp(arg + 7, "pic", 3) == 0)
1226 						pic = 1;
1227 					break;
1228 				}
1229 				if (strncmp(arg, "-xcache=", 8) == 0)
1230 					break;
1231 				if (strncmp(arg, "-xcrossfile", 11) == 0)
1232 					break;
1233 				error(arg);
1234 				break;
1235 			case 'd':
1236 				if (strcmp(arg, "-xdepend") == 0)
1237 					break;
1238 				if (strncmp(arg, "-xdebugformat=", 14) == 0)
1239 					break;
1240 				error(arg);
1241 				break;
1242 			case 'F':
1243 				/*
1244 				 * Compile for mapfile reordering, or unused
1245 				 * section elimination, syntax can be -xF or
1246 				 * more complex, like -xF=%all -- ignore.
1247 				 */
1248 				if (strncmp(arg, "-xF", 3) == 0)
1249 					break;
1250 				error(arg);
1251 				break;
1252 			case 'i':
1253 				if (strncmp(arg, "-xinline", 8) == 0)
1254 					/* No inlining; ignore */
1255 					break;
1256 				if (strcmp(arg, "-xildon") == 0 ||
1257 				    strcmp(arg, "-xildoff") == 0)
1258 					/* No incremental linking; ignore */
1259 					break;
1260 				error(arg);
1261 				break;
1262 #if defined(__x86)
1263 			case 'm':
1264 				if (strcmp(arg, "-xmodel=kernel") == 0) {
1265 					newae(ctx->i_ae, "-ffreestanding");
1266 					newae(ctx->i_ae, "-mno-red-zone");
1267 					model = "-mcmodel=kernel";
1268 					nolibc = 1;
1269 					break;
1270 				}
1271 				error(arg);
1272 				break;
1273 #endif	/* __x86 */
1274 			case 'M':
1275 				if (strcmp(arg, "-xM") == 0) {
1276 					newae(ctx->i_ae, "-M");
1277 					break;
1278 				}
1279 				if (strcmp(arg, "-xM1") == 0) {
1280 					newae(ctx->i_ae, "-MM");
1281 					break;
1282 				}
1283 				error(arg);
1284 				break;
1285 			case 'n':
1286 				if (strcmp(arg, "-xnolib") == 0) {
1287 					nolibc = 1;
1288 					break;
1289 				}
1290 				error(arg);
1291 				break;
1292 			case 'O':
1293 				if (strncmp(arg, "-xO", 3) == 0) {
1294 					size_t len = strlen(arg);
1295 					char *s;
1296 					int c = *(arg + 3);
1297 					int level;
1298 
1299 					if (len != 4 || !isdigit(c))
1300 						error(arg);
1301 
1302 					if ((s = malloc(len)) == NULL)
1303 						nomem();
1304 
1305 					level = atoi(arg + 3);
1306 					if (level > 5)
1307 						error(arg);
1308 					if (level >= 2) {
1309 						/*
1310 						 * For gcc-3.4.x at -O2 we
1311 						 * need to disable optimizations
1312 						 * that break ON.
1313 						 */
1314 						optim_disable(ctx->i_ae, level);
1315 						/*
1316 						 * limit -xO3 to -O2 as well.
1317 						 */
1318 						level = 2;
1319 					}
1320 					(void) snprintf(s, len, "-O%d", level);
1321 					newae(ctx->i_ae, s);
1322 					free(s);
1323 					break;
1324 				}
1325 				error(arg);
1326 				break;
1327 			case 'p':
1328 				if (strcmp(arg, "-xpentium") == 0) {
1329 					newae(ctx->i_ae, "-march=pentium");
1330 					break;
1331 				}
1332 				if (strcmp(arg, "-xpg") == 0) {
1333 					newae(ctx->i_ae, "-pg");
1334 					break;
1335 				}
1336 				error(arg);
1337 				break;
1338 			case 'r':
1339 				if (strncmp(arg, "-xregs=", 7) == 0) {
1340 					xlate(ctx->i_ae, arg + 7, xregs_tbl);
1341 					break;
1342 				}
1343 				error(arg);
1344 				break;
1345 			case 's':
1346 				if (strcmp(arg, "-xs") == 0 ||
1347 				    strcmp(arg, "-xspace") == 0 ||
1348 				    strcmp(arg, "-xstrconst") == 0)
1349 					break;
1350 				error(arg);
1351 				break;
1352 			case 't':
1353 				if (strcmp(arg, "-xtransition") == 0) {
1354 					newae(ctx->i_ae, "-Wtransition");
1355 					break;
1356 				}
1357 				if (strcmp(arg, "-xtrigraphs=yes") == 0) {
1358 					newae(ctx->i_ae, "-trigraphs");
1359 					break;
1360 				}
1361 				if (strcmp(arg, "-xtrigraphs=no") == 0) {
1362 					newae(ctx->i_ae, "-notrigraphs");
1363 					break;
1364 				}
1365 				if (strncmp(arg, "-xtarget=", 9) == 0) {
1366 					xlate(ctx->i_ae, arg + 9, xtarget_tbl);
1367 					break;
1368 				}
1369 				error(arg);
1370 				break;
1371 			case 'e':
1372 			case 'h':
1373 			case 'l':
1374 			default:
1375 				error(arg);
1376 				break;
1377 			}
1378 			break;
1379 		case 'Y':
1380 			if (arglen == 1) {
1381 				if ((arg = *++ctx->i_oldargv) == NULL ||
1382 				    *arg == '\0')
1383 					error("-Y");
1384 				ctx->i_oldargc--;
1385 				arglen = strlen(arg + 1);
1386 			} else {
1387 				arg += 2;
1388 			}
1389 			/* Just ignore -YS,... for now */
1390 			if (strncmp(arg, "S,", 2) == 0)
1391 				break;
1392 			if (strncmp(arg, "l,", 2) == 0) {
1393 				char *s = strdup(arg);
1394 				s[0] = '-';
1395 				s[1] = 'B';
1396 				newae(ctx->i_ae, s);
1397 				free(s);
1398 				break;
1399 			}
1400 			if (strncmp(arg, "I,", 2) == 0) {
1401 				char *s = strdup(arg);
1402 				s[0] = '-';
1403 				s[1] = 'I';
1404 				newae(ctx->i_ae, "-nostdinc");
1405 				newae(ctx->i_ae, s);
1406 				free(s);
1407 				break;
1408 			}
1409 			error(arg);
1410 			break;
1411 		case 'Q':
1412 			/*
1413 			 * We could map -Qy into -Wl,-Qy etc.
1414 			 */
1415 		default:
1416 			error(arg);
1417 			break;
1418 		}
1419 	}
1420 
1421 	if (c_files > 1 && (ctx->i_flags & CW_F_SHADOW) &&
1422 	    op != CW_O_PREPROCESS) {
1423 		(void) fprintf(stderr, "%s: error: multiple source files are "
1424 		    "allowed only with -E or -P\n", progname);
1425 		exit(2);
1426 	}
1427 
1428 	/*
1429 	 * Make sure that we do not have any unintended interactions between
1430 	 * the xarch options passed in and the version of the Studio compiler
1431 	 * used.
1432 	 */
1433 	if ((mflag & (SS11|SS12)) == (SS11|SS12)) {
1434 		(void) fprintf(stderr,
1435 		    "Conflicting \"-xarch=\" flags (both Studio 11 and 12)\n");
1436 		exit(2);
1437 	}
1438 
1439 	switch (mflag) {
1440 	case 0:
1441 		/* FALLTHROUGH */
1442 	case M32:
1443 #if defined(__sparc)
1444 		/*
1445 		 * Only -m32 is defined and so put in the missing xarch
1446 		 * translation.
1447 		 */
1448 		newae(ctx->i_ae, "-mcpu=v8");
1449 		newae(ctx->i_ae, "-mno-v8plus");
1450 #endif
1451 		break;
1452 	case M64:
1453 #if defined(__sparc)
1454 		/*
1455 		 * Only -m64 is defined and so put in the missing xarch
1456 		 * translation.
1457 		 */
1458 		newae(ctx->i_ae, "-mcpu=v9");
1459 #endif
1460 		break;
1461 	case SS12:
1462 #if defined(__sparc)
1463 		/* no -m32/-m64 flag used - this is an error for sparc builds */
1464 		(void) fprintf(stderr, "No -m32/-m64 flag defined\n");
1465 		exit(2);
1466 #endif
1467 		break;
1468 	case SS11:
1469 		/* FALLTHROUGH */
1470 	case (SS11|M32):
1471 	case (SS11|M64):
1472 		break;
1473 	case (SS12|M32):
1474 #if defined(__sparc)
1475 		/*
1476 		 * Need to add in further 32 bit options because with SS12
1477 		 * the xarch=sparcvis option can be applied to 32 or 64
1478 		 * bit, and so the translatation table (xtbl) cannot handle
1479 		 * that.
1480 		 */
1481 		newae(ctx->i_ae, "-mv8plus");
1482 #endif
1483 		break;
1484 	case (SS12|M64):
1485 		break;
1486 	default:
1487 		(void) fprintf(stderr,
1488 		    "Incompatible -xarch= and/or -m32/-m64 options used.\n");
1489 		exit(2);
1490 	}
1491 	if (op == CW_O_LINK && (ctx->i_flags & CW_F_SHADOW))
1492 		exit(0);
1493 
1494 	if (model && !pic)
1495 		newae(ctx->i_ae, model);
1496 	if (!nolibc)
1497 		newae(ctx->i_ae, "-lc");
1498 	if (!seen_o && (ctx->i_flags & CW_F_SHADOW)) {
1499 		newae(ctx->i_ae, "-o");
1500 		newae(ctx->i_ae, ctx->i_discard);
1501 	}
1502 }
1503 
1504 static void
1505 do_cc(cw_ictx_t *ctx)
1506 {
1507 	int in_output = 0, seen_o = 0;
1508 	cw_op_t op = CW_O_LINK;
1509 
1510 	if (ctx->i_flags & CW_F_PROG) {
1511 		newae(ctx->i_ae, "-V");
1512 		return;
1513 	}
1514 
1515 	while (--ctx->i_oldargc > 0) {
1516 		char *arg = *++ctx->i_oldargv;
1517 
1518 		if (*arg != '-') {
1519 			if (in_output == 0 || !(ctx->i_flags & CW_F_SHADOW)) {
1520 				newae(ctx->i_ae, arg);
1521 			} else {
1522 				in_output = 0;
1523 				newae(ctx->i_ae, ctx->i_discard);
1524 			}
1525 			continue;
1526 		}
1527 		switch (*(arg + 1)) {
1528 		case '_':
1529 			if (strcmp(arg, "-_noecho") == 0) {
1530 				ctx->i_flags &= ~CW_F_ECHO;
1531 			} else if (strncmp(arg, "-_cc=", 5) == 0 ||
1532 			    strncmp(arg, "-_CC=", 5) == 0) {
1533 				newae(ctx->i_ae, arg + 5);
1534 			} else if (strncmp(arg, "-_gcc=", 6) != 0 &&
1535 			    strncmp(arg, "-_g++=", 6) != 0) {
1536 				(void) fprintf(stderr,
1537 				    "%s: invalid argument '%s'\n", progname,
1538 				    arg);
1539 				exit(2);
1540 			}
1541 			break;
1542 		case 'V':
1543 			ctx->i_flags &= ~CW_F_ECHO;
1544 			newae(ctx->i_ae, arg);
1545 			break;
1546 		case 'o':
1547 			seen_o = 1;
1548 			if (strlen(arg) == 2) {
1549 				in_output = 1;
1550 				newae(ctx->i_ae, arg);
1551 			} else if (ctx->i_flags & CW_F_SHADOW) {
1552 				newae(ctx->i_ae, "-o");
1553 				newae(ctx->i_ae, ctx->i_discard);
1554 			} else {
1555 				newae(ctx->i_ae, arg);
1556 			}
1557 			break;
1558 		case 'c':
1559 		case 'S':
1560 			if (strlen(arg) == 2)
1561 				op = CW_O_COMPILE;
1562 			newae(ctx->i_ae, arg);
1563 			break;
1564 		case 'E':
1565 		case 'P':
1566 			if (strlen(arg) == 2)
1567 				op = CW_O_PREPROCESS;
1568 		/*FALLTHROUGH*/
1569 		default:
1570 			newae(ctx->i_ae, arg);
1571 		}
1572 	}
1573 
1574 	if ((op == CW_O_LINK || op == CW_O_PREPROCESS) &&
1575 	    (ctx->i_flags & CW_F_SHADOW))
1576 		exit(0);
1577 
1578 	if (!seen_o && (ctx->i_flags & CW_F_SHADOW)) {
1579 		newae(ctx->i_ae, "-o");
1580 		newae(ctx->i_ae, ctx->i_discard);
1581 	}
1582 }
1583 
1584 static void
1585 prepctx(cw_ictx_t *ctx)
1586 {
1587 	const char *dir, *cmd;
1588 	char *program;
1589 	size_t len;
1590 
1591 	dir = dirs[CIDX(CC(ctx), ctx->i_flags)];
1592 	cmd = cmds[CIDX(CC(ctx), ctx->i_flags)];
1593 	len = strlen(dir) + strlen(cmd) + 2;
1594 	if ((program = malloc(len)) == NULL)
1595 		nomem();
1596 	(void) snprintf(program, len, "%s/%s", dir, cmd);
1597 
1598 	newae(ctx->i_ae, program);
1599 
1600 	if (ctx->i_flags & CW_F_PROG) {
1601 		(void) printf("%s: %s\n", (ctx->i_flags & CW_F_SHADOW) ?
1602 		    "shadow" : "primary", program);
1603 		(void) fflush(stdout);
1604 	}
1605 
1606 	if (!(ctx->i_flags & CW_F_XLATE))
1607 		return;
1608 
1609 	switch (CC(ctx)) {
1610 	case CW_C_CC:
1611 		do_cc(ctx);
1612 		break;
1613 	case CW_C_GCC:
1614 		do_gcc(ctx);
1615 		break;
1616 	}
1617 }
1618 
1619 static int
1620 invoke(cw_ictx_t *ctx)
1621 {
1622 	char **newargv;
1623 	int ac;
1624 	struct ae *a;
1625 
1626 	if ((newargv = calloc(sizeof (*newargv), ctx->i_ae->ael_argc + 1)) ==
1627 	    NULL)
1628 		nomem();
1629 
1630 	if (ctx->i_flags & CW_F_ECHO)
1631 		(void) fprintf(stderr, "+ ");
1632 
1633 	for (ac = 0, a = ctx->i_ae->ael_head; a; a = a->ae_next, ac++) {
1634 		newargv[ac] = a->ae_arg;
1635 		if (ctx->i_flags & CW_F_ECHO)
1636 			(void) fprintf(stderr, "%s ", a->ae_arg);
1637 		if (a == ctx->i_ae->ael_tail)
1638 			break;
1639 	}
1640 
1641 	if (ctx->i_flags & CW_F_ECHO) {
1642 		(void) fprintf(stderr, "\n");
1643 		(void) fflush(stderr);
1644 	}
1645 
1646 	if (!(ctx->i_flags & CW_F_EXEC))
1647 		return (0);
1648 
1649 	/*
1650 	 * We must fix up the environment here so that the
1651 	 * dependency files are not trampled by the shadow compiler.
1652 	 */
1653 	if ((ctx->i_flags & CW_F_SHADOW) &&
1654 	    (unsetenv("SUNPRO_DEPENDENCIES") != 0 ||
1655 	    unsetenv("DEPENDENCIES_OUTPUT") != 0)) {
1656 		(void) fprintf(stderr, "error: environment setup failed: %s\n",
1657 		    strerror(errno));
1658 		return (-1);
1659 	}
1660 
1661 	(void) execv(newargv[0], newargv);
1662 	cw_perror("couldn't run %s", newargv[0]);
1663 
1664 	return (-1);
1665 }
1666 
1667 static int
1668 reap(cw_ictx_t *ctx)
1669 {
1670 	int status, ret = 0;
1671 	char buf[1024];
1672 	struct stat s;
1673 
1674 	do {
1675 		(void) waitpid(ctx->i_pid, &status, 0);
1676 		if (status != 0) {
1677 			if (WIFSIGNALED(status)) {
1678 				ret = -WTERMSIG(status);
1679 				break;
1680 			} else if (WIFEXITED(status)) {
1681 				ret = WEXITSTATUS(status);
1682 				break;
1683 			}
1684 		}
1685 	} while (!WIFEXITED(status) && !WIFSIGNALED(status));
1686 
1687 	(void) unlink(ctx->i_discard);
1688 
1689 	if (stat(ctx->i_stderr, &s) < 0) {
1690 		cw_perror("stat failed on child cleanup");
1691 		return (-1);
1692 	}
1693 	if (s.st_size != 0) {
1694 		FILE *f;
1695 
1696 		if ((f = fopen(ctx->i_stderr, "r")) != NULL) {
1697 			while (fgets(buf, sizeof (buf), f))
1698 				(void) fprintf(stderr, "%s", buf);
1699 			(void) fflush(stderr);
1700 			(void) fclose(f);
1701 		}
1702 	}
1703 	(void) unlink(ctx->i_stderr);
1704 	free(ctx->i_stderr);
1705 
1706 	/*
1707 	 * cc returns an error code when given -V; we want that to succeed.
1708 	 */
1709 	if (ctx->i_flags & CW_F_PROG)
1710 		return (0);
1711 
1712 	return (ret);
1713 }
1714 
1715 static int
1716 exec_ctx(cw_ictx_t *ctx, int block)
1717 {
1718 	char *file;
1719 
1720 	/*
1721 	 * To avoid offending cc's sensibilities, the name of its output
1722 	 * file must end in '.o'.
1723 	 */
1724 	if ((file = tempnam(NULL, ".cw")) == NULL) {
1725 		nomem();
1726 		return (-1);
1727 	}
1728 	(void) strlcpy(ctx->i_discard, file, MAXPATHLEN);
1729 	(void) strlcat(ctx->i_discard, ".o", MAXPATHLEN);
1730 	free(file);
1731 
1732 	if ((ctx->i_stderr = tempnam(NULL, ".cw")) == NULL) {
1733 		nomem();
1734 		return (-1);
1735 	}
1736 
1737 	if ((ctx->i_pid = fork()) == 0) {
1738 		int fd;
1739 
1740 		(void) fclose(stderr);
1741 		if ((fd = open(ctx->i_stderr, O_WRONLY | O_CREAT | O_EXCL,
1742 		    0666)) < 0) {
1743 			cw_perror("open failed for standard error");
1744 			exit(1);
1745 		}
1746 		if (dup2(fd, 2) < 0) {
1747 			cw_perror("dup2 failed for standard error");
1748 			exit(1);
1749 		}
1750 		if (fd != 2)
1751 			(void) close(fd);
1752 		if (freopen("/dev/fd/2", "w", stderr) == NULL) {
1753 			cw_perror("freopen failed for /dev/fd/2");
1754 			exit(1);
1755 		}
1756 		prepctx(ctx);
1757 		exit(invoke(ctx));
1758 	}
1759 
1760 	if (ctx->i_pid < 0) {
1761 		cw_perror("fork failed");
1762 		return (1);
1763 	}
1764 
1765 	if (block)
1766 		return (reap(ctx));
1767 
1768 	return (0);
1769 }
1770 
1771 int
1772 main(int argc, char **argv)
1773 {
1774 	cw_ictx_t *ctx = newictx();
1775 	cw_ictx_t *ctx_shadow = newictx();
1776 	const char *dir;
1777 	char cc_buf[MAXPATHLEN], gcc_buf[MAXPATHLEN];
1778 	int do_serial, do_shadow;
1779 	int ret = 0;
1780 
1781 	if ((progname = strrchr(argv[0], '/')) == NULL)
1782 		progname = argv[0];
1783 	else
1784 		progname++;
1785 
1786 	if (ctx == NULL || ctx_shadow == NULL)
1787 		nomem();
1788 
1789 	ctx->i_flags = CW_F_ECHO|CW_F_XLATE;
1790 
1791 	/*
1792 	 * Figure out where to get our tools from.  This depends on
1793 	 * the environment variables set at run time.
1794 	 */
1795 	if ((dir = getenv("SPRO_VROOT")) != NULL) {
1796 		(void) snprintf(cc_buf, MAXPATHLEN, "%s/bin", dir);
1797 	} else if ((dir = getenv("SPRO_ROOT")) != NULL) {
1798 		(void) snprintf(cc_buf, MAXPATHLEN, "%s/SS12/bin", dir);
1799 	} else if ((dir = getenv("BUILD_TOOLS")) != NULL) {
1800 		(void) snprintf(cc_buf, MAXPATHLEN,
1801 		    "%s/SUNWspro/SS12/bin", dir);
1802 	}
1803 	if (dir != NULL) {
1804 		dirs[CIDX(CW_C_CC, 0)] = (const char *)cc_buf;
1805 		dirs[CIDX(CW_C_CC, CW_F_CXX)] = (const char *)cc_buf;
1806 	}
1807 
1808 	if ((dir = getenv("GNU_ROOT")) != NULL) {
1809 		(void) snprintf(gcc_buf, MAXPATHLEN, "%s/bin", dir);
1810 		dirs[CIDX(CW_C_GCC, 0)] = (const char *)gcc_buf;
1811 		dirs[CIDX(CW_C_GCC, CW_F_CXX)] = (const char *)gcc_buf;
1812 	}
1813 
1814 	if ((dir = getenv("CW_CC_DIR")) != NULL)
1815 		dirs[CIDX(CW_C_CC, 0)] = dir;
1816 	if ((dir = getenv("CW_CPLUSPLUS_DIR")) != NULL)
1817 		dirs[CIDX(CW_C_CC, CW_F_CXX)] = dir;
1818 	if ((dir = getenv("CW_GCC_DIR")) != NULL)
1819 		dirs[CIDX(CW_C_GCC, 0)] = dir;
1820 	if ((dir = getenv("CW_GPLUSPLUS_DIR")) != NULL)
1821 		dirs[CIDX(CW_C_GCC, CW_F_CXX)] = dir;
1822 
1823 	do_shadow = (getenv("CW_NO_SHADOW") ? 0 : 1);
1824 	do_serial = (getenv("CW_SHADOW_SERIAL") ? 1 : 0);
1825 
1826 	if (getenv("CW_NO_EXEC") == NULL)
1827 		ctx->i_flags |= CW_F_EXEC;
1828 
1829 	/*
1830 	 * The first argument must be one of "-_cc", "-_gcc", "-_CC", or "-_g++"
1831 	 */
1832 	if (argc == 1)
1833 		usage();
1834 	argc--;
1835 	argv++;
1836 	if (strcmp(argv[0], "-_cc") == 0) {
1837 		ctx->i_compiler = CW_C_CC;
1838 	} else if (strcmp(argv[0], "-_gcc") == 0) {
1839 		ctx->i_compiler = CW_C_GCC;
1840 	} else if (strcmp(argv[0], "-_CC") == 0) {
1841 		ctx->i_compiler = CW_C_CC;
1842 		ctx->i_flags |= CW_F_CXX;
1843 	} else if (strcmp(argv[0], "-_g++") == 0) {
1844 		ctx->i_compiler = CW_C_GCC;
1845 		ctx->i_flags |= CW_F_CXX;
1846 	} else {
1847 		/* assume "-_gcc" by default */
1848 		argc++;
1849 		argv--;
1850 		ctx->i_compiler = CW_C_GCC;
1851 	}
1852 
1853 	/*
1854 	 * -_compiler - tell us the path to the primary compiler only
1855 	 */
1856 	if (argc > 1 && strcmp(argv[1], "-_compiler") == 0) {
1857 		ctx->i_flags &= ~CW_F_XLATE;
1858 		prepctx(ctx);
1859 		(void) printf("%s\n", ctx->i_ae->ael_head->ae_arg);
1860 		return (0);
1861 	}
1862 
1863 	/*
1864 	 * -_versions - tell us the cw version, paths to all compilers, and
1865 	 *		ask each for its version if we know how.
1866 	 */
1867 	if (argc > 1 && strcmp(argv[1], "-_versions") == 0) {
1868 		(void) printf("cw version %s", CW_VERSION);
1869 		if (!do_shadow)
1870 			(void) printf(" (SHADOW MODE DISABLED)");
1871 		(void) printf("\n");
1872 		(void) fflush(stdout);
1873 		ctx->i_flags &= ~CW_F_ECHO;
1874 		ctx->i_flags |= CW_F_PROG|CW_F_EXEC;
1875 		argc--;
1876 		argv++;
1877 		do_serial = 1;
1878 	}
1879 
1880 	ctx->i_oldargc = argc;
1881 	ctx->i_oldargv = argv;
1882 
1883 	ret |= exec_ctx(ctx, do_serial);
1884 
1885 	if (do_shadow) {
1886 		(void) memcpy(ctx_shadow, ctx, sizeof (cw_ictx_t));
1887 		ctx_shadow->i_flags |= CW_F_SHADOW;
1888 		ret |= exec_ctx(ctx_shadow, 1);
1889 	}
1890 
1891 	if (!do_serial)
1892 		ret |= reap(ctx);
1893 
1894 	return (ret);
1895 }
1896