Save the variable buffer content, not a potentially old pointer to it.
[make.git] / commands.c
blob5e02ee72809116ccd681460406b6c331a92f7fe2
1 /* Command processing for GNU Make.
2 Copyright (C) 1988-2012 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify it under the
6 terms of the GNU General Public License as published by the Free Software
7 Foundation; either version 3 of the License, or (at your option) any later
8 version.
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along with
15 this program. If not, see <http://www.gnu.org/licenses/>. */
17 #include "make.h"
18 #include "dep.h"
19 #include "filedef.h"
20 #include "variable.h"
21 #include "job.h"
22 #include "commands.h"
23 #ifdef WINDOWS32
24 #include <windows.h>
25 #include "w32err.h"
26 #endif
28 #if VMS
29 # define FILE_LIST_SEPARATOR ','
30 #else
31 # define FILE_LIST_SEPARATOR ' '
32 #endif
34 int remote_kill (int id, int sig);
36 #ifndef HAVE_UNISTD_H
37 int getpid ();
38 #endif
41 static unsigned long
42 dep_hash_1 (const void *key)
44 const struct dep *d = key;
45 return_STRING_HASH_1 (dep_name (d));
48 static unsigned long
49 dep_hash_2 (const void *key)
51 const struct dep *d = key;
52 return_STRING_HASH_2 (dep_name (d));
55 static int
56 dep_hash_cmp (const void *x, const void *y)
58 const struct dep *dx = x;
59 const struct dep *dy = y;
60 return strcmp (dep_name (dx), dep_name (dy));
63 /* Set FILE's automatic variables up. */
65 void
66 set_file_variables (struct file *file)
68 struct dep *d;
69 const char *at, *percent, *star, *less;
71 #ifndef NO_ARCHIVES
72 /* If the target is an archive member 'lib(member)',
73 then $@ is 'lib' and $% is 'member'. */
75 if (ar_name (file->name))
77 unsigned int len;
78 const char *cp;
79 char *p;
81 cp = strchr (file->name, '(');
82 p = alloca (cp - file->name + 1);
83 memcpy (p, file->name, cp - file->name);
84 p[cp - file->name] = '\0';
85 at = p;
86 len = strlen (cp + 1);
87 p = alloca (len);
88 memcpy (p, cp + 1, len - 1);
89 p[len - 1] = '\0';
90 percent = p;
92 else
93 #endif /* NO_ARCHIVES. */
95 at = file->name;
96 percent = "";
99 /* $* is the stem from an implicit or static pattern rule. */
100 if (file->stem == 0)
102 /* In Unix make, $* is set to the target name with
103 any suffix in the .SUFFIXES list stripped off for
104 explicit rules. We store this in the 'stem' member. */
105 const char *name;
106 unsigned int len;
108 #ifndef NO_ARCHIVES
109 if (ar_name (file->name))
111 name = strchr (file->name, '(') + 1;
112 len = strlen (name) - 1;
114 else
115 #endif
117 name = file->name;
118 len = strlen (name);
121 for (d = enter_file (strcache_add (".SUFFIXES"))->deps; d ; d = d->next)
123 unsigned int slen = strlen (dep_name (d));
124 if (len > slen && strneq (dep_name (d), name + (len - slen), slen))
126 file->stem = strcache_add_len (name, len - slen);
127 break;
130 if (d == 0)
131 file->stem = "";
133 star = file->stem;
135 /* $< is the first not order-only dependency. */
136 less = "";
137 for (d = file->deps; d != 0; d = d->next)
138 if (!d->ignore_mtime)
140 if (!d->need_2nd_expansion)
141 less = dep_name (d);
142 break;
145 if (file->cmds == default_file->cmds)
146 /* This file got its commands from .DEFAULT.
147 In this case $< is the same as $@. */
148 less = at;
150 #define DEFINE_VARIABLE(name, len, value) \
151 (void) define_variable_for_file (name,len,value,o_automatic,0,file)
153 /* Define the variables. */
155 DEFINE_VARIABLE ("<", 1, less);
156 DEFINE_VARIABLE ("*", 1, star);
157 DEFINE_VARIABLE ("@", 1, at);
158 DEFINE_VARIABLE ("%", 1, percent);
160 /* Compute the values for $^, $+, $?, and $|. */
163 static char *plus_value=0, *bar_value=0, *qmark_value=0;
164 static unsigned int plus_max=0, bar_max=0, qmark_max=0;
166 unsigned int qmark_len, plus_len, bar_len;
167 char *cp;
168 char *caret_value;
169 char *qp;
170 char *bp;
171 unsigned int len;
173 struct hash_table dep_hash;
174 void **slot;
176 /* Compute first the value for $+, which is supposed to contain
177 duplicate dependencies as they were listed in the makefile. */
179 plus_len = 0;
180 bar_len = 0;
181 for (d = file->deps; d != 0; d = d->next)
183 if (!d->need_2nd_expansion)
185 if (d->ignore_mtime)
186 bar_len += strlen (dep_name (d)) + 1;
187 else
188 plus_len += strlen (dep_name (d)) + 1;
192 if (bar_len == 0)
193 bar_len++;
195 if (plus_len == 0)
196 plus_len++;
198 if (plus_len > plus_max)
199 plus_value = xrealloc (plus_value, plus_max = plus_len);
201 cp = plus_value;
203 qmark_len = plus_len + 1; /* Will be this or less. */
204 for (d = file->deps; d != 0; d = d->next)
205 if (! d->ignore_mtime && ! d->need_2nd_expansion)
207 const char *c = dep_name (d);
209 #ifndef NO_ARCHIVES
210 if (ar_name (c))
212 c = strchr (c, '(') + 1;
213 len = strlen (c) - 1;
215 else
216 #endif
217 len = strlen (c);
219 memcpy (cp, c, len);
220 cp += len;
221 *cp++ = FILE_LIST_SEPARATOR;
222 if (! (d->changed || always_make_flag))
223 qmark_len -= len + 1; /* Don't space in $? for this one. */
226 /* Kill the last space and define the variable. */
228 cp[cp > plus_value ? -1 : 0] = '\0';
229 DEFINE_VARIABLE ("+", 1, plus_value);
231 /* Compute the values for $^, $?, and $|. */
233 cp = caret_value = plus_value; /* Reuse the buffer; it's big enough. */
235 if (qmark_len > qmark_max)
236 qmark_value = xrealloc (qmark_value, qmark_max = qmark_len);
237 qp = qmark_value;
239 if (bar_len > bar_max)
240 bar_value = xrealloc (bar_value, bar_max = bar_len);
241 bp = bar_value;
243 /* Make sure that no dependencies are repeated in $^, $?, and $|. It
244 would be natural to combine the next two loops but we can't do it
245 because of a situation where we have two dep entries, the first
246 is order-only and the second is normal (see below). */
248 hash_init (&dep_hash, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
250 for (d = file->deps; d != 0; d = d->next)
252 if (d->need_2nd_expansion)
253 continue;
255 slot = hash_find_slot (&dep_hash, d);
256 if (HASH_VACANT (*slot))
257 hash_insert_at (&dep_hash, d, slot);
258 else
260 /* Check if the two prerequisites have different ignore_mtime.
261 If so then we need to "upgrade" one that is order-only. */
263 struct dep* hd = (struct dep*) *slot;
265 if (d->ignore_mtime != hd->ignore_mtime)
266 d->ignore_mtime = hd->ignore_mtime = 0;
270 for (d = file->deps; d != 0; d = d->next)
272 const char *c;
274 if (d->need_2nd_expansion || hash_find_item (&dep_hash, d) != d)
275 continue;
277 c = dep_name (d);
278 #ifndef NO_ARCHIVES
279 if (ar_name (c))
281 c = strchr (c, '(') + 1;
282 len = strlen (c) - 1;
284 else
285 #endif
286 len = strlen (c);
288 if (d->ignore_mtime)
290 memcpy (bp, c, len);
291 bp += len;
292 *bp++ = FILE_LIST_SEPARATOR;
294 else
296 memcpy (cp, c, len);
297 cp += len;
298 *cp++ = FILE_LIST_SEPARATOR;
299 if (d->changed || always_make_flag)
301 memcpy (qp, c, len);
302 qp += len;
303 *qp++ = FILE_LIST_SEPARATOR;
308 hash_free (&dep_hash, 0);
310 /* Kill the last spaces and define the variables. */
312 cp[cp > caret_value ? -1 : 0] = '\0';
313 DEFINE_VARIABLE ("^", 1, caret_value);
315 qp[qp > qmark_value ? -1 : 0] = '\0';
316 DEFINE_VARIABLE ("?", 1, qmark_value);
318 bp[bp > bar_value ? -1 : 0] = '\0';
319 DEFINE_VARIABLE ("|", 1, bar_value);
322 #undef DEFINE_VARIABLE
325 /* Chop CMDS up into individual command lines if necessary.
326 Also set the 'lines_flags' and 'any_recurse' members. */
328 void
329 chop_commands (struct commands *cmds)
331 unsigned int nlines, idx;
332 char **lines;
334 /* If we don't have any commands,
335 or we already parsed them, never mind. */
337 if (!cmds || cmds->command_lines != 0)
338 return;
340 /* Chop CMDS->commands up into lines in CMDS->command_lines. */
342 if (one_shell)
344 int l = strlen (cmds->commands);
346 nlines = 1;
347 lines = xmalloc (nlines * sizeof (char *));
348 lines[0] = xstrdup (cmds->commands);
350 /* Strip the trailing newline. */
351 if (l > 0 && lines[0][l-1] == '\n')
352 lines[0][l-1] = '\0';
354 else
356 const char *p;
358 nlines = 5;
359 lines = xmalloc (nlines * sizeof (char *));
360 idx = 0;
361 p = cmds->commands;
362 while (*p != '\0')
364 const char *end = p;
365 find_end:;
366 end = strchr (end, '\n');
367 if (end == 0)
368 end = p + strlen (p);
369 else if (end > p && end[-1] == '\\')
371 int backslash = 1;
372 const char *b;
373 for (b = end - 2; b >= p && *b == '\\'; --b)
374 backslash = !backslash;
375 if (backslash)
377 ++end;
378 goto find_end;
382 if (idx == nlines)
384 nlines += 2;
385 lines = xrealloc (lines, nlines * sizeof (char *));
387 lines[idx++] = xstrndup (p, end - p);
388 p = end;
389 if (*p != '\0')
390 ++p;
393 if (idx != nlines)
395 nlines = idx;
396 lines = xrealloc (lines, nlines * sizeof (char *));
400 /* Finally, set the corresponding CMDS->lines_flags elements and the
401 CMDS->any_recurse flag. */
403 if (nlines > USHRT_MAX)
404 fatal (&cmds->fileinfo, _("Recipe has too many lines (%ud)"), nlines);
406 cmds->ncommand_lines = nlines;
407 cmds->command_lines = lines;
409 cmds->any_recurse = 0;
410 cmds->lines_flags = xmalloc (nlines);
412 for (idx = 0; idx < nlines; ++idx)
414 int flags = 0;
415 const char *p = lines[idx];
417 while (isblank (*p) || *p == '-' || *p == '@' || *p == '+')
418 switch (*(p++))
420 case '+':
421 flags |= COMMANDS_RECURSE;
422 break;
423 case '@':
424 flags |= COMMANDS_SILENT;
425 break;
426 case '-':
427 flags |= COMMANDS_NOERROR;
428 break;
431 /* If no explicit '+' was given, look for MAKE variable references. */
432 if (!(flags & COMMANDS_RECURSE)
433 && (strstr (p, "$(MAKE)") != 0 || strstr (p, "${MAKE}") != 0))
434 flags |= COMMANDS_RECURSE;
436 cmds->lines_flags[idx] = flags;
437 cmds->any_recurse |= flags & COMMANDS_RECURSE ? 1 : 0;
441 /* Execute the commands to remake FILE. If they are currently executing,
442 return or have already finished executing, just return. Otherwise,
443 fork off a child process to run the first command line in the sequence. */
445 void
446 execute_file_commands (struct file *file)
448 const char *p;
450 /* Don't go through all the preparations if
451 the commands are nothing but whitespace. */
453 for (p = file->cmds->commands; *p != '\0'; ++p)
454 if (!isspace ((unsigned char)*p) && *p != '-' && *p != '@')
455 break;
456 if (*p == '\0')
458 /* If there are no commands, assume everything worked. */
459 set_command_state (file, cs_running);
460 file->update_status = 0;
461 notice_finished_file (file);
462 return;
465 /* First set the automatic variables according to this file. */
467 initialize_file_variables (file, 0);
469 set_file_variables (file);
471 /* Start the commands running. */
472 new_job (file);
475 /* This is set while we are inside fatal_error_signal,
476 so things can avoid nonreentrant operations. */
478 int handling_fatal_signal = 0;
480 /* Handle fatal signals. */
482 RETSIGTYPE
483 fatal_error_signal (int sig)
485 #ifdef __MSDOS__
486 extern int dos_status, dos_command_running;
488 if (dos_command_running)
490 /* That was the child who got the signal, not us. */
491 dos_status |= (sig << 8);
492 return;
494 remove_intermediates (1);
495 exit (EXIT_FAILURE);
496 #else /* not __MSDOS__ */
497 #ifdef _AMIGA
498 remove_intermediates (1);
499 if (sig == SIGINT)
500 fputs (_("*** Break.\n"), stderr);
502 exit (10);
503 #else /* not Amiga */
504 #ifdef WINDOWS32
505 extern HANDLE main_thread;
507 /* Windows creates a sperate thread for handling Ctrl+C, so we need
508 to suspend the main thread, or else we will have race conditions
509 when both threads call reap_children. */
510 if (main_thread)
512 DWORD susp_count = SuspendThread (main_thread);
514 if (susp_count != 0)
515 fprintf (stderr, "SuspendThread: suspend count = %ld\n", susp_count);
516 else if (susp_count == (DWORD)-1)
518 DWORD ierr = GetLastError ();
520 fprintf (stderr, "SuspendThread: error %ld: %s\n",
521 ierr, map_windows32_error_to_string (ierr));
524 #endif
525 handling_fatal_signal = 1;
527 /* Set the handling for this signal to the default.
528 It is blocked now while we run this handler. */
529 signal (sig, SIG_DFL);
531 /* A termination signal won't be sent to the entire
532 process group, but it means we want to kill the children. */
534 if (sig == SIGTERM)
536 struct child *c;
537 for (c = children; c != 0; c = c->next)
538 if (!c->remote)
539 (void) kill (c->pid, SIGTERM);
542 /* If we got a signal that means the user
543 wanted to kill make, remove pending targets. */
545 if (sig == SIGTERM || sig == SIGINT
546 #ifdef SIGHUP
547 || sig == SIGHUP
548 #endif
549 #ifdef SIGQUIT
550 || sig == SIGQUIT
551 #endif
554 struct child *c;
556 /* Remote children won't automatically get signals sent
557 to the process group, so we must send them. */
558 for (c = children; c != 0; c = c->next)
559 if (c->remote)
560 (void) remote_kill (c->pid, sig);
562 for (c = children; c != 0; c = c->next)
563 delete_child_targets (c);
565 /* Clean up the children. We don't just use the call below because
566 we don't want to print the "Waiting for children" message. */
567 while (job_slots_used > 0)
568 reap_children (1, 0);
570 else
571 /* Wait for our children to die. */
572 while (job_slots_used > 0)
573 reap_children (1, 1);
575 /* Delete any non-precious intermediate files that were made. */
577 remove_intermediates (1);
579 #ifdef SIGQUIT
580 if (sig == SIGQUIT)
581 /* We don't want to send ourselves SIGQUIT, because it will
582 cause a core dump. Just exit instead. */
583 exit (EXIT_FAILURE);
584 #endif
586 #ifdef WINDOWS32
587 if (main_thread)
588 CloseHandle (main_thread);
589 /* Cannot call W32_kill with a pid (it needs a handle). The exit
590 status of 130 emulates what happens in Bash. */
591 exit (130);
592 #else
593 /* Signal the same code; this time it will really be fatal. The signal
594 will be unblocked when we return and arrive then to kill us. */
595 if (kill (getpid (), sig) < 0)
596 pfatal_with_name ("kill");
597 #endif /* not WINDOWS32 */
598 #endif /* not Amiga */
599 #endif /* not __MSDOS__ */
602 /* Delete FILE unless it's precious or not actually a file (phony),
603 and it has changed on disk since we last stat'd it. */
605 static void
606 delete_target (struct file *file, const char *on_behalf_of)
608 struct stat st;
609 int e;
611 if (file->precious || file->phony)
612 return;
614 #ifndef NO_ARCHIVES
615 if (ar_name (file->name))
617 time_t file_date = (file->last_mtime == NONEXISTENT_MTIME
618 ? (time_t) -1
619 : (time_t) FILE_TIMESTAMP_S (file->last_mtime));
620 if (ar_member_date (file->name) != file_date)
622 if (on_behalf_of)
623 error (NILF, _("*** [%s] Archive member '%s' may be bogus; not deleted"),
624 on_behalf_of, file->name);
625 else
626 error (NILF, _("*** Archive member '%s' may be bogus; not deleted"),
627 file->name);
629 return;
631 #endif
633 EINTRLOOP (e, stat (file->name, &st));
634 if (e == 0
635 && S_ISREG (st.st_mode)
636 && FILE_TIMESTAMP_STAT_MODTIME (file->name, st) != file->last_mtime)
638 if (on_behalf_of)
639 error (NILF, _("*** [%s] Deleting file '%s'"), on_behalf_of, file->name);
640 else
641 error (NILF, _("*** Deleting file '%s'"), file->name);
642 if (unlink (file->name) < 0
643 && errno != ENOENT) /* It disappeared; so what. */
644 perror_with_name ("unlink: ", file->name);
649 /* Delete all non-precious targets of CHILD unless they were already deleted.
650 Set the flag in CHILD to say they've been deleted. */
652 void
653 delete_child_targets (struct child *child)
655 struct dep *d;
657 if (child->deleted)
658 return;
660 /* Delete the target file if it changed. */
661 delete_target (child->file, NULL);
663 /* Also remove any non-precious targets listed in the 'also_make' member. */
664 for (d = child->file->also_make; d != 0; d = d->next)
665 delete_target (d->file, child->file->name);
667 child->deleted = 1;
670 /* Print out the commands in CMDS. */
672 void
673 print_commands (const struct commands *cmds)
675 const char *s;
677 fputs (_("# recipe to execute"), stdout);
679 if (cmds->fileinfo.filenm == 0)
680 puts (_(" (built-in):"));
681 else
682 printf (_(" (from '%s', line %lu):\n"),
683 cmds->fileinfo.filenm, cmds->fileinfo.lineno);
685 s = cmds->commands;
686 while (*s != '\0')
688 const char *end;
689 int bs;
691 /* Print one full logical recipe line: find a non-escaped newline. */
692 for (end = s, bs = 0; *end != '\0'; ++end)
694 if (*end == '\n' && !bs)
695 break;
697 bs = *end == '\\' ? !bs : 0;
700 printf ("%c%.*s\n", cmd_prefix, (int) (end - s), s);
702 s = end + (end[0] == '\n');