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