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