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