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