1/* Command processing for GNU Make.
2Copyright (C) 1988,89,91,92,93,94,95,96,97 Free Software Foundation, Inc.
3This file is part of GNU Make.
4
5GNU Make is free software; you can redistribute it and/or modify
6it under the terms of the GNU General Public License as published by
7the Free Software Foundation; either version 2, or (at your option)
8any later version.
9
10GNU Make is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with GNU Make; see the file COPYING.  If not, write to
17the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18Boston, MA 02111-1307, USA.  */
19
20#include "make.h"
21#include "dep.h"
22#include "filedef.h"
23#include "variable.h"
24#include "job.h"
25#include "commands.h"
26
27#if VMS
28# define FILE_LIST_SEPARATOR ','
29#else
30# define FILE_LIST_SEPARATOR ' '
31#endif
32
33extern int remote_kill PARAMS ((int id, int sig));
34
35#ifndef	HAVE_UNISTD_H
36extern int getpid ();
37#endif
38
39/* Set FILE's automatic variables up.  */
40
41static void
42set_file_variables (file)
43     register struct file *file;
44{
45  char *at, *percent, *star, *less;
46
47#ifndef	NO_ARCHIVES
48  /* If the target is an archive member `lib(member)',
49     then $@ is `lib' and $% is `member'.  */
50
51  if (ar_name (file->name))
52    {
53      unsigned int len;
54      char *p;
55
56      p = strchr (file->name, '(');
57      at = (char *) alloca (p - file->name + 1);
58      bcopy (file->name, at, p - file->name);
59      at[p - file->name] = '\0';
60      len = strlen (p + 1);
61      percent = (char *) alloca (len);
62      bcopy (p + 1, percent, len - 1);
63      percent[len - 1] = '\0';
64    }
65  else
66#endif	/* NO_ARCHIVES.  */
67    {
68      at = file->name;
69      percent = "";
70    }
71
72  /* $* is the stem from an implicit or static pattern rule.  */
73  if (file->stem == 0)
74    {
75      /* In Unix make, $* is set to the target name with
76	 any suffix in the .SUFFIXES list stripped off for
77	 explicit rules.  We store this in the `stem' member.  */
78      register struct dep *d;
79      char *name;
80      unsigned int len;
81
82#ifndef	NO_ARCHIVES
83      if (ar_name (file->name))
84	{
85	  name = strchr (file->name, '(') + 1;
86	  len = strlen (name) - 1;
87	}
88      else
89#endif
90	{
91	  name = file->name;
92	  len = strlen (name);
93	}
94
95      for (d = enter_file (".SUFFIXES")->deps; d != 0; d = d->next)
96	{
97	  unsigned int slen = strlen (dep_name (d));
98	  if (len > slen && strneq (dep_name (d), name + (len - slen), slen))
99	    {
100	      file->stem = savestring (name, len - slen);
101	      break;
102	    }
103	}
104      if (d == 0)
105	file->stem = "";
106    }
107  star = file->stem;
108
109  /* $< is the first dependency.  */
110  less = file->deps != 0 ? dep_name (file->deps) : "";
111
112  if (file->cmds == default_file->cmds)
113    /* This file got its commands from .DEFAULT.
114       In this case $< is the same as $@.  */
115    less = at;
116
117#define	DEFINE_VARIABLE(name, len, value) \
118  (void) define_variable_for_file (name,len,value,o_automatic,0,file)
119
120  /* Define the variables.  */
121
122  DEFINE_VARIABLE ("<", 1, less);
123  DEFINE_VARIABLE ("*", 1, star);
124  DEFINE_VARIABLE ("@", 1, at);
125  DEFINE_VARIABLE ("%", 1, percent);
126
127  /* Compute the values for $^, $+, $?, and $|.  */
128
129  {
130    unsigned int qmark_len, plus_len, bar_len;
131    char *caret_value, *plus_value;
132    char *cp;
133    char *qmark_value;
134    char *bar_value;
135    char *qp;
136    char *bp;
137    struct dep *d;
138    unsigned int len;
139
140    /* Compute first the value for $+, which is supposed to contain
141       duplicate dependencies as they were listed in the makefile.  */
142
143    plus_len = 0;
144    for (d = file->deps; d != 0; d = d->next)
145      if (! d->ignore_mtime)
146	plus_len += strlen (dep_name (d)) + 1;
147    if (plus_len == 0)
148      plus_len++;
149
150    cp = plus_value = (char *) alloca (plus_len);
151
152    qmark_len = plus_len + 1;	/* Will be this or less.  */
153    for (d = file->deps; d != 0; d = d->next)
154      if (! d->ignore_mtime)
155        {
156          char *c = dep_name (d);
157
158#ifndef	NO_ARCHIVES
159          if (ar_name (c))
160            {
161              c = strchr (c, '(') + 1;
162              len = strlen (c) - 1;
163            }
164          else
165#endif
166            len = strlen (c);
167
168          bcopy (c, cp, len);
169          cp += len;
170          *cp++ = FILE_LIST_SEPARATOR;
171          if (! d->changed)
172            qmark_len -= len + 1;	/* Don't space in $? for this one.  */
173        }
174
175    /* Kill the last space and define the variable.  */
176
177    cp[cp > plus_value ? -1 : 0] = '\0';
178    DEFINE_VARIABLE ("+", 1, plus_value);
179
180    /* Make sure that no dependencies are repeated.  This does not
181       really matter for the purpose of updating targets, but it
182       might make some names be listed twice for $^ and $?.  */
183
184    uniquize_deps (file->deps);
185
186    bar_len = 0;
187    for (d = file->deps; d != 0; d = d->next)
188      if (d->ignore_mtime)
189	bar_len += strlen (dep_name (d)) + 1;
190    if (bar_len == 0)
191      bar_len++;
192
193    /* Compute the values for $^, $?, and $|.  */
194
195    cp = caret_value = plus_value; /* Reuse the buffer; it's big enough.  */
196    qp = qmark_value = (char *) alloca (qmark_len);
197    bp = bar_value = (char *) alloca (bar_len);
198
199    for (d = file->deps; d != 0; d = d->next)
200      {
201	char *c = dep_name (d);
202
203#ifndef	NO_ARCHIVES
204	if (ar_name (c))
205	  {
206	    c = strchr (c, '(') + 1;
207	    len = strlen (c) - 1;
208	  }
209	else
210#endif
211	  len = strlen (c);
212
213        if (d->ignore_mtime)
214          {
215	    bcopy (c, bp, len);
216	    bp += len;
217	    *bp++ = FILE_LIST_SEPARATOR;
218	  }
219	else
220	  {
221            bcopy (c, cp, len);
222            cp += len;
223            *cp++ = FILE_LIST_SEPARATOR;
224            if (d->changed)
225              {
226                bcopy (c, qp, len);
227                qp += len;
228                *qp++ = FILE_LIST_SEPARATOR;
229              }
230          }
231      }
232
233    /* Kill the last spaces and define the variables.  */
234
235    cp[cp > caret_value ? -1 : 0] = '\0';
236    DEFINE_VARIABLE ("^", 1, caret_value);
237
238    qp[qp > qmark_value ? -1 : 0] = '\0';
239    DEFINE_VARIABLE ("?", 1, qmark_value);
240
241    bp[bp > bar_value ? -1 : 0] = '\0';
242    DEFINE_VARIABLE ("|", 1, bar_value);
243  }
244
245#undef	DEFINE_VARIABLE
246}
247
248/* Chop CMDS up into individual command lines if necessary.
249   Also set the `lines_flags' and `any_recurse' members.  */
250
251void
252chop_commands (cmds)
253     register struct commands *cmds;
254{
255  register char *p;
256  unsigned int nlines, idx;
257  char **lines;
258
259  /* If we don't have any commands,
260     or we already parsed them, never mind.  */
261
262  if (!cmds || cmds->command_lines != 0)
263    return;
264
265  /* Chop CMDS->commands up into lines in CMDS->command_lines.
266	 Also set the corresponding CMDS->lines_flags elements,
267	 and the CMDS->any_recurse flag.  */
268
269  nlines = 5;
270  lines = (char **) xmalloc (5 * sizeof (char *));
271  idx = 0;
272  p = cmds->commands;
273  while (*p != '\0')
274    {
275      char *end = p;
276    find_end:;
277      end = strchr (end, '\n');
278      if (end == 0)
279        end = p + strlen (p);
280      else if (end > p && end[-1] == '\\')
281        {
282          int backslash = 1;
283          register char *b;
284          for (b = end - 2; b >= p && *b == '\\'; --b)
285            backslash = !backslash;
286          if (backslash)
287            {
288              ++end;
289              goto find_end;
290            }
291        }
292
293      if (idx == nlines)
294        {
295          nlines += 2;
296          lines = (char **) xrealloc ((char *) lines,
297                                      nlines * sizeof (char *));
298        }
299      lines[idx++] = savestring (p, end - p);
300      p = end;
301      if (*p != '\0')
302        ++p;
303    }
304
305  if (idx != nlines)
306    {
307      nlines = idx;
308      lines = (char **) xrealloc ((char *) lines,
309                                  nlines * sizeof (char *));
310    }
311
312  cmds->ncommand_lines = nlines;
313  cmds->command_lines = lines;
314
315  cmds->any_recurse = 0;
316  cmds->lines_flags = (char *) xmalloc (nlines);
317  for (idx = 0; idx < nlines; ++idx)
318    {
319      int flags = 0;
320
321      for (p = lines[idx];
322           isblank ((unsigned char)*p) || *p == '-' || *p == '@' || *p == '+';
323           ++p)
324        switch (*p)
325          {
326          case '+':
327            flags |= COMMANDS_RECURSE;
328            break;
329          case '@':
330            flags |= COMMANDS_SILENT;
331            break;
332          case '-':
333            flags |= COMMANDS_NOERROR;
334            break;
335          }
336      if (!(flags & COMMANDS_RECURSE))
337        {
338          unsigned int len = strlen (p);
339          if (sindex (p, len, "$(MAKE)", 7) != 0
340              || sindex (p, len, "${MAKE}", 7) != 0)
341            flags |= COMMANDS_RECURSE;
342        }
343
344      cmds->lines_flags[idx] = flags;
345      cmds->any_recurse |= flags & COMMANDS_RECURSE;
346    }
347}
348
349/* Execute the commands to remake FILE.  If they are currently executing,
350   return or have already finished executing, just return.  Otherwise,
351   fork off a child process to run the first command line in the sequence.  */
352
353void
354execute_file_commands (file)
355     struct file *file;
356{
357  register char *p;
358
359  /* Don't go through all the preparations if
360     the commands are nothing but whitespace.  */
361
362  for (p = file->cmds->commands; *p != '\0'; ++p)
363    if (!isspace ((unsigned char)*p) && *p != '-' && *p != '@')
364      break;
365  if (*p == '\0')
366    {
367      /* If there are no commands, assume everything worked.  */
368      set_command_state (file, cs_running);
369      file->update_status = 0;
370      notice_finished_file (file);
371      return;
372    }
373
374  /* First set the automatic variables according to this file.  */
375
376  initialize_file_variables (file, 0);
377
378  set_file_variables (file);
379
380  /* Start the commands running.  */
381  new_job (file);
382}
383
384/* This is set while we are inside fatal_error_signal,
385   so things can avoid nonreentrant operations.  */
386
387int handling_fatal_signal = 0;
388
389/* Handle fatal signals.  */
390
391RETSIGTYPE
392fatal_error_signal (sig)
393     int sig;
394{
395#ifdef __MSDOS__
396  extern int dos_status, dos_command_running;
397
398  if (dos_command_running)
399    {
400      /* That was the child who got the signal, not us.  */
401      dos_status |= (sig << 8);
402      return;
403    }
404  remove_intermediates (1);
405  exit (EXIT_FAILURE);
406#else /* not __MSDOS__ */
407#ifdef _AMIGA
408  remove_intermediates (1);
409  if (sig == SIGINT)
410     fputs (_("*** Break.\n"), stderr);
411
412  exit (10);
413#else /* not Amiga */
414  handling_fatal_signal = 1;
415
416  /* Set the handling for this signal to the default.
417     It is blocked now while we run this handler.  */
418  signal (sig, SIG_DFL);
419
420  /* A termination signal won't be sent to the entire
421     process group, but it means we want to kill the children.  */
422
423  if (sig == SIGTERM)
424    {
425      register struct child *c;
426      for (c = children; c != 0; c = c->next)
427	if (!c->remote)
428	  (void) kill (c->pid, SIGTERM);
429    }
430
431  /* If we got a signal that means the user
432     wanted to kill make, remove pending targets.  */
433
434  if (sig == SIGTERM || sig == SIGINT
435#ifdef SIGHUP
436    || sig == SIGHUP
437#endif
438#ifdef SIGQUIT
439    || sig == SIGQUIT
440#endif
441    )
442    {
443      register struct child *c;
444
445      /* Remote children won't automatically get signals sent
446	 to the process group, so we must send them.  */
447      for (c = children; c != 0; c = c->next)
448	if (c->remote)
449	  (void) remote_kill (c->pid, sig);
450
451      for (c = children; c != 0; c = c->next)
452	delete_child_targets (c);
453
454      /* Clean up the children.  We don't just use the call below because
455	 we don't want to print the "Waiting for children" message.  */
456      while (job_slots_used > 0)
457	reap_children (1, 0);
458    }
459  else
460    /* Wait for our children to die.  */
461    while (job_slots_used > 0)
462      reap_children (1, 1);
463
464  /* Delete any non-precious intermediate files that were made.  */
465
466  remove_intermediates (1);
467
468#ifdef SIGQUIT
469  if (sig == SIGQUIT)
470    /* We don't want to send ourselves SIGQUIT, because it will
471       cause a core dump.  Just exit instead.  */
472    exit (EXIT_FAILURE);
473#endif
474
475  /* Signal the same code; this time it will really be fatal.  The signal
476     will be unblocked when we return and arrive then to kill us.  */
477  if (kill (getpid (), sig) < 0)
478    pfatal_with_name ("kill");
479#endif /* not Amiga */
480#endif /* not __MSDOS__  */
481}
482
483/* Delete FILE unless it's precious or not actually a file (phony),
484   and it has changed on disk since we last stat'd it.  */
485
486static void
487delete_target (file, on_behalf_of)
488     struct file *file;
489     char *on_behalf_of;
490{
491  struct stat st;
492
493  if (file->precious || file->phony)
494    return;
495
496#ifndef NO_ARCHIVES
497  if (ar_name (file->name))
498    {
499      time_t file_date = (file->last_mtime == NONEXISTENT_MTIME
500			  ? (time_t) -1
501			  : (time_t) FILE_TIMESTAMP_S (file->last_mtime));
502      if (ar_member_date (file->name) != file_date)
503	{
504	  if (on_behalf_of)
505	    error (NILF, _("*** [%s] Archive member `%s' may be bogus; not deleted"),
506		   on_behalf_of, file->name);
507	  else
508	    error (NILF, _("*** Archive member `%s' may be bogus; not deleted"),
509		   file->name);
510	}
511      return;
512    }
513#endif
514
515  if (stat (file->name, &st) == 0
516      && S_ISREG (st.st_mode)
517      && FILE_TIMESTAMP_STAT_MODTIME (file->name, st) != file->last_mtime)
518    {
519      if (on_behalf_of)
520	error (NILF, _("*** [%s] Deleting file `%s'"), on_behalf_of, file->name);
521      else
522	error (NILF, _("*** Deleting file `%s'"), file->name);
523      if (unlink (file->name) < 0
524	  && errno != ENOENT)	/* It disappeared; so what.  */
525	perror_with_name ("unlink: ", file->name);
526    }
527}
528
529
530/* Delete all non-precious targets of CHILD unless they were already deleted.
531   Set the flag in CHILD to say they've been deleted.  */
532
533void
534delete_child_targets (child)
535     struct child *child;
536{
537  struct dep *d;
538
539  if (child->deleted)
540    return;
541
542  /* Delete the target file if it changed.  */
543  delete_target (child->file, (char *) 0);
544
545  /* Also remove any non-precious targets listed in the `also_make' member.  */
546  for (d = child->file->also_make; d != 0; d = d->next)
547    delete_target (d->file, child->file->name);
548
549  child->deleted = 1;
550}
551
552/* Print out the commands in CMDS.  */
553
554void
555print_commands (cmds)
556     register struct commands *cmds;
557{
558  register char *s;
559
560  fputs (_("#  commands to execute"), stdout);
561
562  if (cmds->fileinfo.filenm == 0)
563    puts (_(" (built-in):"));
564  else
565    printf (_(" (from `%s', line %lu):\n"),
566            cmds->fileinfo.filenm, cmds->fileinfo.lineno);
567
568  s = cmds->commands;
569  while (*s != '\0')
570    {
571      char *end;
572
573      while (isspace ((unsigned char)*s))
574	++s;
575
576      end = strchr (s, '\n');
577      if (end == 0)
578	end = s + strlen (s);
579
580      printf ("\t%.*s\n", (int) (end - s), s);
581
582      s = end;
583    }
584}
585