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