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