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