Merge from vendor branch GCC:
[dragonfly.git] / usr.bin / make / compat.c
1 /*
2  * Copyright (c) 1988, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1988, 1989 by Adam de Boor
5  * Copyright (c) 1989 by Berkeley Softworks
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Adam de Boor.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *      This product includes software developed by the University of
22  *      California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  *
39  * @(#)compat.c 8.2 (Berkeley) 3/19/94
40  * $FreeBSD: src/usr.bin/make/compat.c,v 1.16.2.2 2000/07/01 12:24:21 ps Exp $
41  * $DragonFly: src/usr.bin/make/Attic/compat.c,v 1.19 2004/12/17 08:13:30 okumoto Exp $
42  */
43
44 /*-
45  * compat.c --
46  *      The routines in this file implement the full-compatibility
47  *      mode of PMake. Most of the special functionality of PMake
48  *      is available in this mode. Things not supported:
49  *          - different shells.
50  *          - friendly variable substitution.
51  *
52  * Interface:
53  *      Compat_Run          Initialize things for this module and recreate
54  *                          thems as need creatin'
55  */
56
57 #include    <stdio.h>
58 #include    <sys/types.h>
59 #include    <sys/stat.h>
60 #include    <sys/wait.h>
61 #include    <ctype.h>
62 #include    <errno.h>
63 #include    <signal.h>
64 #include    <unistd.h>
65 #include    "make.h"
66 #include    "hash.h"
67 #include    "dir.h"
68 #include    "job.h"
69
70 /*
71  * The following array is used to make a fast determination of which
72  * characters are interpreted specially by the shell.  If a command
73  * contains any of these characters, it is executed by the shell, not
74  * directly by us.
75  */
76
77 static char         meta[256];
78
79 static GNode        *curTarg = NULL;
80 static GNode        *ENDNode;
81 static sig_atomic_t interrupted;
82
83 static void CompatInterrupt(int);
84 static int CompatMake(void *, void *);
85 static int shellneed(char *);
86
87 static char *sh_builtin[] = {
88         "alias", "cd", "eval", "exec", "exit", "read", "set", "ulimit",
89         "unalias", "umask", "unset", "wait", ":", 0};
90
91 static void
92 CompatInit(void)
93 {
94     char          *cp;      /* Pointer to string of shell meta-characters */
95
96     for (cp = "#=|^(){};&<>*?[]:$`\\\n"; *cp != '\0'; cp++) {
97         meta[(unsigned char)*cp] = 1;
98     }
99     /*
100      * The null character serves as a sentinel in the string.
101      */
102     meta[0] = 1;
103 }
104
105 /*
106  * Interrupt handler - set flag and defer handling to the main code
107  */
108 static void
109 CompatCatchSig(int signo)
110 {
111
112         interrupted = signo;
113 }
114
115 /*-
116  *-----------------------------------------------------------------------
117  * CompatInterrupt --
118  *      Interrupt the creation of the current target and remove it if
119  *      it ain't precious.
120  *
121  * Results:
122  *      None.
123  *
124  * Side Effects:
125  *      The target is removed and the process exits. If .INTERRUPT exists,
126  *      its commands are run first WITH INTERRUPTS IGNORED..
127  *
128  *-----------------------------------------------------------------------
129  */
130 static void
131 CompatInterrupt (int signo)
132 {
133     GNode   *gn;
134     sigset_t nmask, omask;
135
136     sigemptyset(&nmask);
137     sigaddset(&nmask, SIGINT);
138     sigaddset(&nmask, SIGTERM);
139     sigaddset(&nmask, SIGHUP);
140     sigaddset(&nmask, SIGQUIT);
141     sigprocmask(SIG_SETMASK, &nmask, &omask);
142
143     /* prevent recursion in evaluation of .INTERRUPT */
144     interrupted = 0;
145
146     if ((curTarg != NULL) && !Targ_Precious(curTarg)) {
147         char      *p1;
148         char      *file = Var_Value(TARGET, curTarg, &p1);
149
150         if (!noExecute && eunlink(file) != -1) {
151             printf("*** %s removed\n", file);
152         }
153         free(p1);
154     }
155
156     /*
157      * Run .INTERRUPT only if hit with interrupt signal
158      */
159     if (signo == SIGINT) {
160         gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
161         if (gn != NULL) {
162             Lst_ForEach(&gn->commands, Compat_RunCommand, (void *)gn);
163         }
164     }
165
166     sigprocmask(SIG_SETMASK, &omask, NULL);
167
168     if (signo == SIGQUIT)
169         exit(signo);
170     signal(signo, SIG_DFL);
171     kill(getpid(), signo);
172 }
173
174 /*-
175  *-----------------------------------------------------------------------
176  * shellneed --
177  *
178  * Results:
179  *      Returns 1 if a specified line must be executed by the shell,
180  *      0 if it can be run via execve, and -1 if the command is a no-op.
181  *
182  * Side Effects:
183  *      None.
184  *
185  *-----------------------------------------------------------------------
186  */
187 static int
188 shellneed (char *cmd)
189 {
190         char **av, **p;
191         int ac;
192
193         av = brk_string(cmd, &ac, TRUE);
194         for(p = sh_builtin; *p != 0; p++)
195                 if (strcmp(av[1], *p) == 0)
196                         return (1);
197         return (0);
198 }
199
200 /*-
201  *-----------------------------------------------------------------------
202  * Compat_RunCommand --
203  *      Execute the next command for a target. If the command returns an
204  *      error, the node's made field is set to ERROR and creation stops.
205  *      The node from which the command came is also given.
206  *
207  * Results:
208  *      0 if the command succeeded, 1 if an error occurred.
209  *
210  * Side Effects:
211  *      The node's 'made' field may be set to ERROR.
212  *
213  *-----------------------------------------------------------------------
214  */
215 int
216 Compat_RunCommand(void *cmdp, void *gnp)
217 {
218     char          *cmdStart;    /* Start of expanded command */
219     char          *cp;
220     Boolean       silent,       /* Don't print command */
221                   doit,         /* Execute even in -n */
222                   errCheck;     /* Check errors */
223     int           reason;       /* Reason for child's death */
224     int           status;       /* Description of child's death */
225     int           cpid;         /* Child actually found */
226     ReturnStatus  rstat;        /* Status of fork */
227     LstNode       *cmdNode;     /* Node where current command is located */
228     char          **av;         /* Argument vector for thing to exec */
229     int           argc;         /* Number of arguments in av or 0 if not
230                                  * dynamically allocated */
231     int           internal;     /* Various values.. */
232     char          *cmd = cmdp;
233     GNode         *gn = gnp;
234
235     /*
236      * Avoid clobbered variable warnings by forcing the compiler
237      * to ``unregister'' variables
238      */
239 #if __GNUC__
240     (void) &av;
241     (void) &errCheck;
242 #endif
243     silent = gn->type & OP_SILENT;
244     errCheck = !(gn->type & OP_IGNORE);
245     doit = FALSE;
246
247     cmdNode = Lst_Member(&gn->commands, cmd);
248     cmdStart = Var_Subst(NULL, cmd, gn, FALSE);
249
250     /*
251      * brk_string will return an argv with a NULL in av[0], thus causing
252      * execvp to choke and die horribly. Besides, how can we execute a null
253      * command? In any case, we warn the user that the command expanded to
254      * nothing (is this the right thing to do?).
255      */
256
257     if (*cmdStart == '\0') {
258         free(cmdStart);
259         Error("%s expands to empty string", cmd);
260         return (0);
261     } else {
262         cmd = cmdStart;
263     }
264     Lst_Replace (cmdNode, cmdStart);
265
266     if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
267         Lst_AtEnd(&ENDNode->commands, cmdStart);
268         return (0);
269     } else if (strcmp(cmdStart, "...") == 0) {
270         gn->type |= OP_SAVE_CMDS;
271         return (0);
272     }
273
274     while ((*cmd == '@') || (*cmd == '-') || (*cmd == '+')) {
275         switch (*cmd) {
276
277           case '@':
278             silent = DEBUG(LOUD) ? FALSE : TRUE;
279             break;
280
281           case '-':
282             errCheck = FALSE;
283             break;
284
285           case '+':
286             doit = TRUE;
287             if (!meta[0])               /* we came here from jobs */
288                 CompatInit();
289             break;
290         }
291         cmd++;
292     }
293
294     while (isspace((unsigned char)*cmd))
295         cmd++;
296
297     /*
298      * Search for meta characters in the command. If there are no meta
299      * characters, there's no need to execute a shell to execute the
300      * command.
301      */
302     for (cp = cmd; !meta[(unsigned char)*cp]; cp++) {
303         continue;
304     }
305
306     /*
307      * Print the command before echoing if we're not supposed to be quiet for
308      * this one. We also print the command if -n given, but not if '+'.
309      */
310     if (!silent || (noExecute && !doit)) {
311         printf("%s\n", cmd);
312         fflush(stdout);
313     }
314
315     /*
316      * If we're not supposed to execute any commands, this is as far as
317      * we go...
318      */
319     if (!doit && noExecute) {
320         return (0);
321     }
322
323     if (*cp != '\0') {
324         /*
325          * If *cp isn't the null character, we hit a "meta" character and
326          * need to pass the command off to the shell. We give the shell the
327          * -e flag as well as -c if it's supposed to exit when it hits an
328          * error.
329          */
330         static char     *shargv[4];
331
332         shargv[0] = shellPath;
333         shargv[1] = (errCheck ? "-ec" : "-c");
334         shargv[2] = cmd;
335         shargv[3] = NULL;
336         av = shargv;
337         argc = 0;
338     } else if ((internal = shellneed(cmd))) {
339         /*
340          * This command must be passed by the shell for other reasons..
341          * or.. possibly not at all.
342          */
343         static char     *shargv[4];
344
345         if (internal == -1) {
346                 /* Command does not need to be executed */
347                 return (0);
348         }
349
350         shargv[0] = shellPath;
351         shargv[1] = (errCheck ? "-ec" : "-c");
352         shargv[2] = cmd;
353         shargv[3] = NULL;
354         av = shargv;
355         argc = 0;
356     } else {
357         /*
358          * No meta-characters, so no need to exec a shell. Break the command
359          * into words to form an argument vector we can execute.
360          * brk_string sticks our name in av[0], so we have to
361          * skip over it...
362          */
363         av = brk_string(cmd, &argc, TRUE);
364         av += 1;
365     }
366
367     /*
368      * Fork and execute the single command. If the fork fails, we abort.
369      */
370     cpid = vfork();
371     if (cpid < 0) {
372         Fatal("Could not fork");
373     }
374     if (cpid == 0) {
375         execvp(av[0], av);
376         write(STDERR_FILENO, av[0], strlen (av[0]));
377         write(STDERR_FILENO, ":", 1);
378         write(STDERR_FILENO, strerror(errno), strlen(strerror(errno)));
379         write(STDERR_FILENO, "\n", 1);
380         exit(1);
381     }
382
383     /*
384      * we need to print out the command associated with this Gnode in
385      * Targ_PrintCmd from Targ_PrintGraph when debugging at level g2,
386      * in main(), Fatal() and DieHorribly(), therefore do not free it
387      * when debugging.
388      */
389     if (!DEBUG(GRAPH2)) {
390         free(cmdStart);
391         Lst_Replace(cmdNode, cmdp);
392     }
393
394     /*
395      * The child is off and running. Now all we can do is wait...
396      */
397     while (1) {
398
399         while ((rstat = wait(&reason)) != cpid) {
400             if (interrupted || (rstat == -1 && errno != EINTR)) {
401                     break;
402             }
403         }
404         if (interrupted)
405             CompatInterrupt(interrupted);
406
407         if (rstat > -1) {
408             if (WIFSTOPPED(reason)) {
409                 status = WSTOPSIG(reason);              /* stopped */
410             } else if (WIFEXITED(reason)) {
411                 status = WEXITSTATUS(reason);           /* exited */
412                 if (status != 0) {
413                     printf("*** Error code %d", status);
414                 }
415             } else {
416                 status = WTERMSIG(reason);              /* signaled */
417                 printf("*** Signal %d", status);
418             }
419
420
421             if (!WIFEXITED(reason) || (status != 0)) {
422                 if (errCheck) {
423                     gn->made = ERROR;
424                     if (keepgoing) {
425                         /*
426                          * Abort the current target, but let others
427                          * continue.
428                          */
429                         printf(" (continuing)\n");
430                     }
431                 } else {
432                     /*
433                      * Continue executing commands for this target.
434                      * If we return 0, this will happen...
435                      */
436                     printf(" (ignored)\n");
437                     status = 0;
438                 }
439             }
440             break;
441         } else {
442             Fatal("error in wait: %d", rstat);
443             /*NOTREACHED*/
444         }
445     }
446
447     return (status);
448 }
449
450 /*-
451  *-----------------------------------------------------------------------
452  * CompatMake --
453  *      Make a target, given the parent, to abort if necessary.
454  *
455  * Results:
456  *      0
457  *
458  * Side Effects:
459  *      If an error is detected and not being ignored, the process exits.
460  *
461  *-----------------------------------------------------------------------
462  */
463 static int
464 CompatMake(void *gnp, void *pgnp)
465 {
466     GNode *gn = gnp;
467     GNode *pgn = pgnp;
468
469     if (gn->type & OP_USE) {
470         Make_HandleUse(gn, pgn);
471     } else if (gn->made == UNMADE) {
472         /*
473          * First mark ourselves to be made, then apply whatever transformations
474          * the suffix module thinks are necessary. Once that's done, we can
475          * descend and make all our children. If any of them has an error
476          * but the -k flag was given, our 'make' field will be set FALSE again.
477          * This is our signal to not attempt to do anything but abort our
478          * parent as well.
479          */
480         gn->make = TRUE;
481         gn->made = BEINGMADE;
482         Suff_FindDeps(gn);
483         Lst_ForEach(&gn->children, CompatMake, gn);
484         if (!gn->make) {
485             gn->made = ABORTED;
486             pgn->make = FALSE;
487             return (0);
488         }
489
490         if (Lst_Member(&gn->iParents, pgn) != NULL) {
491             char *p1;
492             Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
493             free(p1);
494         }
495
496         /*
497          * All the children were made ok. Now cmtime contains the modification
498          * time of the newest child, we need to find out if we exist and when
499          * we were modified last. The criteria for datedness are defined by the
500          * Make_OODate function.
501          */
502         DEBUGF(MAKE, ("Examining %s...", gn->name));
503         if (!Make_OODate(gn)) {
504             gn->made = UPTODATE;
505             DEBUGF(MAKE, ("up-to-date.\n"));
506             return (0);
507         } else {
508             DEBUGF(MAKE, ("out-of-date.\n"));
509         }
510
511         /*
512          * If the user is just seeing if something is out-of-date, exit now
513          * to tell him/her "yes".
514          */
515         if (queryFlag) {
516             exit(1);
517         }
518
519         /*
520          * We need to be re-made. We also have to make sure we've got a $?
521          * variable. To be nice, we also define the $> variable using
522          * Make_DoAllVar().
523          */
524         Make_DoAllVar(gn);
525
526         /*
527          * Alter our type to tell if errors should be ignored or things
528          * should not be printed so Compat_RunCommand knows what to do.
529          */
530         if (Targ_Ignore(gn)) {
531             gn->type |= OP_IGNORE;
532         }
533         if (Targ_Silent(gn)) {
534             gn->type |= OP_SILENT;
535         }
536
537         if (Job_CheckCommands(gn, Fatal)) {
538             /*
539              * Our commands are ok, but we still have to worry about the -t
540              * flag...
541              */
542             if (!touchFlag) {
543                 curTarg = gn;
544                 Lst_ForEach(&gn->commands, Compat_RunCommand, (void *)gn);
545                 curTarg = NULL;
546             } else {
547                 Job_Touch(gn, gn->type & OP_SILENT);
548             }
549         } else {
550             gn->made = ERROR;
551         }
552
553         if (gn->made != ERROR) {
554             /*
555              * If the node was made successfully, mark it so, update
556              * its modification time and timestamp all its parents. Note
557              * that for .ZEROTIME targets, the timestamping isn't done.
558              * This is to keep its state from affecting that of its parent.
559              */
560             gn->made = MADE;
561 #ifndef RECHECK
562             /*
563              * We can't re-stat the thing, but we can at least take care of
564              * rules where a target depends on a source that actually creates
565              * the target, but only if it has changed, e.g.
566              *
567              * parse.h : parse.o
568              *
569              * parse.o : parse.y
570              *          yacc -d parse.y
571              *          cc -c y.tab.c
572              *          mv y.tab.o parse.o
573              *          cmp -s y.tab.h parse.h || mv y.tab.h parse.h
574              *
575              * In this case, if the definitions produced by yacc haven't
576              * changed from before, parse.h won't have been updated and
577              * gn->mtime will reflect the current modification time for
578              * parse.h. This is something of a kludge, I admit, but it's a
579              * useful one..
580              *
581              * XXX: People like to use a rule like
582              *
583              * FRC:
584              *
585              * To force things that depend on FRC to be made, so we have to
586              * check for gn->children being empty as well...
587              */
588             if (!Lst_IsEmpty(&gn->commands) || Lst_IsEmpty(gn->children)) {
589                 gn->mtime = now;
590             }
591 #else
592             /*
593              * This is what Make does and it's actually a good thing, as it
594              * allows rules like
595              *
596              *  cmp -s y.tab.h parse.h || cp y.tab.h parse.h
597              *
598              * to function as intended. Unfortunately, thanks to the stateless
599              * nature of NFS (and the speed of this program), there are times
600              * when the modification time of a file created on a remote
601              * machine will not be modified before the stat() implied by
602              * the Dir_MTime occurs, thus leading us to believe that the file
603              * is unchanged, wreaking havoc with files that depend on this one.
604              *
605              * I have decided it is better to make too much than to make too
606              * little, so this stuff is commented out unless you're sure it's
607              * ok.
608              * -- ardeb 1/12/88
609              */
610             if (noExecute || Dir_MTime(gn) == 0) {
611                 gn->mtime = now;
612             }
613             if (gn->cmtime > gn->mtime)
614                 gn->mtime = gn->cmtime;
615             DEBUGF(MAKE, ("update time: %s\n", Targ_FmtTime(gn->mtime)));
616 #endif
617             if (!(gn->type & OP_EXEC)) {
618                 pgn->childMade = TRUE;
619                 Make_TimeStamp(pgn, gn);
620             }
621         } else if (keepgoing) {
622             pgn->make = FALSE;
623         } else {
624             char *p1;
625
626             printf("\n\nStop in %s.\n", Var_Value(".CURDIR", gn, &p1));
627             free(p1);
628             exit(1);
629         }
630     } else if (gn->made == ERROR) {
631         /*
632          * Already had an error when making this beastie. Tell the parent
633          * to abort.
634          */
635         pgn->make = FALSE;
636     } else {
637         if (Lst_Member(&gn->iParents, pgn) != NULL) {
638             char *p1;
639             Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
640             free(p1);
641         }
642         switch(gn->made) {
643             case BEINGMADE:
644                 Error("Graph cycles through %s\n", gn->name);
645                 gn->made = ERROR;
646                 pgn->make = FALSE;
647                 break;
648             case MADE:
649                 if ((gn->type & OP_EXEC) == 0) {
650                     pgn->childMade = TRUE;
651                     Make_TimeStamp(pgn, gn);
652                 }
653                 break;
654             case UPTODATE:
655                 if ((gn->type & OP_EXEC) == 0) {
656                     Make_TimeStamp(pgn, gn);
657                 }
658                 break;
659             default:
660                 break;
661         }
662     }
663
664     return (0);
665 }
666
667 /*-
668  *-----------------------------------------------------------------------
669  * Compat_Run --
670  *      Start making again, given a list of target nodes.
671  *
672  * Results:
673  *      None.
674  *
675  * Side Effects:
676  *      Guess what?
677  *
678  *-----------------------------------------------------------------------
679  */
680 void
681 Compat_Run(Lst *targs)
682 {
683     GNode         *gn = NULL;/* Current root target */
684     int           errors;   /* Number of targets not remade due to errors */
685
686     CompatInit();
687     Shell_Init();               /* Set up shell. */
688
689     if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
690         signal(SIGINT, CompatCatchSig);
691     }
692     if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
693         signal(SIGTERM, CompatCatchSig);
694     }
695     if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
696         signal(SIGHUP, CompatCatchSig);
697     }
698     if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
699         signal(SIGQUIT, CompatCatchSig);
700     }
701
702     ENDNode = Targ_FindNode(".END", TARG_CREATE);
703     /*
704      * If the user has defined a .BEGIN target, execute the commands attached
705      * to it.
706      */
707     if (!queryFlag) {
708         gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
709         if (gn != NULL) {
710             Lst_ForEach(&gn->commands, Compat_RunCommand, gn);
711             if (gn->made == ERROR) {
712                 printf("\n\nStop.\n");
713                 exit(1);
714             }
715         }
716     }
717
718     /*
719      * For each entry in the list of targets to create, call CompatMake on
720      * it to create the thing. CompatMake will leave the 'made' field of gn
721      * in one of several states:
722      *      UPTODATE        gn was already up-to-date
723      *      MADE            gn was recreated successfully
724      *      ERROR           An error occurred while gn was being created
725      *      ABORTED         gn was not remade because one of its inferiors
726      *                      could not be made due to errors.
727      */
728     errors = 0;
729     while (!Lst_IsEmpty(targs)) {
730         gn = Lst_DeQueue(targs);
731         CompatMake(gn, gn);
732
733         if (gn->made == UPTODATE) {
734             printf("`%s' is up to date.\n", gn->name);
735         } else if (gn->made == ABORTED) {
736             printf("`%s' not remade because of errors.\n", gn->name);
737             errors += 1;
738         }
739     }
740
741     /*
742      * If the user has defined a .END target, run its commands.
743      */
744     if (errors == 0) {
745         Lst_ForEach(&ENDNode->commands, Compat_RunCommand, gn);
746     }
747 }