Makefile:1.30->1.31
[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.13 2004/11/30 19:12:57 joerg 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 void CompatInterrupt(int);
82 static int CompatMake(void *, void *);
83 static int shellneed(char *);
84
85 static char *sh_builtin[] = { 
86         "alias", "cd", "eval", "exec", "exit", "read", "set", "ulimit", 
87         "unalias", "umask", "unset", "wait", ":", 0};
88
89 static void
90 CompatInit(void)
91 {
92     char          *cp;      /* Pointer to string of shell meta-characters */
93
94     for (cp = "#=|^(){};&<>*?[]:$`\\\n"; *cp != '\0'; cp++) {
95         meta[(unsigned char) *cp] = 1;
96     }
97     /*
98      * The null character serves as a sentinel in the string.
99      */
100     meta[0] = 1;
101 }
102
103 /*-
104  *-----------------------------------------------------------------------
105  * CompatInterrupt --
106  *      Interrupt the creation of the current target and remove it if
107  *      it ain't precious.
108  *
109  * Results:
110  *      None.
111  *
112  * Side Effects:
113  *      The target is removed and the process exits. If .INTERRUPT exists,
114  *      its commands are run first WITH INTERRUPTS IGNORED..
115  *
116  *-----------------------------------------------------------------------
117  */
118 static void
119 CompatInterrupt (int signo)
120 {
121     GNode   *gn;
122
123     if ((curTarg != NULL) && !Targ_Precious (curTarg)) {
124         char      *p1;
125         char      *file = Var_Value (TARGET, curTarg, &p1);
126
127         if (!noExecute && eunlink(file) != -1) {
128             printf ("*** %s removed\n", file);
129         }
130         free(p1);
131
132         /*
133          * Run .INTERRUPT only if hit with interrupt signal
134          */
135         if (signo == SIGINT) {
136             gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
137             if (gn != NULL) {
138                 Lst_ForEach(gn->commands, Compat_RunCommand, (void *)gn);
139             }
140         }
141
142     }
143     if (signo == SIGQUIT)
144         exit(signo);
145     (void) signal(signo, SIG_DFL);
146     (void) kill(getpid(), signo);
147 }
148 \f
149 /*-
150  *-----------------------------------------------------------------------
151  * shellneed --
152  *      
153  * Results:
154  *      Returns 1 if a specified line must be executed by the shell,
155  *      0 if it can be run via execve, and -1 if the command is a no-op.
156  *
157  * Side Effects:
158  *      None.
159  *      
160  *-----------------------------------------------------------------------
161  */
162 static int
163 shellneed (char *cmd)
164 {
165         char **av, **p;
166         int ac;
167
168         av = brk_string(cmd, &ac, TRUE);
169         for(p = sh_builtin; *p != 0; p++)
170                 if (strcmp(av[1], *p) == 0)
171                         return (1);
172         return (0);
173 }
174 \f
175 /*-
176  *-----------------------------------------------------------------------
177  * Compat_RunCommand --
178  *      Execute the next command for a target. If the command returns an
179  *      error, the node's made field is set to ERROR and creation stops.
180  *      The node from which the command came is also given.
181  *
182  * Results:
183  *      0 if the command succeeded, 1 if an error occurred.
184  *
185  * Side Effects:
186  *      The node's 'made' field may be set to ERROR.
187  *
188  *-----------------------------------------------------------------------
189  */
190 int
191 Compat_RunCommand (void *cmdp, void *gnp)
192 {
193     char          *cmdStart;    /* Start of expanded command */
194     char          *cp;
195     Boolean       silent,       /* Don't print command */
196                   doit,         /* Execute even in -n */
197                   errCheck;     /* Check errors */
198     int           reason;       /* Reason for child's death */
199     int           status;       /* Description of child's death */
200     int           cpid;         /* Child actually found */
201     ReturnStatus  rstat;        /* Status of fork */
202     LstNode       cmdNode;      /* Node where current command is located */
203     char          **av;         /* Argument vector for thing to exec */
204     int           argc;         /* Number of arguments in av or 0 if not
205                                  * dynamically allocated */
206     int           internal;     /* Various values.. */
207     char          *cmd = (char *) cmdp;
208     GNode         *gn = (GNode *) gnp;
209
210     /*
211      * Avoid clobbered variable warnings by forcing the compiler
212      * to ``unregister'' variables
213      */
214 #if __GNUC__
215     (void) &av;
216     (void) &errCheck;
217 #endif
218     silent = gn->type & OP_SILENT;
219     errCheck = !(gn->type & OP_IGNORE);
220     doit = FALSE;
221
222     cmdNode = Lst_Member (gn->commands, (void *)cmd);
223     cmdStart = Var_Subst (NULL, cmd, gn, FALSE);
224
225     /*
226      * brk_string will return an argv with a NULL in av[0], thus causing
227      * execvp to choke and die horribly. Besides, how can we execute a null
228      * command? In any case, we warn the user that the command expanded to
229      * nothing (is this the right thing to do?).
230      */
231
232     if (*cmdStart == '\0') {
233         free(cmdStart);
234         Error("%s expands to empty string", cmd);
235         return(0);
236     } else {
237         cmd = cmdStart;
238     }
239     Lst_Replace (cmdNode, (void *)cmdStart);
240
241     if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
242         (void)Lst_AtEnd(ENDNode->commands, (void *)cmdStart);
243         return(0);
244     } else if (strcmp(cmdStart, "...") == 0) {
245         gn->type |= OP_SAVE_CMDS;
246         return(0);
247     }
248
249     while ((*cmd == '@') || (*cmd == '-') || (*cmd == '+')) {
250         switch (*cmd) {
251
252           case '@':
253             silent = DEBUG(LOUD) ? FALSE : TRUE;
254             break;
255
256           case '-':
257             errCheck = FALSE;
258             break;
259
260           case '+':
261             doit = TRUE;
262             if (!meta[0])               /* we came here from jobs */
263                 CompatInit();
264             break;
265         }
266         cmd++;
267     }
268
269     while (isspace((unsigned char)*cmd))
270         cmd++;
271
272     /*
273      * Search for meta characters in the command. If there are no meta
274      * characters, there's no need to execute a shell to execute the
275      * command.
276      */
277     for (cp = cmd; !meta[(unsigned char)*cp]; cp++) {
278         continue;
279     }
280
281     /*
282      * Print the command before echoing if we're not supposed to be quiet for
283      * this one. We also print the command if -n given, but not if '+'.
284      */
285     if (!silent || (noExecute && !doit)) {
286         printf ("%s\n", cmd);
287         fflush(stdout);
288     }
289
290     /*
291      * If we're not supposed to execute any commands, this is as far as
292      * we go...
293      */
294     if (!doit && noExecute) {
295         return (0);
296     }
297
298     if (*cp != '\0') {
299         /*
300          * If *cp isn't the null character, we hit a "meta" character and
301          * need to pass the command off to the shell. We give the shell the
302          * -e flag as well as -c if it's supposed to exit when it hits an
303          * error.
304          */
305         static char     *shargv[4] = { "/bin/sh" };
306
307         shargv[1] = (errCheck ? "-ec" : "-c");
308         shargv[2] = cmd;
309         shargv[3] = (char *)NULL;
310         av = shargv;
311         argc = 0;
312     } else if ((internal = shellneed(cmd))) {
313         /*
314          * This command must be passed by the shell for other reasons..
315          * or.. possibly not at all.
316          */
317         static char     *shargv[4] = { "/bin/sh" };
318
319         if (internal == -1) {
320                 /* Command does not need to be executed */
321                 return (0);
322         }
323
324         shargv[1] = (errCheck ? "-ec" : "-c");
325         shargv[2] = cmd;
326         shargv[3] = (char *)NULL;
327         av = shargv;
328         argc = 0;
329     } else {
330         /*
331          * No meta-characters, so no need to exec a shell. Break the command
332          * into words to form an argument vector we can execute.
333          * brk_string sticks our name in av[0], so we have to
334          * skip over it...
335          */
336         av = brk_string(cmd, &argc, TRUE);
337         av += 1;
338     }
339
340     /*
341      * Fork and execute the single command. If the fork fails, we abort.
342      */
343     cpid = vfork();
344     if (cpid < 0) {
345         Fatal("Could not fork");
346     }
347     if (cpid == 0) {
348         execvp(av[0], av);
349         (void) write (STDERR_FILENO, av[0], strlen (av[0]));
350         (void) write (STDERR_FILENO, ":", 1);
351         (void) write (STDERR_FILENO, strerror(errno), strlen(strerror(errno)));
352         (void) write (STDERR_FILENO, "\n", 1);
353         exit(1);
354     }
355
356     /* 
357      * we need to print out the command associated with this Gnode in
358      * Targ_PrintCmd from Targ_PrintGraph when debugging at level g2,
359      * in main(), Fatal() and DieHorribly(), therefore do not free it
360      * when debugging. 
361      */
362     if (!DEBUG(GRAPH2)) {
363         free(cmdStart);
364         Lst_Replace (cmdNode, cmdp);
365     }
366
367     /*
368      * The child is off and running. Now all we can do is wait...
369      */
370     while (1) {
371
372         while ((rstat = wait(&reason)) != cpid) {
373             if (rstat == -1 && errno != EINTR) {
374                 break;
375             }
376         }
377
378         if (rstat > -1) {
379             if (WIFSTOPPED(reason)) {
380                 status = WSTOPSIG(reason);              /* stopped */
381             } else if (WIFEXITED(reason)) {
382                 status = WEXITSTATUS(reason);           /* exited */
383                 if (status != 0) {
384                     printf ("*** Error code %d", status);
385                 }
386             } else {
387                 status = WTERMSIG(reason);              /* signaled */
388                 printf ("*** Signal %d", status);
389             }
390
391
392             if (!WIFEXITED(reason) || (status != 0)) {
393                 if (errCheck) {
394                     gn->made = ERROR;
395                     if (keepgoing) {
396                         /*
397                          * Abort the current target, but let others
398                          * continue.
399                          */
400                         printf (" (continuing)\n");
401                     }
402                 } else {
403                     /*
404                      * Continue executing commands for this target.
405                      * If we return 0, this will happen...
406                      */
407                     printf (" (ignored)\n");
408                     status = 0;
409                 }
410             }
411             break;
412         } else {
413             Fatal ("error in wait: %d", rstat);
414             /*NOTREACHED*/
415         }
416     }
417
418     return (status);
419 }
420 \f
421 /*-
422  *-----------------------------------------------------------------------
423  * CompatMake --
424  *      Make a target, given the parent, to abort if necessary.
425  *
426  * Results:
427  *      0
428  *
429  * Side Effects:
430  *      If an error is detected and not being ignored, the process exits.
431  *
432  *-----------------------------------------------------------------------
433  */
434 static int
435 CompatMake (void *gnp, void *pgnp)
436 {
437     GNode *gn = (GNode *) gnp;
438     GNode *pgn = (GNode *) pgnp;
439     if (gn->type & OP_USE) {
440         Make_HandleUse(gn, pgn);
441     } else if (gn->made == UNMADE) {
442         /*
443          * First mark ourselves to be made, then apply whatever transformations
444          * the suffix module thinks are necessary. Once that's done, we can
445          * descend and make all our children. If any of them has an error
446          * but the -k flag was given, our 'make' field will be set FALSE again.
447          * This is our signal to not attempt to do anything but abort our
448          * parent as well.
449          */
450         gn->make = TRUE;
451         gn->made = BEINGMADE;
452         Suff_FindDeps (gn);
453         Lst_ForEach (gn->children, CompatMake, (void *)gn);
454         if (!gn->make) {
455             gn->made = ABORTED;
456             pgn->make = FALSE;
457             return (0);
458         }
459
460         if (Lst_Member (gn->iParents, pgn) != NULL) {
461             char *p1;
462             Var_Set (IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
463             free(p1);
464         }
465
466         /*
467          * All the children were made ok. Now cmtime contains the modification
468          * time of the newest child, we need to find out if we exist and when
469          * we were modified last. The criteria for datedness are defined by the
470          * Make_OODate function.
471          */
472         DEBUGF(MAKE, ("Examining %s...", gn->name));
473         if (! Make_OODate(gn)) {
474             gn->made = UPTODATE;
475             DEBUGF(MAKE, ("up-to-date.\n"));
476             return (0);
477         } else {
478             DEBUGF(MAKE, ("out-of-date.\n"));
479         }
480
481         /*
482          * If the user is just seeing if something is out-of-date, exit now
483          * to tell him/her "yes".
484          */
485         if (queryFlag) {
486             exit (1);
487         }
488
489         /*
490          * We need to be re-made. We also have to make sure we've got a $?
491          * variable. To be nice, we also define the $> variable using
492          * Make_DoAllVar().
493          */
494         Make_DoAllVar(gn);
495
496         /*
497          * Alter our type to tell if errors should be ignored or things
498          * should not be printed so Compat_RunCommand knows what to do.
499          */
500         if (Targ_Ignore (gn)) {
501             gn->type |= OP_IGNORE;
502         }
503         if (Targ_Silent (gn)) {
504             gn->type |= OP_SILENT;
505         }
506
507         if (Job_CheckCommands (gn, Fatal)) {
508             /*
509              * Our commands are ok, but we still have to worry about the -t
510              * flag...
511              */
512             if (!touchFlag) {
513                 curTarg = gn;
514                 Lst_ForEach (gn->commands, Compat_RunCommand, (void *)gn);
515                 curTarg = NULL;
516             } else {
517                 Job_Touch (gn, gn->type & OP_SILENT);
518             }
519         } else {
520             gn->made = ERROR;
521         }
522
523         if (gn->made != ERROR) {
524             /*
525              * If the node was made successfully, mark it so, update
526              * its modification time and timestamp all its parents. Note
527              * that for .ZEROTIME targets, the timestamping isn't done.
528              * This is to keep its state from affecting that of its parent.
529              */
530             gn->made = MADE;
531 #ifndef RECHECK
532             /*
533              * We can't re-stat the thing, but we can at least take care of
534              * rules where a target depends on a source that actually creates
535              * the target, but only if it has changed, e.g.
536              *
537              * parse.h : parse.o
538              *
539              * parse.o : parse.y
540              *          yacc -d parse.y
541              *          cc -c y.tab.c
542              *          mv y.tab.o parse.o
543              *          cmp -s y.tab.h parse.h || mv y.tab.h parse.h
544              *
545              * In this case, if the definitions produced by yacc haven't
546              * changed from before, parse.h won't have been updated and
547              * gn->mtime will reflect the current modification time for
548              * parse.h. This is something of a kludge, I admit, but it's a
549              * useful one..
550              *
551              * XXX: People like to use a rule like
552              *
553              * FRC:
554              *
555              * To force things that depend on FRC to be made, so we have to
556              * check for gn->children being empty as well...
557              */
558             if (!Lst_IsEmpty(gn->commands) || Lst_IsEmpty(gn->children)) {
559                 gn->mtime = now;
560             }
561 #else
562             /*
563              * This is what Make does and it's actually a good thing, as it
564              * allows rules like
565              *
566              *  cmp -s y.tab.h parse.h || cp y.tab.h parse.h
567              *
568              * to function as intended. Unfortunately, thanks to the stateless
569              * nature of NFS (and the speed of this program), there are times
570              * when the modification time of a file created on a remote
571              * machine will not be modified before the stat() implied by
572              * the Dir_MTime occurs, thus leading us to believe that the file
573              * is unchanged, wreaking havoc with files that depend on this one.
574              *
575              * I have decided it is better to make too much than to make too
576              * little, so this stuff is commented out unless you're sure it's
577              * ok.
578              * -- ardeb 1/12/88
579              */
580             if (noExecute || Dir_MTime(gn) == 0) {
581                 gn->mtime = now;
582             }
583             if (gn->cmtime > gn->mtime)
584                 gn->mtime = gn->cmtime;
585             DEBUGF(MAKE, ("update time: %s\n", Targ_FmtTime(gn->mtime)));
586 #endif
587             if (!(gn->type & OP_EXEC)) {
588                 pgn->childMade = TRUE;
589                 Make_TimeStamp(pgn, gn);
590             }
591         } else if (keepgoing) {
592             pgn->make = FALSE;
593         } else {
594             char *p1;
595
596             printf ("\n\nStop in %s.\n", Var_Value(".CURDIR", gn, &p1));
597             free(p1);
598             exit (1);
599         }
600     } else if (gn->made == ERROR) {
601         /*
602          * Already had an error when making this beastie. Tell the parent
603          * to abort.
604          */
605         pgn->make = FALSE;
606     } else {
607         if (Lst_Member (gn->iParents, pgn) != NULL) {
608             char *p1;
609             Var_Set (IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
610             free(p1);
611         }
612         switch(gn->made) {
613             case BEINGMADE:
614                 Error("Graph cycles through %s\n", gn->name);
615                 gn->made = ERROR;
616                 pgn->make = FALSE;
617                 break;
618             case MADE:
619                 if ((gn->type & OP_EXEC) == 0) {
620                     pgn->childMade = TRUE;
621                     Make_TimeStamp(pgn, gn);
622                 }
623                 break;
624             case UPTODATE:
625                 if ((gn->type & OP_EXEC) == 0) {
626                     Make_TimeStamp(pgn, gn);
627                 }
628                 break;
629             default:
630                 break;
631         }
632     }
633
634     return (0);
635 }
636 \f
637 /*-
638  *-----------------------------------------------------------------------
639  * Compat_Run --
640  *      Start making again, given a list of target nodes.
641  *
642  * Results:
643  *      None.
644  *
645  * Side Effects:
646  *      Guess what?
647  *
648  *-----------------------------------------------------------------------
649  */
650 void
651 Compat_Run(Lst targs)
652 {
653     GNode         *gn = NULL;/* Current root target */
654     int           errors;   /* Number of targets not remade due to errors */
655
656     CompatInit();
657
658     if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
659         signal(SIGINT, CompatInterrupt);
660     }
661     if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
662         signal(SIGTERM, CompatInterrupt);
663     }
664     if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
665         signal(SIGHUP, CompatInterrupt);
666     }
667     if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
668         signal(SIGQUIT, CompatInterrupt);
669     }
670
671     ENDNode = Targ_FindNode(".END", TARG_CREATE);
672     /*
673      * If the user has defined a .BEGIN target, execute the commands attached
674      * to it.
675      */
676     if (!queryFlag) {
677         gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
678         if (gn != NULL) {
679             Lst_ForEach(gn->commands, Compat_RunCommand, (void *)gn);
680             if (gn->made == ERROR) {
681                 printf("\n\nStop.\n");
682                 exit(1);
683             }
684         }
685     }
686
687     /*
688      * For each entry in the list of targets to create, call CompatMake on
689      * it to create the thing. CompatMake will leave the 'made' field of gn
690      * in one of several states:
691      *      UPTODATE        gn was already up-to-date
692      *      MADE            gn was recreated successfully
693      *      ERROR           An error occurred while gn was being created
694      *      ABORTED         gn was not remade because one of its inferiors
695      *                      could not be made due to errors.
696      */
697     errors = 0;
698     while (!Lst_IsEmpty (targs)) {
699         gn = (GNode *) Lst_DeQueue (targs);
700         CompatMake (gn, gn);
701
702         if (gn->made == UPTODATE) {
703             printf ("`%s' is up to date.\n", gn->name);
704         } else if (gn->made == ABORTED) {
705             printf ("`%s' not remade because of errors.\n", gn->name);
706             errors += 1;
707         }
708     }
709
710     /*
711      * If the user has defined a .END target, run its commands.
712      */
713     if (errors == 0) {
714         Lst_ForEach(ENDNode->commands, Compat_RunCommand, (void *)gn);
715     }
716 }