(root)/
make-4.4/
src/
commands.c
       1  /* Command processing for GNU Make.
       2  Copyright (C) 1988-2022 Free Software Foundation, Inc.
       3  This file is part of GNU Make.
       4  
       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.
       9  
      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.
      13  
      14  You should have received a copy of the GNU General Public License along with
      15  this program.  If not, see <https://www.gnu.org/licenses/>.  */
      16  
      17  #include "makeint.h"
      18  #include "filedef.h"
      19  #include "os.h"
      20  #include "dep.h"
      21  #include "variable.h"
      22  #include "job.h"
      23  #include "commands.h"
      24  #ifdef WINDOWS32
      25  #include <windows.h>
      26  #include "w32err.h"
      27  #endif
      28  
      29  #if VMS
      30  # define FILE_LIST_SEPARATOR (vms_comma_separator ? ',' : ' ')
      31  #else
      32  # define FILE_LIST_SEPARATOR ' '
      33  #endif
      34  
      35  
      36  static unsigned long
      37  dep_hash_1 (const void *key)
      38  {
      39    const struct dep *d = key;
      40    return_STRING_HASH_1 (dep_name (d));
      41  }
      42  
      43  static unsigned long
      44  dep_hash_2 (const void *key)
      45  {
      46    const struct dep *d = key;
      47    return_STRING_HASH_2 (dep_name (d));
      48  }
      49  
      50  static int
      51  dep_hash_cmp (const void *x, const void *y)
      52  {
      53    const struct dep *dx = x;
      54    const struct dep *dy = y;
      55    return strcmp (dep_name (dx), dep_name (dy));
      56  }
      57  
      58  /* Set FILE's automatic variables up.
      59   * Use STEM to set $*.
      60   * If STEM is 0, then set FILE->STEM and $* to the target name with any
      61   * suffix in the .SUFFIXES list stripped off.  */
      62  
      63  void
      64  set_file_variables (struct file *file, const char *stem)
      65  {
      66    struct dep *d;
      67    const char *at, *percent, *star, *less;
      68  
      69  #ifndef NO_ARCHIVES
      70    /* If the target is an archive member 'lib(member)',
      71       then $@ is 'lib' and $% is 'member'.  */
      72  
      73    if (ar_name (file->name))
      74      {
      75        size_t len;
      76        const char *cp;
      77        char *p;
      78  
      79        cp = strchr (file->name, '(');
      80        p = alloca (cp - file->name + 1);
      81        memcpy (p, file->name, cp - file->name);
      82        p[cp - file->name] = '\0';
      83        at = p;
      84        len = strlen (cp + 1);
      85        p = alloca (len);
      86        memcpy (p, cp + 1, len - 1);
      87        p[len - 1] = '\0';
      88        percent = p;
      89      }
      90    else
      91  #endif  /* NO_ARCHIVES.  */
      92      {
      93        at = file->name;
      94        percent = "";
      95      }
      96  
      97    /* $* is the stem from an implicit or static pattern rule.  */
      98    if (stem == 0)
      99      {
     100        /* In Unix make, $* is set to the target name with
     101           any suffix in the .SUFFIXES list stripped off for
     102           explicit rules.  We store this in the 'stem' member.  */
     103        const char *name;
     104        size_t len;
     105  
     106  #ifndef NO_ARCHIVES
     107        if (ar_name (file->name))
     108          {
     109            name = strchr (file->name, '(') + 1;
     110            len = strlen (name) - 1;
     111          }
     112        else
     113  #endif
     114          {
     115            name = file->name;
     116            len = strlen (name);
     117          }
     118  
     119        for (d = enter_file (strcache_add (".SUFFIXES"))->deps; d ; d = d->next)
     120          {
     121            const char *dn = dep_name (d);
     122            size_t slen = strlen (dn);
     123            if (len > slen && memcmp (dn, name + (len - slen), slen) == 0)
     124              {
     125                file->stem = stem = strcache_add_len (name, len - slen);
     126                break;
     127              }
     128          }
     129        if (d == 0)
     130          file->stem = stem = "";
     131      }
     132    star = stem;
     133  
     134    /* $< is the first not order-only dependency.  */
     135    less = "";
     136    for (d = file->deps; d != 0; d = d->next)
     137      if (!d->ignore_mtime && !d->ignore_automatic_vars && !d->need_2nd_expansion)
     138        {
     139          less = dep_name (d);
     140          break;
     141        }
     142  
     143    if (file->cmds != 0 && file->cmds == default_file->cmds)
     144      /* This file got its commands from .DEFAULT.
     145         In this case $< is the same as $@.  */
     146      less = at;
     147  
     148  #define DEFINE_VARIABLE(name, len, value) \
     149    (void) define_variable_for_file (name,len,value,o_automatic,0,file)
     150  
     151    /* Define the variables.  */
     152  
     153    DEFINE_VARIABLE ("<", 1, less);
     154    DEFINE_VARIABLE ("*", 1, star);
     155    DEFINE_VARIABLE ("@", 1, at);
     156    DEFINE_VARIABLE ("%", 1, percent);
     157  
     158    /* Compute the values for $^, $+, $?, and $|.  */
     159  
     160    {
     161      static char *plus_value=0, *bar_value=0, *qmark_value=0;
     162      static size_t plus_max=0, bar_max=0, qmark_max=0;
     163  
     164      size_t qmark_len, plus_len, bar_len;
     165      char *cp;
     166      char *caret_value;
     167      char *qp;
     168      char *bp;
     169      size_t len;
     170  
     171      struct hash_table dep_hash;
     172      void **slot;
     173  
     174      /* Compute first the value for $+, which is supposed to contain
     175         duplicate dependencies as they were listed in the makefile.  */
     176  
     177      plus_len = 0;
     178      bar_len = 0;
     179      for (d = file->deps; d != 0; d = d->next)
     180        {
     181          if (!d->need_2nd_expansion && !d->ignore_automatic_vars)
     182            {
     183              if (d->ignore_mtime)
     184                bar_len += strlen (dep_name (d)) + 1;
     185              else
     186                plus_len += strlen (dep_name (d)) + 1;
     187            }
     188        }
     189  
     190      if (bar_len == 0)
     191        bar_len++;
     192  
     193      if (plus_len == 0)
     194        plus_len++;
     195  
     196      if (plus_len > plus_max)
     197        plus_value = xrealloc (plus_value, plus_max = plus_len);
     198  
     199      cp = plus_value;
     200  
     201      qmark_len = plus_len + 1;   /* Will be this or less.  */
     202      for (d = file->deps; d != 0; d = d->next)
     203        if (! d->ignore_mtime && ! d->need_2nd_expansion && ! d->ignore_automatic_vars)
     204          {
     205            const char *c = dep_name (d);
     206  
     207  #ifndef NO_ARCHIVES
     208            if (ar_name (c))
     209              {
     210                c = strchr (c, '(') + 1;
     211                len = strlen (c) - 1;
     212              }
     213            else
     214  #endif
     215              len = strlen (c);
     216  
     217            cp = mempcpy (cp, c, len);
     218            *cp++ = FILE_LIST_SEPARATOR;
     219            if (! (d->changed || always_make_flag))
     220              qmark_len -= len + 1;       /* Don't space in $? for this one.  */
     221          }
     222  
     223      /* Kill the last space and define the variable.  */
     224  
     225      cp[cp > plus_value ? -1 : 0] = '\0';
     226      DEFINE_VARIABLE ("+", 1, plus_value);
     227  
     228      /* Compute the values for $^, $?, and $|.  */
     229  
     230      cp = caret_value = plus_value; /* Reuse the buffer; it's big enough.  */
     231  
     232      if (qmark_len > qmark_max)
     233        qmark_value = xrealloc (qmark_value, qmark_max = qmark_len);
     234      qp = qmark_value;
     235  
     236      if (bar_len > bar_max)
     237        bar_value = xrealloc (bar_value, bar_max = bar_len);
     238      bp = bar_value;
     239  
     240      /* Make sure that no dependencies are repeated in $^, $?, and $|.  It
     241         would be natural to combine the next two loops but we can't do it
     242         because of a situation where we have two dep entries, the first
     243         is order-only and the second is normal (see below).  */
     244  
     245      hash_init (&dep_hash, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);
     246  
     247      for (d = file->deps; d != 0; d = d->next)
     248        {
     249          if (d->need_2nd_expansion || d->ignore_automatic_vars)
     250            continue;
     251  
     252          slot = hash_find_slot (&dep_hash, d);
     253          if (HASH_VACANT (*slot))
     254            hash_insert_at (&dep_hash, d, slot);
     255          else
     256            {
     257              /* Check if the two prerequisites have different ignore_mtime.
     258                 If so then we need to "upgrade" one that is order-only.  */
     259  
     260              struct dep* hd = (struct dep*) *slot;
     261  
     262              if (d->ignore_mtime != hd->ignore_mtime)
     263                d->ignore_mtime = hd->ignore_mtime = 0;
     264            }
     265        }
     266  
     267      for (d = file->deps; d != 0; d = d->next)
     268        {
     269          const char *c;
     270  
     271          if (d->need_2nd_expansion || d->ignore_automatic_vars || hash_find_item (&dep_hash, d) != d)
     272            continue;
     273  
     274          c = dep_name (d);
     275  #ifndef NO_ARCHIVES
     276          if (ar_name (c))
     277            {
     278              c = strchr (c, '(') + 1;
     279              len = strlen (c) - 1;
     280            }
     281          else
     282  #endif
     283            len = strlen (c);
     284  
     285          if (d->ignore_mtime)
     286            {
     287              bp = mempcpy (bp, c, len);
     288              *bp++ = FILE_LIST_SEPARATOR;
     289            }
     290          else
     291            {
     292              cp = mempcpy (cp, c, len);
     293              *cp++ = FILE_LIST_SEPARATOR;
     294              if (d->changed || always_make_flag)
     295                {
     296                  qp = mempcpy (qp, c, len);
     297                  *qp++ = FILE_LIST_SEPARATOR;
     298                }
     299            }
     300        }
     301  
     302      hash_free (&dep_hash, 0);
     303  
     304      /* Kill the last spaces and define the variables.  */
     305  
     306      cp[cp > caret_value ? -1 : 0] = '\0';
     307      DEFINE_VARIABLE ("^", 1, caret_value);
     308  
     309      qp[qp > qmark_value ? -1 : 0] = '\0';
     310      DEFINE_VARIABLE ("?", 1, qmark_value);
     311  
     312      bp[bp > bar_value ? -1 : 0] = '\0';
     313      DEFINE_VARIABLE ("|", 1, bar_value);
     314    }
     315  
     316  #undef  DEFINE_VARIABLE
     317  }
     318  
     319  /* Chop CMDS up into individual command lines if necessary.
     320     Also set the 'lines_flags' and 'any_recurse' members.  */
     321  
     322  void
     323  chop_commands (struct commands *cmds)
     324  {
     325    unsigned short nlines;
     326    unsigned short i;
     327    char **lines;
     328  
     329    /* If we don't have any commands, or we already parsed them, never mind.  */
     330    if (!cmds || cmds->command_lines != NULL)
     331      return;
     332  
     333    /* Chop CMDS->commands up into lines in CMDS->command_lines.  */
     334  
     335    if (one_shell)
     336      {
     337        size_t l = strlen (cmds->commands);
     338  
     339        nlines = 1;
     340        lines = xmalloc (nlines * sizeof (char *));
     341        lines[0] = xstrdup (cmds->commands);
     342  
     343        /* Strip the trailing newline.  */
     344        if (l > 0 && lines[0][l-1] == '\n')
     345          lines[0][l-1] = '\0';
     346      }
     347    else
     348      {
     349        const char *p = cmds->commands;
     350        size_t max = 5;
     351  
     352        nlines = 0;
     353        lines = xmalloc (max * sizeof (char *));
     354        while (*p != '\0')
     355          {
     356            const char *end = p;
     357          find_end:;
     358            end = strchr (end, '\n');
     359            if (end == NULL)
     360              end = p + strlen (p);
     361            else if (end > p && end[-1] == '\\')
     362              {
     363                int backslash = 1;
     364                if (end > p + 1)
     365                  {
     366                    const char *b;
     367                    for (b = end - 2; b >= p && *b == '\\'; --b)
     368                      backslash = !backslash;
     369                  }
     370                if (backslash)
     371                  {
     372                    ++end;
     373                    goto find_end;
     374                  }
     375              }
     376  
     377            if (nlines == USHRT_MAX)
     378              ON (fatal, &cmds->fileinfo,
     379                  _("Recipe has too many lines (limit %hu)"), nlines);
     380  
     381            if (nlines == max)
     382              {
     383                max += 2;
     384                lines = xrealloc (lines, max * sizeof (char *));
     385              }
     386  
     387            lines[nlines++] = xstrndup (p, (size_t) (end - p));
     388            p = end;
     389            if (*p != '\0')
     390              ++p;
     391          }
     392      }
     393  
     394    /* Finally, set the corresponding CMDS->lines_flags elements and the
     395       CMDS->any_recurse flag.  */
     396  
     397    cmds->ncommand_lines = nlines;
     398    cmds->command_lines = lines;
     399  
     400    cmds->any_recurse = 0;
     401    cmds->lines_flags = xmalloc (nlines);
     402  
     403    for (i = 0; i < nlines; ++i)
     404      {
     405        unsigned char flags = 0;
     406        const char *p = lines[i];
     407  
     408        while (ISBLANK (*p) || *p == '-' || *p == '@' || *p == '+')
     409          switch (*(p++))
     410            {
     411            case '+':
     412              flags |= COMMANDS_RECURSE;
     413              break;
     414            case '@':
     415              flags |= COMMANDS_SILENT;
     416              break;
     417            case '-':
     418              flags |= COMMANDS_NOERROR;
     419              break;
     420            }
     421  
     422        /* If no explicit '+' was given, look for MAKE variable references.  */
     423        if (! ANY_SET (flags, COMMANDS_RECURSE)
     424            && (strstr (p, "$(MAKE)") != 0 || strstr (p, "${MAKE}") != 0))
     425          flags |= COMMANDS_RECURSE;
     426  
     427        cmds->lines_flags[i] = flags;
     428        cmds->any_recurse |= ANY_SET (flags, COMMANDS_RECURSE) ? 1 : 0;
     429      }
     430  }
     431  
     432  /* Execute the commands to remake FILE.  If they are currently executing,
     433     return or have already finished executing, just return.  Otherwise,
     434     fork off a child process to run the first command line in the sequence.  */
     435  
     436  void
     437  execute_file_commands (struct file *file)
     438  {
     439    const char *p;
     440  
     441    /* Don't go through all the preparations if
     442       the commands are nothing but whitespace.  */
     443  
     444    for (p = file->cmds->commands; *p != '\0'; ++p)
     445      if (!ISSPACE (*p) && *p != '-' && *p != '@' && *p != '+')
     446        break;
     447    if (*p == '\0')
     448      {
     449        /* If there are no commands, assume everything worked.  */
     450        set_command_state (file, cs_running);
     451        file->update_status = us_success;
     452        notice_finished_file (file);
     453        return;
     454      }
     455  
     456    /* First set the automatic variables according to this file.  */
     457  
     458    initialize_file_variables (file, 0);
     459  
     460    set_file_variables (file, file->stem);
     461  
     462    /* Some systems don't support overwriting a loaded object so if this one
     463       unload it before remaking.  Keep its name in .LOADED: it will be rebuilt
     464       and loaded again.  If rebuilding or loading again fail, then we'll exit
     465       anyway and it won't matter.  */
     466    if (file->loaded && unload_file (file->name) == 0)
     467      {
     468        file->loaded = 0;
     469        file->unloaded = 1;
     470      }
     471  
     472    /* Start the commands running.  */
     473    new_job (file);
     474  }
     475  
     476  /* This is set while we are inside fatal_error_signal,
     477     so things can avoid nonreentrant operations.  */
     478  
     479  volatile sig_atomic_t handling_fatal_signal = 0;
     480  
     481  /* Handle fatal signals.  */
     482  
     483  void
     484  fatal_error_signal (int sig)
     485  {
     486  #ifdef __MSDOS__
     487    extern int dos_status, dos_command_running;
     488  
     489    if (dos_command_running)
     490      {
     491        /* That was the child who got the signal, not us.  */
     492        dos_status |= (sig << 8);
     493        return;
     494      }
     495    remove_intermediates (1);
     496    exit (EXIT_FAILURE);
     497  #else /* not __MSDOS__ */
     498  #ifdef _AMIGA
     499    remove_intermediates (1);
     500    if (sig == SIGINT)
     501       fputs (_("*** Break.\n"), stderr);
     502  
     503    exit (10);
     504  #else /* not Amiga */
     505  #ifdef WINDOWS32
     506    extern HANDLE main_thread;
     507  
     508    /* Windows creates a separate thread for handling Ctrl+C, so we need
     509       to suspend the main thread, or else we will have race conditions
     510       when both threads call reap_children.  */
     511    if (main_thread)
     512      {
     513        DWORD susp_count = SuspendThread (main_thread);
     514  
     515        if (susp_count != 0)
     516          fprintf (stderr, "SuspendThread: suspend count = %lu\n", susp_count);
     517        else if (susp_count == (DWORD)-1)
     518          {
     519            DWORD ierr = GetLastError ();
     520  
     521            fprintf (stderr, "SuspendThread: error %lu: %s\n",
     522                     ierr, map_windows32_error_to_string (ierr));
     523          }
     524      }
     525  #endif
     526    handling_fatal_signal = 1;
     527  
     528    /* Set the handling for this signal to the default.
     529       It is blocked now while we run this handler.  */
     530    signal (sig, SIG_DFL);
     531  
     532    temp_stdin_unlink ();
     533    osync_clear ();
     534    jobserver_clear ();
     535  
     536    /* A termination signal won't be sent to the entire
     537       process group, but it means we want to kill the children.  */
     538  
     539    if (sig == SIGTERM)
     540      {
     541        struct child *c;
     542        for (c = children; c != 0; c = c->next)
     543          if (!c->remote && c->pid > 0)
     544            (void) kill (c->pid, SIGTERM);
     545      }
     546  
     547    /* If we got a signal that means the user
     548       wanted to kill make, remove pending targets.  */
     549  
     550    if (sig == SIGTERM || sig == SIGINT
     551  #ifdef SIGHUP
     552      || sig == SIGHUP
     553  #endif
     554  #ifdef SIGQUIT
     555      || sig == SIGQUIT
     556  #endif
     557      )
     558      {
     559        struct child *c;
     560  
     561        /* Remote children won't automatically get signals sent
     562           to the process group, so we must send them.  */
     563        for (c = children; c != 0; c = c->next)
     564          if (c->remote && c->pid > 0)
     565            (void) remote_kill (c->pid, sig);
     566  
     567        for (c = children; c != 0; c = c->next)
     568          delete_child_targets (c);
     569  
     570        /* Clean up the children.  We don't just use the call below because
     571           we don't want to print the "Waiting for children" message.  */
     572        while (job_slots_used > 0)
     573          reap_children (1, 0);
     574      }
     575    else
     576      /* Wait for our children to die.  */
     577      while (job_slots_used > 0)
     578        reap_children (1, 1);
     579  
     580    /* Delete any non-precious intermediate files that were made.  */
     581  
     582    remove_intermediates (1);
     583  
     584  #ifdef SIGQUIT
     585    if (sig == SIGQUIT)
     586      /* We don't want to send ourselves SIGQUIT, because it will
     587         cause a core dump.  Just exit instead.  */
     588      exit (MAKE_TROUBLE);
     589  #endif
     590  
     591  #ifdef WINDOWS32
     592    if (main_thread)
     593      CloseHandle (main_thread);
     594    /* Cannot call W32_kill with a pid (it needs a handle).  The exit
     595       status of 130 emulates what happens in Bash.  */
     596    exit (130);
     597  #else
     598    /* Signal the same code; this time it will really be fatal.  The signal
     599       will be unblocked when we return and arrive then to kill us.  */
     600    if (kill (make_pid (), sig) < 0)
     601      pfatal_with_name ("kill");
     602  #endif /* not WINDOWS32 */
     603  #endif /* not Amiga */
     604  #endif /* not __MSDOS__  */
     605  }
     606  
     607  /* Delete FILE unless it's precious or not actually a file (phony),
     608     and it has changed on disk since we last stat'd it.  */
     609  
     610  static void
     611  delete_target (struct file *file, const char *on_behalf_of)
     612  {
     613    struct stat st;
     614    int e;
     615  
     616    if (file->precious || file->phony)
     617      return;
     618  
     619  #ifndef NO_ARCHIVES
     620    if (ar_name (file->name))
     621      {
     622        time_t file_date = (file->last_mtime == NONEXISTENT_MTIME
     623                            ? (time_t) -1
     624                            : (time_t) FILE_TIMESTAMP_S (file->last_mtime));
     625        if (ar_member_date (file->name) != file_date)
     626          {
     627            if (on_behalf_of)
     628              OSS (error, NILF,
     629                   _("*** [%s] Archive member '%s' may be bogus; not deleted"),
     630                   on_behalf_of, file->name);
     631            else
     632              OS (error, NILF,
     633                  _("*** Archive member '%s' may be bogus; not deleted"),
     634                  file->name);
     635          }
     636        return;
     637      }
     638  #endif
     639  
     640    EINTRLOOP (e, stat (file->name, &st));
     641    if (e == 0
     642        && S_ISREG (st.st_mode)
     643        && FILE_TIMESTAMP_STAT_MODTIME (file->name, st) != file->last_mtime)
     644      {
     645        if (on_behalf_of)
     646          OSS (error, NILF,
     647               _("*** [%s] Deleting file '%s'"), on_behalf_of, file->name);
     648        else
     649          OS (error, NILF, _("*** Deleting file '%s'"), file->name);
     650        if (unlink (file->name) < 0
     651            && errno != ENOENT)   /* It disappeared; so what.  */
     652          perror_with_name ("unlink: ", file->name);
     653      }
     654  }
     655  
     656  
     657  /* Delete all non-precious targets of CHILD unless they were already deleted.
     658     Set the flag in CHILD to say they've been deleted.  */
     659  
     660  void
     661  delete_child_targets (struct child *child)
     662  {
     663    struct dep *d;
     664  
     665    if (child->deleted || child->pid < 0)
     666      return;
     667  
     668    /* Delete the target file if it changed.  */
     669    delete_target (child->file, NULL);
     670  
     671    /* Also remove any non-precious targets listed in the 'also_make' member.  */
     672    for (d = child->file->also_make; d != 0; d = d->next)
     673      delete_target (d->file, child->file->name);
     674  
     675    child->deleted = 1;
     676  }
     677  
     678  /* Print out the commands in CMDS.  */
     679  
     680  void
     681  print_commands (const struct commands *cmds)
     682  {
     683    const char *s;
     684  
     685    fputs (_("#  recipe to execute"), stdout);
     686  
     687    if (cmds->fileinfo.filenm == 0)
     688      puts (_(" (built-in):"));
     689    else
     690      printf (_(" (from '%s', line %lu):\n"),
     691              cmds->fileinfo.filenm, cmds->fileinfo.lineno);
     692  
     693    s = cmds->commands;
     694    while (*s != '\0')
     695      {
     696        const char *end;
     697        int bs;
     698  
     699        /* Print one full logical recipe line: find a non-escaped newline.  */
     700        for (end = s, bs = 0; *end != '\0'; ++end)
     701          {
     702            if (*end == '\n' && !bs)
     703              break;
     704  
     705            bs = *end == '\\' ? !bs : 0;
     706          }
     707  
     708        printf ("%c%.*s\n", cmd_prefix, (int) (end - s), s);
     709  
     710        s = end + (end[0] == '\n');
     711      }
     712  }