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