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