Coverage Report

Created: 2025-12-31 07:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/git/run-command.c
Line
Count
Source
1
#define USE_THE_REPOSITORY_VARIABLE
2
#define DISABLE_SIGN_COMPARE_WARNINGS
3
4
#include "git-compat-util.h"
5
#include "run-command.h"
6
#include "environment.h"
7
#include "exec-cmd.h"
8
#include "gettext.h"
9
#include "sigchain.h"
10
#include "strvec.h"
11
#include "symlinks.h"
12
#include "thread-utils.h"
13
#include "strbuf.h"
14
#include "string-list.h"
15
#include "trace.h"
16
#include "trace2.h"
17
#include "quote.h"
18
#include "config.h"
19
#include "packfile.h"
20
#include "compat/nonblock.h"
21
22
void child_process_init(struct child_process *child)
23
0
{
24
0
  struct child_process blank = CHILD_PROCESS_INIT;
25
0
  memcpy(child, &blank, sizeof(*child));
26
0
}
27
28
void child_process_clear(struct child_process *child)
29
0
{
30
0
  strvec_clear(&child->args);
31
0
  strvec_clear(&child->env);
32
0
}
33
34
struct child_to_clean {
35
  pid_t pid;
36
  struct child_process *process;
37
  struct child_to_clean *next;
38
};
39
static struct child_to_clean *children_to_clean;
40
static int installed_child_cleanup_handler;
41
42
static void cleanup_children(int sig, int in_signal)
43
0
{
44
0
  struct child_to_clean *children_to_wait_for = NULL;
45
46
0
  while (children_to_clean) {
47
0
    struct child_to_clean *p = children_to_clean;
48
0
    children_to_clean = p->next;
49
50
0
    if (p->process && !in_signal) {
51
0
      struct child_process *process = p->process;
52
0
      if (process->clean_on_exit_handler) {
53
0
        trace_printf(
54
0
          "trace: run_command: running exit handler for pid %"
55
0
          PRIuMAX, (uintmax_t)p->pid
56
0
        );
57
0
        process->clean_on_exit_handler(process);
58
0
      }
59
0
    }
60
61
0
    kill(p->pid, sig);
62
63
0
    if (p->process && p->process->wait_after_clean) {
64
0
      p->next = children_to_wait_for;
65
0
      children_to_wait_for = p;
66
0
    } else {
67
0
      if (!in_signal)
68
0
        free(p);
69
0
    }
70
0
  }
71
72
0
  while (children_to_wait_for) {
73
0
    struct child_to_clean *p = children_to_wait_for;
74
0
    children_to_wait_for = p->next;
75
76
0
    while (waitpid(p->pid, NULL, 0) < 0 && errno == EINTR)
77
0
      ; /* spin waiting for process exit or error */
78
79
0
    if (!in_signal)
80
0
      free(p);
81
0
  }
82
0
}
83
84
static void cleanup_children_on_signal(int sig)
85
0
{
86
0
  cleanup_children(sig, 1);
87
0
  sigchain_pop(sig);
88
0
  raise(sig);
89
0
}
90
91
static void cleanup_children_on_exit(void)
92
0
{
93
0
  cleanup_children(SIGTERM, 0);
94
0
}
95
96
static void mark_child_for_cleanup(pid_t pid, struct child_process *process)
97
0
{
98
0
  struct child_to_clean *p = xmalloc(sizeof(*p));
99
0
  p->pid = pid;
100
0
  p->process = process;
101
0
  p->next = children_to_clean;
102
0
  children_to_clean = p;
103
104
0
  if (!installed_child_cleanup_handler) {
105
0
    atexit(cleanup_children_on_exit);
106
0
    sigchain_push_common(cleanup_children_on_signal);
107
0
    installed_child_cleanup_handler = 1;
108
0
  }
109
0
}
110
111
static void clear_child_for_cleanup(pid_t pid)
112
0
{
113
0
  struct child_to_clean **pp;
114
115
0
  for (pp = &children_to_clean; *pp; pp = &(*pp)->next) {
116
0
    struct child_to_clean *clean_me = *pp;
117
118
0
    if (clean_me->pid == pid) {
119
0
      *pp = clean_me->next;
120
0
      free(clean_me);
121
0
      return;
122
0
    }
123
0
  }
124
0
}
125
126
static inline void close_pair(int fd[2])
127
0
{
128
0
  close(fd[0]);
129
0
  close(fd[1]);
130
0
}
131
132
int is_executable(const char *name)
133
0
{
134
0
  struct stat st;
135
136
0
  if (stat(name, &st) || /* stat, not lstat */
137
0
      !S_ISREG(st.st_mode))
138
0
    return 0;
139
140
#if defined(GIT_WINDOWS_NATIVE)
141
  /*
142
   * On Windows there is no executable bit. The file extension
143
   * indicates whether it can be run as an executable, and Git
144
   * has special-handling to detect scripts and launch them
145
   * through the indicated script interpreter. We test for the
146
   * file extension first because virus scanners may make
147
   * it quite expensive to open many files.
148
   */
149
  if (ends_with(name, ".exe"))
150
    return S_IXUSR;
151
152
{
153
  /*
154
   * Now that we know it does not have an executable extension,
155
   * peek into the file instead.
156
   */
157
  char buf[3] = { 0 };
158
  int n;
159
  int fd = open(name, O_RDONLY);
160
  st.st_mode &= ~S_IXUSR;
161
  if (fd >= 0) {
162
    n = read(fd, buf, 2);
163
    if (n == 2)
164
      /* look for a she-bang */
165
      if (!strcmp(buf, "#!"))
166
        st.st_mode |= S_IXUSR;
167
    close(fd);
168
  }
169
}
170
#endif
171
0
  return st.st_mode & S_IXUSR;
172
0
}
173
174
#ifndef locate_in_PATH
175
/*
176
 * Search $PATH for a command.  This emulates the path search that
177
 * execvp would perform, without actually executing the command so it
178
 * can be used before fork() to prepare to run a command using
179
 * execve() or after execvp() to diagnose why it failed.
180
 *
181
 * The caller should ensure that file contains no directory
182
 * separators.
183
 *
184
 * Returns the path to the command, as found in $PATH or NULL if the
185
 * command could not be found.  The caller inherits ownership of the memory
186
 * used to store the resultant path.
187
 *
188
 * This should not be used on Windows, where the $PATH search rules
189
 * are more complicated (e.g., a search for "foo" should find
190
 * "foo.exe").
191
 */
192
static char *locate_in_PATH(const char *file)
193
0
{
194
0
  const char *p = getenv("PATH");
195
0
  struct strbuf buf = STRBUF_INIT;
196
197
0
  if (!p || !*p)
198
0
    return NULL;
199
200
0
  while (1) {
201
0
    const char *end = strchrnul(p, ':');
202
203
0
    strbuf_reset(&buf);
204
205
    /* POSIX specifies an empty entry as the current directory. */
206
0
    if (end != p) {
207
0
      strbuf_add(&buf, p, end - p);
208
0
      strbuf_addch(&buf, '/');
209
0
    }
210
0
    strbuf_addstr(&buf, file);
211
212
0
    if (is_executable(buf.buf))
213
0
      return strbuf_detach(&buf, NULL);
214
215
0
    if (!*end)
216
0
      break;
217
0
    p = end + 1;
218
0
  }
219
220
0
  strbuf_release(&buf);
221
0
  return NULL;
222
0
}
223
#endif
224
225
int exists_in_PATH(const char *command)
226
0
{
227
0
  char *r = locate_in_PATH(command);
228
0
  int found = r != NULL;
229
0
  free(r);
230
0
  return found;
231
0
}
232
233
int sane_execvp(const char *file, char * const argv[])
234
0
{
235
0
#ifndef GIT_WINDOWS_NATIVE
236
  /*
237
   * execvp() doesn't return, so we all we can do is tell trace2
238
   * what we are about to do and let it leave a hint in the log
239
   * (unless of course the execvp() fails).
240
   *
241
   * we skip this for Windows because the compat layer already
242
   * has to emulate the execvp() call anyway.
243
   */
244
0
  int exec_id = trace2_exec(file, (const char **)argv);
245
0
#endif
246
247
0
  if (!execvp(file, argv))
248
0
    return 0; /* cannot happen ;-) */
249
250
0
#ifndef GIT_WINDOWS_NATIVE
251
0
  {
252
0
    int ec = errno;
253
0
    trace2_exec_result(exec_id, ec);
254
0
    errno = ec;
255
0
  }
256
0
#endif
257
258
  /*
259
   * When a command can't be found because one of the directories
260
   * listed in $PATH is unsearchable, execvp reports EACCES, but
261
   * careful usability testing (read: analysis of occasional bug
262
   * reports) reveals that "No such file or directory" is more
263
   * intuitive.
264
   *
265
   * We avoid commands with "/", because execvp will not do $PATH
266
   * lookups in that case.
267
   *
268
   * The reassignment of EACCES to errno looks like a no-op below,
269
   * but we need to protect against exists_in_PATH overwriting errno.
270
   */
271
0
  if (errno == EACCES && !strchr(file, '/'))
272
0
    errno = exists_in_PATH(file) ? EACCES : ENOENT;
273
0
  else if (errno == ENOTDIR && !strchr(file, '/'))
274
0
    errno = ENOENT;
275
0
  return -1;
276
0
}
277
278
char *git_shell_path(void)
279
0
{
280
0
#ifndef GIT_WINDOWS_NATIVE
281
0
  return xstrdup(SHELL_PATH);
282
#else
283
  char *p = locate_in_PATH("sh");
284
  convert_slashes(p);
285
  return p;
286
#endif
287
0
}
288
289
static const char **prepare_shell_cmd(struct strvec *out, const char **argv)
290
0
{
291
0
  if (!argv[0])
292
0
    BUG("shell command is empty");
293
294
0
  if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
295
0
    strvec_push_nodup(out, git_shell_path());
296
0
    strvec_push(out, "-c");
297
298
    /*
299
     * If we have no extra arguments, we do not even need to
300
     * bother with the "$@" magic.
301
     */
302
0
    if (!argv[1])
303
0
      strvec_push(out, argv[0]);
304
0
    else
305
0
      strvec_pushf(out, "%s \"$@\"", argv[0]);
306
0
  }
307
308
0
  strvec_pushv(out, argv);
309
0
  return out->v;
310
0
}
311
312
#ifndef GIT_WINDOWS_NATIVE
313
static int child_notifier = -1;
314
315
enum child_errcode {
316
  CHILD_ERR_CHDIR,
317
  CHILD_ERR_DUP2,
318
  CHILD_ERR_CLOSE,
319
  CHILD_ERR_SIGPROCMASK,
320
  CHILD_ERR_SILENT,
321
  CHILD_ERR_ERRNO
322
};
323
324
struct child_err {
325
  enum child_errcode err;
326
  int syserr; /* errno */
327
};
328
329
static void child_die(enum child_errcode err)
330
0
{
331
0
  struct child_err buf;
332
333
0
  buf.err = err;
334
0
  buf.syserr = errno;
335
336
  /* write(2) on buf smaller than PIPE_BUF (min 512) is atomic: */
337
0
  xwrite(child_notifier, &buf, sizeof(buf));
338
0
  _exit(1);
339
0
}
340
341
static void child_dup2(int fd, int to)
342
0
{
343
0
  if (dup2(fd, to) < 0)
344
0
    child_die(CHILD_ERR_DUP2);
345
0
}
346
347
static void child_close(int fd)
348
0
{
349
0
  if (close(fd))
350
0
    child_die(CHILD_ERR_CLOSE);
351
0
}
352
353
static void child_close_pair(int fd[2])
354
0
{
355
0
  child_close(fd[0]);
356
0
  child_close(fd[1]);
357
0
}
358
359
static void child_error_fn(const char *err UNUSED, va_list params UNUSED)
360
0
{
361
0
  const char msg[] = "error() should not be called in child\n";
362
0
  xwrite(2, msg, sizeof(msg) - 1);
363
0
}
364
365
static void child_warn_fn(const char *err UNUSED, va_list params UNUSED)
366
0
{
367
0
  const char msg[] = "warn() should not be called in child\n";
368
0
  xwrite(2, msg, sizeof(msg) - 1);
369
0
}
370
371
static void NORETURN child_die_fn(const char *err UNUSED, va_list params UNUSED)
372
0
{
373
0
  const char msg[] = "die() should not be called in child\n";
374
0
  xwrite(2, msg, sizeof(msg) - 1);
375
0
  _exit(2);
376
0
}
377
378
/* this runs in the parent process */
379
static void child_err_spew(struct child_process *cmd, struct child_err *cerr)
380
0
{
381
0
  static void (*old_errfn)(const char *err, va_list params);
382
0
  report_fn die_message_routine = get_die_message_routine();
383
384
0
  old_errfn = get_error_routine();
385
0
  set_error_routine(die_message_routine);
386
0
  errno = cerr->syserr;
387
388
0
  switch (cerr->err) {
389
0
  case CHILD_ERR_CHDIR:
390
0
    error_errno("exec '%s': cd to '%s' failed",
391
0
          cmd->args.v[0], cmd->dir);
392
0
    break;
393
0
  case CHILD_ERR_DUP2:
394
0
    error_errno("dup2() in child failed");
395
0
    break;
396
0
  case CHILD_ERR_CLOSE:
397
0
    error_errno("close() in child failed");
398
0
    break;
399
0
  case CHILD_ERR_SIGPROCMASK:
400
0
    error_errno("sigprocmask failed restoring signals");
401
0
    break;
402
0
  case CHILD_ERR_SILENT:
403
0
    break;
404
0
  case CHILD_ERR_ERRNO:
405
0
    error_errno("cannot exec '%s'", cmd->args.v[0]);
406
0
    break;
407
0
  }
408
0
  set_error_routine(old_errfn);
409
0
}
410
411
static int prepare_cmd(struct strvec *out, const struct child_process *cmd)
412
0
{
413
0
  if (!cmd->args.v[0])
414
0
    BUG("command is empty");
415
416
  /*
417
   * Add SHELL_PATH so in the event exec fails with ENOEXEC we can
418
   * attempt to interpret the command with 'sh'.
419
   */
420
0
  strvec_push(out, SHELL_PATH);
421
422
0
  if (cmd->git_cmd) {
423
0
    prepare_git_cmd(out, cmd->args.v);
424
0
  } else if (cmd->use_shell) {
425
0
    prepare_shell_cmd(out, cmd->args.v);
426
0
  } else {
427
0
    strvec_pushv(out, cmd->args.v);
428
0
  }
429
430
  /*
431
   * If there are no dir separator characters in the command then perform
432
   * a path lookup and use the resolved path as the command to exec. If
433
   * there are dir separator characters, we have exec attempt to invoke
434
   * the command directly.
435
   */
436
0
  if (!has_dir_sep(out->v[1])) {
437
0
    char *program = locate_in_PATH(out->v[1]);
438
0
    if (program) {
439
0
      free((char *)out->v[1]);
440
0
      out->v[1] = program;
441
0
    } else {
442
0
      strvec_clear(out);
443
0
      errno = ENOENT;
444
0
      return -1;
445
0
    }
446
0
  }
447
448
0
  return 0;
449
0
}
450
451
static char **prep_childenv(const char *const *deltaenv)
452
0
{
453
0
  extern char **environ;
454
0
  char **childenv;
455
0
  struct string_list env = STRING_LIST_INIT_DUP;
456
0
  struct strbuf key = STRBUF_INIT;
457
0
  const char *const *p;
458
0
  int i;
459
460
  /* Construct a sorted string list consisting of the current environ */
461
0
  for (p = (const char *const *) environ; p && *p; p++) {
462
0
    const char *equals = strchr(*p, '=');
463
464
0
    if (equals) {
465
0
      strbuf_reset(&key);
466
0
      strbuf_add(&key, *p, equals - *p);
467
0
      string_list_append(&env, key.buf)->util = (void *) *p;
468
0
    } else {
469
0
      string_list_append(&env, *p)->util = (void *) *p;
470
0
    }
471
0
  }
472
0
  string_list_sort(&env);
473
474
  /* Merge in 'deltaenv' with the current environ */
475
0
  for (p = deltaenv; p && *p; p++) {
476
0
    const char *equals = strchr(*p, '=');
477
478
0
    if (equals) {
479
      /* ('key=value'), insert or replace entry */
480
0
      strbuf_reset(&key);
481
0
      strbuf_add(&key, *p, equals - *p);
482
0
      string_list_insert(&env, key.buf)->util = (void *) *p;
483
0
    } else {
484
      /* otherwise ('key') remove existing entry */
485
0
      string_list_remove(&env, *p, 0);
486
0
    }
487
0
  }
488
489
  /* Create an array of 'char *' to be used as the childenv */
490
0
  ALLOC_ARRAY(childenv, env.nr + 1);
491
0
  for (i = 0; i < env.nr; i++)
492
0
    childenv[i] = env.items[i].util;
493
0
  childenv[env.nr] = NULL;
494
495
0
  string_list_clear(&env, 0);
496
0
  strbuf_release(&key);
497
0
  return childenv;
498
0
}
499
500
struct atfork_state {
501
#ifndef NO_PTHREADS
502
  int cs;
503
#endif
504
  sigset_t old;
505
};
506
507
#define CHECK_BUG(err, msg) \
508
0
  do { \
509
0
    int e = (err); \
510
0
    if (e) \
511
0
      BUG("%s: %s", msg, strerror(e)); \
512
0
  } while(0)
513
514
static void atfork_prepare(struct atfork_state *as)
515
0
{
516
0
  sigset_t all;
517
518
  /*
519
   * POSIX says sigfillset() can fail, but an overly clever
520
   * compiler can see through the header files and decide
521
   * it cannot fail on a particular platform it is compiling for,
522
   * triggering -Wunreachable-code false positive.
523
   */
524
0
  if (NOT_CONSTANT(sigfillset(&all)))
525
0
    die_errno("sigfillset");
526
#ifdef NO_PTHREADS
527
  if (sigprocmask(SIG_SETMASK, &all, &as->old))
528
    die_errno("sigprocmask");
529
#else
530
0
  CHECK_BUG(pthread_sigmask(SIG_SETMASK, &all, &as->old),
531
0
    "blocking all signals");
532
0
  CHECK_BUG(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &as->cs),
533
0
    "disabling cancellation");
534
0
#endif
535
0
}
536
537
static void atfork_parent(struct atfork_state *as)
538
0
{
539
#ifdef NO_PTHREADS
540
  if (sigprocmask(SIG_SETMASK, &as->old, NULL))
541
    die_errno("sigprocmask");
542
#else
543
0
  CHECK_BUG(pthread_setcancelstate(as->cs, NULL),
544
0
    "re-enabling cancellation");
545
0
  CHECK_BUG(pthread_sigmask(SIG_SETMASK, &as->old, NULL),
546
0
    "restoring signal mask");
547
0
#endif
548
0
}
549
#endif /* GIT_WINDOWS_NATIVE */
550
551
static inline void set_cloexec(int fd)
552
0
{
553
0
  int flags = fcntl(fd, F_GETFD);
554
0
  if (flags >= 0)
555
0
    fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
556
0
}
557
558
static int wait_or_whine(pid_t pid, const char *argv0, int in_signal)
559
0
{
560
0
  int status, code = -1;
561
0
  pid_t waiting;
562
0
  int failed_errno = 0;
563
564
0
  while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
565
0
    ;  /* nothing */
566
567
0
  if (waiting < 0) {
568
0
    failed_errno = errno;
569
0
    if (!in_signal)
570
0
      error_errno("waitpid for %s failed", argv0);
571
0
  } else if (waiting != pid) {
572
0
    if (!in_signal)
573
0
      error("waitpid is confused (%s)", argv0);
574
0
  } else if (WIFSIGNALED(status)) {
575
0
    code = WTERMSIG(status);
576
0
    if (!in_signal && code != SIGINT && code != SIGQUIT && code != SIGPIPE)
577
0
      error("%s died of signal %d", argv0, code);
578
    /*
579
     * This return value is chosen so that code & 0xff
580
     * mimics the exit code that a POSIX shell would report for
581
     * a program that died from this signal.
582
     */
583
0
    code += 128;
584
0
  } else if (WIFEXITED(status)) {
585
0
    code = WEXITSTATUS(status);
586
0
  } else {
587
0
    if (!in_signal)
588
0
      error("waitpid is confused (%s)", argv0);
589
0
  }
590
591
0
  if (!in_signal)
592
0
    clear_child_for_cleanup(pid);
593
594
0
  errno = failed_errno;
595
0
  return code;
596
0
}
597
598
static void trace_add_env(struct strbuf *dst, const char *const *deltaenv)
599
0
{
600
0
  struct string_list envs = STRING_LIST_INIT_DUP;
601
0
  const char *const *e;
602
0
  int i;
603
0
  int printed_unset = 0;
604
605
  /* Last one wins, see run-command.c:prep_childenv() for context */
606
0
  for (e = deltaenv; e && *e; e++) {
607
0
    struct strbuf key = STRBUF_INIT;
608
0
    char *equals = strchr(*e, '=');
609
610
0
    if (equals) {
611
0
      strbuf_add(&key, *e, equals - *e);
612
0
      string_list_insert(&envs, key.buf)->util = equals + 1;
613
0
    } else {
614
0
      string_list_insert(&envs, *e)->util = NULL;
615
0
    }
616
0
    strbuf_release(&key);
617
0
  }
618
619
  /* "unset X Y...;" */
620
0
  for (i = 0; i < envs.nr; i++) {
621
0
    const char *var = envs.items[i].string;
622
0
    const char *val = envs.items[i].util;
623
624
0
    if (val || !getenv(var))
625
0
      continue;
626
627
0
    if (!printed_unset) {
628
0
      strbuf_addstr(dst, " unset");
629
0
      printed_unset = 1;
630
0
    }
631
0
    strbuf_addf(dst, " %s", var);
632
0
  }
633
0
  if (printed_unset)
634
0
    strbuf_addch(dst, ';');
635
636
  /* ... followed by "A=B C=D ..." */
637
0
  for (i = 0; i < envs.nr; i++) {
638
0
    const char *var = envs.items[i].string;
639
0
    const char *val = envs.items[i].util;
640
0
    const char *oldval;
641
642
0
    if (!val)
643
0
      continue;
644
645
0
    oldval = getenv(var);
646
0
    if (oldval && !strcmp(val, oldval))
647
0
      continue;
648
649
0
    strbuf_addf(dst, " %s=", var);
650
0
    sq_quote_buf_pretty(dst, val);
651
0
  }
652
0
  string_list_clear(&envs, 0);
653
0
}
654
655
static void trace_run_command(const struct child_process *cp)
656
0
{
657
0
  struct strbuf buf = STRBUF_INIT;
658
659
0
  if (!trace_want(&trace_default_key))
660
0
    return;
661
662
0
  strbuf_addstr(&buf, "trace: run_command:");
663
0
  if (cp->dir) {
664
0
    strbuf_addstr(&buf, " cd ");
665
0
    sq_quote_buf_pretty(&buf, cp->dir);
666
0
    strbuf_addch(&buf, ';');
667
0
  }
668
0
  trace_add_env(&buf, cp->env.v);
669
0
  if (cp->git_cmd)
670
0
    strbuf_addstr(&buf, " git");
671
0
  sq_quote_argv_pretty(&buf, cp->args.v);
672
673
0
  trace_printf("%s", buf.buf);
674
0
  strbuf_release(&buf);
675
0
}
676
677
int start_command(struct child_process *cmd)
678
0
{
679
0
  int need_in, need_out, need_err;
680
0
  int fdin[2], fdout[2], fderr[2];
681
0
  int failed_errno;
682
0
  const char *str;
683
684
  /*
685
   * In case of errors we must keep the promise to close FDs
686
   * that have been passed in via ->in and ->out.
687
   */
688
689
0
  need_in = !cmd->no_stdin && cmd->in < 0;
690
0
  if (need_in) {
691
0
    if (pipe(fdin) < 0) {
692
0
      failed_errno = errno;
693
0
      if (cmd->out > 0)
694
0
        close(cmd->out);
695
0
      str = "standard input";
696
0
      goto fail_pipe;
697
0
    }
698
0
    cmd->in = fdin[1];
699
0
  }
700
701
0
  need_out = !cmd->no_stdout
702
0
    && !cmd->stdout_to_stderr
703
0
    && cmd->out < 0;
704
0
  if (need_out) {
705
0
    if (pipe(fdout) < 0) {
706
0
      failed_errno = errno;
707
0
      if (need_in)
708
0
        close_pair(fdin);
709
0
      else if (cmd->in)
710
0
        close(cmd->in);
711
0
      str = "standard output";
712
0
      goto fail_pipe;
713
0
    }
714
0
    cmd->out = fdout[0];
715
0
  }
716
717
0
  need_err = !cmd->no_stderr && cmd->err < 0;
718
0
  if (need_err) {
719
0
    if (pipe(fderr) < 0) {
720
0
      failed_errno = errno;
721
0
      if (need_in)
722
0
        close_pair(fdin);
723
0
      else if (cmd->in)
724
0
        close(cmd->in);
725
0
      if (need_out)
726
0
        close_pair(fdout);
727
0
      else if (cmd->out)
728
0
        close(cmd->out);
729
0
      str = "standard error";
730
0
fail_pipe:
731
0
      error("cannot create %s pipe for %s: %s",
732
0
        str, cmd->args.v[0], strerror(failed_errno));
733
0
      child_process_clear(cmd);
734
0
      errno = failed_errno;
735
0
      return -1;
736
0
    }
737
0
    cmd->err = fderr[0];
738
0
  }
739
740
0
  trace2_child_start(cmd);
741
0
  trace_run_command(cmd);
742
743
0
  fflush(NULL);
744
745
0
  if (cmd->close_object_store)
746
0
    odb_close(the_repository->objects);
747
748
0
#ifndef GIT_WINDOWS_NATIVE
749
0
{
750
0
  int notify_pipe[2];
751
0
  int null_fd = -1;
752
0
  char **childenv;
753
0
  struct strvec argv = STRVEC_INIT;
754
0
  struct child_err cerr;
755
0
  struct atfork_state as;
756
757
0
  if (prepare_cmd(&argv, cmd) < 0) {
758
0
    failed_errno = errno;
759
0
    cmd->pid = -1;
760
0
    if (!cmd->silent_exec_failure)
761
0
      error_errno("cannot run %s", cmd->args.v[0]);
762
0
    goto end_of_spawn;
763
0
  }
764
765
0
  trace_argv_printf(&argv.v[1], "trace: start_command:");
766
767
0
  if (pipe(notify_pipe))
768
0
    notify_pipe[0] = notify_pipe[1] = -1;
769
770
0
  if (cmd->no_stdin || cmd->no_stdout || cmd->no_stderr) {
771
0
    null_fd = xopen("/dev/null", O_RDWR | O_CLOEXEC);
772
0
    set_cloexec(null_fd);
773
0
  }
774
775
0
  childenv = prep_childenv(cmd->env.v);
776
0
  atfork_prepare(&as);
777
778
  /*
779
   * NOTE: In order to prevent deadlocking when using threads special
780
   * care should be taken with the function calls made in between the
781
   * fork() and exec() calls.  No calls should be made to functions which
782
   * require acquiring a lock (e.g. malloc) as the lock could have been
783
   * held by another thread at the time of forking, causing the lock to
784
   * never be released in the child process.  This means only
785
   * Async-Signal-Safe functions are permitted in the child.
786
   */
787
0
  cmd->pid = fork();
788
0
  failed_errno = errno;
789
0
  if (!cmd->pid) {
790
0
    int sig;
791
    /*
792
     * Ensure the default die/error/warn routines do not get
793
     * called, they can take stdio locks and malloc.
794
     */
795
0
    set_die_routine(child_die_fn);
796
0
    set_error_routine(child_error_fn);
797
0
    set_warn_routine(child_warn_fn);
798
799
0
    close(notify_pipe[0]);
800
0
    set_cloexec(notify_pipe[1]);
801
0
    child_notifier = notify_pipe[1];
802
803
0
    if (cmd->no_stdin)
804
0
      child_dup2(null_fd, 0);
805
0
    else if (need_in) {
806
0
      child_dup2(fdin[0], 0);
807
0
      child_close_pair(fdin);
808
0
    } else if (cmd->in) {
809
0
      child_dup2(cmd->in, 0);
810
0
      child_close(cmd->in);
811
0
    }
812
813
0
    if (cmd->no_stderr)
814
0
      child_dup2(null_fd, 2);
815
0
    else if (need_err) {
816
0
      child_dup2(fderr[1], 2);
817
0
      child_close_pair(fderr);
818
0
    } else if (cmd->err > 1) {
819
0
      child_dup2(cmd->err, 2);
820
0
      child_close(cmd->err);
821
0
    }
822
823
0
    if (cmd->no_stdout)
824
0
      child_dup2(null_fd, 1);
825
0
    else if (cmd->stdout_to_stderr)
826
0
      child_dup2(2, 1);
827
0
    else if (need_out) {
828
0
      child_dup2(fdout[1], 1);
829
0
      child_close_pair(fdout);
830
0
    } else if (cmd->out > 1) {
831
0
      child_dup2(cmd->out, 1);
832
0
      child_close(cmd->out);
833
0
    }
834
835
0
    if (cmd->dir && chdir(cmd->dir))
836
0
      child_die(CHILD_ERR_CHDIR);
837
838
    /*
839
     * restore default signal handlers here, in case
840
     * we catch a signal right before execve below
841
     */
842
0
    for (sig = 1; sig < NSIG; sig++) {
843
      /* ignored signals get reset to SIG_DFL on execve */
844
0
      if (signal(sig, SIG_DFL) == SIG_IGN)
845
0
        signal(sig, SIG_IGN);
846
0
    }
847
848
0
    if (sigprocmask(SIG_SETMASK, &as.old, NULL) != 0)
849
0
      child_die(CHILD_ERR_SIGPROCMASK);
850
851
    /*
852
     * Attempt to exec using the command and arguments starting at
853
     * argv.argv[1].  argv.argv[0] contains SHELL_PATH which will
854
     * be used in the event exec failed with ENOEXEC at which point
855
     * we will try to interpret the command using 'sh'.
856
     */
857
0
    execve(argv.v[1], (char *const *) argv.v + 1,
858
0
           (char *const *) childenv);
859
0
    if (errno == ENOEXEC)
860
0
      execve(argv.v[0], (char *const *) argv.v,
861
0
             (char *const *) childenv);
862
863
0
    if (cmd->silent_exec_failure && errno == ENOENT)
864
0
      child_die(CHILD_ERR_SILENT);
865
0
    child_die(CHILD_ERR_ERRNO);
866
0
  }
867
0
  atfork_parent(&as);
868
0
  if (cmd->pid < 0)
869
0
    error_errno("cannot fork() for %s", cmd->args.v[0]);
870
0
  else if (cmd->clean_on_exit)
871
0
    mark_child_for_cleanup(cmd->pid, cmd);
872
873
  /*
874
   * Wait for child's exec. If the exec succeeds (or if fork()
875
   * failed), EOF is seen immediately by the parent. Otherwise, the
876
   * child process sends a child_err struct.
877
   * Note that use of this infrastructure is completely advisory,
878
   * therefore, we keep error checks minimal.
879
   */
880
0
  close(notify_pipe[1]);
881
0
  if (xread(notify_pipe[0], &cerr, sizeof(cerr)) == sizeof(cerr)) {
882
    /*
883
     * At this point we know that fork() succeeded, but exec()
884
     * failed. Errors have been reported to our stderr.
885
     */
886
0
    wait_or_whine(cmd->pid, cmd->args.v[0], 0);
887
0
    child_err_spew(cmd, &cerr);
888
0
    failed_errno = errno;
889
0
    cmd->pid = -1;
890
0
  }
891
0
  close(notify_pipe[0]);
892
893
0
  if (null_fd >= 0)
894
0
    close(null_fd);
895
0
  strvec_clear(&argv);
896
0
  free(childenv);
897
0
}
898
0
end_of_spawn:
899
900
#else
901
{
902
  int fhin = 0, fhout = 1, fherr = 2;
903
  const char **sargv = cmd->args.v;
904
  struct strvec nargv = STRVEC_INIT;
905
906
  if (cmd->no_stdin)
907
    fhin = open("/dev/null", O_RDWR);
908
  else if (need_in)
909
    fhin = dup(fdin[0]);
910
  else if (cmd->in)
911
    fhin = dup(cmd->in);
912
913
  if (cmd->no_stderr)
914
    fherr = open("/dev/null", O_RDWR);
915
  else if (need_err)
916
    fherr = dup(fderr[1]);
917
  else if (cmd->err > 2)
918
    fherr = dup(cmd->err);
919
920
  if (cmd->no_stdout)
921
    fhout = open("/dev/null", O_RDWR);
922
  else if (cmd->stdout_to_stderr)
923
    fhout = dup(fherr);
924
  else if (need_out)
925
    fhout = dup(fdout[1]);
926
  else if (cmd->out > 1)
927
    fhout = dup(cmd->out);
928
929
  if (cmd->git_cmd)
930
    cmd->args.v = prepare_git_cmd(&nargv, sargv);
931
  else if (cmd->use_shell)
932
    cmd->args.v = prepare_shell_cmd(&nargv, sargv);
933
934
  trace_argv_printf(cmd->args.v, "trace: start_command:");
935
  cmd->pid = mingw_spawnvpe(cmd->args.v[0], cmd->args.v,
936
          (char**) cmd->env.v,
937
          cmd->dir, fhin, fhout, fherr);
938
  failed_errno = errno;
939
  if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
940
    error_errno("cannot spawn %s", cmd->args.v[0]);
941
  if (cmd->clean_on_exit && cmd->pid >= 0)
942
    mark_child_for_cleanup(cmd->pid, cmd);
943
944
  strvec_clear(&nargv);
945
  cmd->args.v = sargv;
946
  if (fhin != 0)
947
    close(fhin);
948
  if (fhout != 1)
949
    close(fhout);
950
  if (fherr != 2)
951
    close(fherr);
952
}
953
#endif
954
955
0
  if (cmd->pid < 0) {
956
0
    trace2_child_exit(cmd, -1);
957
958
0
    if (need_in)
959
0
      close_pair(fdin);
960
0
    else if (cmd->in)
961
0
      close(cmd->in);
962
0
    if (need_out)
963
0
      close_pair(fdout);
964
0
    else if (cmd->out)
965
0
      close(cmd->out);
966
0
    if (need_err)
967
0
      close_pair(fderr);
968
0
    else if (cmd->err)
969
0
      close(cmd->err);
970
0
    child_process_clear(cmd);
971
0
    errno = failed_errno;
972
0
    return -1;
973
0
  }
974
975
0
  if (need_in)
976
0
    close(fdin[0]);
977
0
  else if (cmd->in)
978
0
    close(cmd->in);
979
980
0
  if (need_out)
981
0
    close(fdout[1]);
982
0
  else if (cmd->out)
983
0
    close(cmd->out);
984
985
0
  if (need_err)
986
0
    close(fderr[1]);
987
0
  else if (cmd->err)
988
0
    close(cmd->err);
989
990
0
  return 0;
991
0
}
992
993
int finish_command(struct child_process *cmd)
994
0
{
995
0
  int ret = wait_or_whine(cmd->pid, cmd->args.v[0], 0);
996
0
  trace2_child_exit(cmd, ret);
997
0
  child_process_clear(cmd);
998
0
  invalidate_lstat_cache();
999
0
  return ret;
1000
0
}
1001
1002
int finish_command_in_signal(struct child_process *cmd)
1003
0
{
1004
0
  int ret = wait_or_whine(cmd->pid, cmd->args.v[0], 1);
1005
0
  if (ret != -1)
1006
0
    trace2_child_exit(cmd, ret);
1007
0
  return ret;
1008
0
}
1009
1010
1011
int run_command(struct child_process *cmd)
1012
0
{
1013
0
  int code;
1014
1015
0
  if (cmd->out < 0 || cmd->err < 0)
1016
0
    BUG("run_command with a pipe can cause deadlock");
1017
1018
0
  code = start_command(cmd);
1019
0
  if (code)
1020
0
    return code;
1021
0
  return finish_command(cmd);
1022
0
}
1023
1024
#ifndef NO_PTHREADS
1025
static pthread_t main_thread;
1026
static int main_thread_set;
1027
static pthread_key_t async_key;
1028
static pthread_key_t async_die_counter;
1029
1030
static void *run_thread(void *data)
1031
0
{
1032
0
  struct async *async = data;
1033
0
  intptr_t ret;
1034
1035
0
  if (async->isolate_sigpipe) {
1036
0
    sigset_t mask;
1037
0
    sigemptyset(&mask);
1038
0
    sigaddset(&mask, SIGPIPE);
1039
0
    if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) {
1040
0
      ret = error("unable to block SIGPIPE in async thread");
1041
0
      return (void *)ret;
1042
0
    }
1043
0
  }
1044
1045
0
  pthread_setspecific(async_key, async);
1046
0
  ret = async->proc(async->proc_in, async->proc_out, async->data);
1047
0
  return (void *)ret;
1048
0
}
1049
1050
static NORETURN void die_async(const char *err, va_list params)
1051
0
{
1052
0
  report_fn die_message_fn = get_die_message_routine();
1053
1054
0
  die_message_fn(err, params);
1055
1056
0
  if (in_async()) {
1057
0
    struct async *async = pthread_getspecific(async_key);
1058
0
    if (async->proc_in >= 0)
1059
0
      close(async->proc_in);
1060
0
    if (async->proc_out >= 0)
1061
0
      close(async->proc_out);
1062
0
    pthread_exit((void *)128);
1063
0
  }
1064
1065
0
  exit(128);
1066
0
}
1067
1068
static int async_die_is_recursing(void)
1069
0
{
1070
0
  void *ret = pthread_getspecific(async_die_counter);
1071
0
  pthread_setspecific(async_die_counter, &async_die_counter); /* set to any non-NULL valid pointer */
1072
0
  return ret != NULL;
1073
0
}
1074
1075
int in_async(void)
1076
0
{
1077
0
  if (!main_thread_set)
1078
0
    return 0; /* no asyncs started yet */
1079
0
  return !pthread_equal(main_thread, pthread_self());
1080
0
}
1081
1082
static void NORETURN async_exit(int code)
1083
0
{
1084
0
  pthread_exit((void *)(intptr_t)code);
1085
0
}
1086
1087
#else
1088
1089
static struct {
1090
  void (**handlers)(void);
1091
  size_t nr;
1092
  size_t alloc;
1093
} git_atexit_hdlrs;
1094
1095
static int git_atexit_installed;
1096
1097
static void git_atexit_dispatch(void)
1098
{
1099
  size_t i;
1100
1101
  for (i=git_atexit_hdlrs.nr ; i ; i--)
1102
    git_atexit_hdlrs.handlers[i-1]();
1103
}
1104
1105
static void git_atexit_clear(void)
1106
{
1107
  free(git_atexit_hdlrs.handlers);
1108
  memset(&git_atexit_hdlrs, 0, sizeof(git_atexit_hdlrs));
1109
  git_atexit_installed = 0;
1110
}
1111
1112
#undef atexit
1113
int git_atexit(void (*handler)(void))
1114
{
1115
  ALLOC_GROW(git_atexit_hdlrs.handlers, git_atexit_hdlrs.nr + 1, git_atexit_hdlrs.alloc);
1116
  git_atexit_hdlrs.handlers[git_atexit_hdlrs.nr++] = handler;
1117
  if (!git_atexit_installed) {
1118
    if (atexit(&git_atexit_dispatch))
1119
      return -1;
1120
    git_atexit_installed = 1;
1121
  }
1122
  return 0;
1123
}
1124
#define atexit git_atexit
1125
1126
static int process_is_async;
1127
int in_async(void)
1128
{
1129
  return process_is_async;
1130
}
1131
1132
static void NORETURN async_exit(int code)
1133
{
1134
  exit(code);
1135
}
1136
1137
#endif
1138
1139
void check_pipe(int err)
1140
0
{
1141
0
  if (err == EPIPE) {
1142
0
    if (in_async())
1143
0
      async_exit(141);
1144
1145
0
    signal(SIGPIPE, SIG_DFL);
1146
0
    raise(SIGPIPE);
1147
    /* Should never happen, but just in case... */
1148
0
    exit(141);
1149
0
  }
1150
0
}
1151
1152
int start_async(struct async *async)
1153
0
{
1154
0
  int need_in, need_out;
1155
0
  int fdin[2], fdout[2];
1156
0
  int proc_in, proc_out;
1157
1158
0
  need_in = async->in < 0;
1159
0
  if (need_in) {
1160
0
    if (pipe(fdin) < 0) {
1161
0
      if (async->out > 0)
1162
0
        close(async->out);
1163
0
      return error_errno("cannot create pipe");
1164
0
    }
1165
0
    async->in = fdin[1];
1166
0
  }
1167
1168
0
  need_out = async->out < 0;
1169
0
  if (need_out) {
1170
0
    if (pipe(fdout) < 0) {
1171
0
      if (need_in)
1172
0
        close_pair(fdin);
1173
0
      else if (async->in)
1174
0
        close(async->in);
1175
0
      return error_errno("cannot create pipe");
1176
0
    }
1177
0
    async->out = fdout[0];
1178
0
  }
1179
1180
0
  if (need_in)
1181
0
    proc_in = fdin[0];
1182
0
  else if (async->in)
1183
0
    proc_in = async->in;
1184
0
  else
1185
0
    proc_in = -1;
1186
1187
0
  if (need_out)
1188
0
    proc_out = fdout[1];
1189
0
  else if (async->out)
1190
0
    proc_out = async->out;
1191
0
  else
1192
0
    proc_out = -1;
1193
1194
#ifdef NO_PTHREADS
1195
  /* Flush stdio before fork() to avoid cloning buffers */
1196
  fflush(NULL);
1197
1198
  async->pid = fork();
1199
  if (async->pid < 0) {
1200
    error_errno("fork (async) failed");
1201
    goto error;
1202
  }
1203
  if (!async->pid) {
1204
    if (need_in)
1205
      close(fdin[1]);
1206
    if (need_out)
1207
      close(fdout[0]);
1208
    git_atexit_clear();
1209
    process_is_async = 1;
1210
    exit(!!async->proc(proc_in, proc_out, async->data));
1211
  }
1212
1213
  mark_child_for_cleanup(async->pid, NULL);
1214
1215
  if (need_in)
1216
    close(fdin[0]);
1217
  else if (async->in)
1218
    close(async->in);
1219
1220
  if (need_out)
1221
    close(fdout[1]);
1222
  else if (async->out)
1223
    close(async->out);
1224
#else
1225
0
  if (!main_thread_set) {
1226
    /*
1227
     * We assume that the first time that start_async is called
1228
     * it is from the main thread.
1229
     */
1230
0
    main_thread_set = 1;
1231
0
    main_thread = pthread_self();
1232
0
    pthread_key_create(&async_key, NULL);
1233
0
    pthread_key_create(&async_die_counter, NULL);
1234
0
    set_die_routine(die_async);
1235
0
    set_die_is_recursing_routine(async_die_is_recursing);
1236
0
  }
1237
1238
0
  if (proc_in >= 0)
1239
0
    set_cloexec(proc_in);
1240
0
  if (proc_out >= 0)
1241
0
    set_cloexec(proc_out);
1242
0
  async->proc_in = proc_in;
1243
0
  async->proc_out = proc_out;
1244
0
  {
1245
0
    int err = pthread_create(&async->tid, NULL, run_thread, async);
1246
0
    if (err) {
1247
0
      error(_("cannot create async thread: %s"), strerror(err));
1248
0
      goto error;
1249
0
    }
1250
0
  }
1251
0
#endif
1252
0
  return 0;
1253
1254
0
error:
1255
0
  if (need_in)
1256
0
    close_pair(fdin);
1257
0
  else if (async->in)
1258
0
    close(async->in);
1259
1260
0
  if (need_out)
1261
0
    close_pair(fdout);
1262
0
  else if (async->out)
1263
0
    close(async->out);
1264
0
  return -1;
1265
0
}
1266
1267
int finish_async(struct async *async)
1268
0
{
1269
#ifdef NO_PTHREADS
1270
  int ret = wait_or_whine(async->pid, "child process", 0);
1271
1272
  invalidate_lstat_cache();
1273
1274
  return ret;
1275
#else
1276
0
  void *ret = (void *)(intptr_t)(-1);
1277
1278
0
  if (pthread_join(async->tid, &ret))
1279
0
    error("pthread_join failed");
1280
0
  invalidate_lstat_cache();
1281
0
  return (int)(intptr_t)ret;
1282
1283
0
#endif
1284
0
}
1285
1286
int async_with_fork(void)
1287
0
{
1288
#ifdef NO_PTHREADS
1289
  return 1;
1290
#else
1291
0
  return 0;
1292
0
#endif
1293
0
}
1294
1295
struct io_pump {
1296
  /* initialized by caller */
1297
  int fd;
1298
  int type; /* POLLOUT or POLLIN */
1299
  union {
1300
    struct {
1301
      const char *buf;
1302
      size_t len;
1303
    } out;
1304
    struct {
1305
      struct strbuf *buf;
1306
      size_t hint;
1307
    } in;
1308
  } u;
1309
1310
  /* returned by pump_io */
1311
  int error; /* 0 for success, otherwise errno */
1312
1313
  /* internal use */
1314
  struct pollfd *pfd;
1315
};
1316
1317
static int pump_io_round(struct io_pump *slots, int nr, struct pollfd *pfd)
1318
0
{
1319
0
  int pollsize = 0;
1320
0
  int i;
1321
1322
0
  for (i = 0; i < nr; i++) {
1323
0
    struct io_pump *io = &slots[i];
1324
0
    if (io->fd < 0)
1325
0
      continue;
1326
0
    pfd[pollsize].fd = io->fd;
1327
0
    pfd[pollsize].events = io->type;
1328
0
    io->pfd = &pfd[pollsize++];
1329
0
  }
1330
1331
0
  if (!pollsize)
1332
0
    return 0;
1333
1334
0
  if (poll(pfd, pollsize, -1) < 0) {
1335
0
    if (errno == EINTR)
1336
0
      return 1;
1337
0
    die_errno("poll failed");
1338
0
  }
1339
1340
0
  for (i = 0; i < nr; i++) {
1341
0
    struct io_pump *io = &slots[i];
1342
1343
0
    if (io->fd < 0)
1344
0
      continue;
1345
1346
0
    if (!(io->pfd->revents & (POLLOUT|POLLIN|POLLHUP|POLLERR|POLLNVAL)))
1347
0
      continue;
1348
1349
0
    if (io->type == POLLOUT) {
1350
0
      ssize_t len;
1351
1352
      /*
1353
       * Don't use xwrite() here. It loops forever on EAGAIN,
1354
       * and we're in our own poll() loop here.
1355
       *
1356
       * Note that we lose xwrite()'s handling of MAX_IO_SIZE
1357
       * and EINTR, so we have to implement those ourselves.
1358
       */
1359
0
      len = write(io->fd, io->u.out.buf,
1360
0
            io->u.out.len <= MAX_IO_SIZE ?
1361
0
            io->u.out.len : MAX_IO_SIZE);
1362
0
      if (len < 0) {
1363
0
        if (errno != EINTR && errno != EAGAIN &&
1364
0
            errno != ENOSPC) {
1365
0
          io->error = errno;
1366
0
          close(io->fd);
1367
0
          io->fd = -1;
1368
0
        }
1369
0
      } else {
1370
0
        io->u.out.buf += len;
1371
0
        io->u.out.len -= len;
1372
0
        if (!io->u.out.len) {
1373
0
          close(io->fd);
1374
0
          io->fd = -1;
1375
0
        }
1376
0
      }
1377
0
    }
1378
1379
0
    if (io->type == POLLIN) {
1380
0
      ssize_t len = strbuf_read_once(io->u.in.buf,
1381
0
                   io->fd, io->u.in.hint);
1382
0
      if (len < 0)
1383
0
        io->error = errno;
1384
0
      if (len <= 0) {
1385
0
        close(io->fd);
1386
0
        io->fd = -1;
1387
0
      }
1388
0
    }
1389
0
  }
1390
1391
0
  return 1;
1392
0
}
1393
1394
static int pump_io(struct io_pump *slots, int nr)
1395
0
{
1396
0
  struct pollfd *pfd;
1397
0
  int i;
1398
1399
0
  for (i = 0; i < nr; i++)
1400
0
    slots[i].error = 0;
1401
1402
0
  ALLOC_ARRAY(pfd, nr);
1403
0
  while (pump_io_round(slots, nr, pfd))
1404
0
    ; /* nothing */
1405
0
  free(pfd);
1406
1407
  /* There may be multiple errno values, so just pick the first. */
1408
0
  for (i = 0; i < nr; i++) {
1409
0
    if (slots[i].error) {
1410
0
      errno = slots[i].error;
1411
0
      return -1;
1412
0
    }
1413
0
  }
1414
0
  return 0;
1415
0
}
1416
1417
1418
int pipe_command(struct child_process *cmd,
1419
     const char *in, size_t in_len,
1420
     struct strbuf *out, size_t out_hint,
1421
     struct strbuf *err, size_t err_hint)
1422
0
{
1423
0
  struct io_pump io[3];
1424
0
  int nr = 0;
1425
1426
0
  if (in)
1427
0
    cmd->in = -1;
1428
0
  if (out)
1429
0
    cmd->out = -1;
1430
0
  if (err)
1431
0
    cmd->err = -1;
1432
1433
0
  if (start_command(cmd) < 0)
1434
0
    return -1;
1435
1436
0
  if (in) {
1437
0
    if (enable_pipe_nonblock(cmd->in) < 0) {
1438
0
      error_errno("unable to make pipe non-blocking");
1439
0
      close(cmd->in);
1440
0
      if (out)
1441
0
        close(cmd->out);
1442
0
      if (err)
1443
0
        close(cmd->err);
1444
0
      return -1;
1445
0
    }
1446
0
    io[nr].fd = cmd->in;
1447
0
    io[nr].type = POLLOUT;
1448
0
    io[nr].u.out.buf = in;
1449
0
    io[nr].u.out.len = in_len;
1450
0
    nr++;
1451
0
  }
1452
0
  if (out) {
1453
0
    io[nr].fd = cmd->out;
1454
0
    io[nr].type = POLLIN;
1455
0
    io[nr].u.in.buf = out;
1456
0
    io[nr].u.in.hint = out_hint;
1457
0
    nr++;
1458
0
  }
1459
0
  if (err) {
1460
0
    io[nr].fd = cmd->err;
1461
0
    io[nr].type = POLLIN;
1462
0
    io[nr].u.in.buf = err;
1463
0
    io[nr].u.in.hint = err_hint;
1464
0
    nr++;
1465
0
  }
1466
1467
0
  if (pump_io(io, nr) < 0) {
1468
0
    finish_command(cmd); /* throw away exit code */
1469
0
    return -1;
1470
0
  }
1471
1472
0
  return finish_command(cmd);
1473
0
}
1474
1475
enum child_state {
1476
  GIT_CP_FREE,
1477
  GIT_CP_WORKING,
1478
  GIT_CP_WAIT_CLEANUP,
1479
};
1480
1481
struct parallel_processes {
1482
  size_t nr_processes;
1483
1484
  struct {
1485
    enum child_state state;
1486
    struct child_process process;
1487
    struct strbuf err;
1488
    void *data;
1489
  } *children;
1490
  /*
1491
   * The struct pollfd is logically part of *children,
1492
   * but the system call expects it as its own array.
1493
   */
1494
  struct pollfd *pfd;
1495
1496
  unsigned shutdown : 1;
1497
1498
  size_t output_owner;
1499
  struct strbuf buffered_output; /* of finished children */
1500
};
1501
1502
struct parallel_processes_for_signal {
1503
  const struct run_process_parallel_opts *opts;
1504
  const struct parallel_processes *pp;
1505
};
1506
1507
static void kill_children(const struct parallel_processes *pp,
1508
        const struct run_process_parallel_opts *opts,
1509
        int signo)
1510
0
{
1511
0
  for (size_t i = 0; i < opts->processes; i++)
1512
0
    if (pp->children[i].state == GIT_CP_WORKING)
1513
0
      kill(pp->children[i].process.pid, signo);
1514
0
}
1515
1516
static void kill_children_signal(const struct parallel_processes_for_signal *pp_sig,
1517
         int signo)
1518
0
{
1519
0
  kill_children(pp_sig->pp, pp_sig->opts, signo);
1520
0
}
1521
1522
static struct parallel_processes_for_signal *pp_for_signal;
1523
1524
static void handle_children_on_signal(int signo)
1525
0
{
1526
0
  kill_children_signal(pp_for_signal, signo);
1527
0
  sigchain_pop(signo);
1528
0
  raise(signo);
1529
0
}
1530
1531
static void pp_init(struct parallel_processes *pp,
1532
        const struct run_process_parallel_opts *opts,
1533
        struct parallel_processes_for_signal *pp_sig)
1534
0
{
1535
0
  const size_t n = opts->processes;
1536
1537
0
  if (!n)
1538
0
    BUG("you must provide a non-zero number of processes!");
1539
1540
0
  trace_printf("run_processes_parallel: preparing to run up to %"PRIuMAX" tasks",
1541
0
         (uintmax_t)n);
1542
1543
0
  if (!opts->get_next_task)
1544
0
    BUG("you need to specify a get_next_task function");
1545
1546
0
  CALLOC_ARRAY(pp->children, n);
1547
0
  if (!opts->ungroup)
1548
0
    CALLOC_ARRAY(pp->pfd, n);
1549
1550
0
  for (size_t i = 0; i < n; i++) {
1551
0
    strbuf_init(&pp->children[i].err, 0);
1552
0
    child_process_init(&pp->children[i].process);
1553
0
    if (pp->pfd) {
1554
0
      pp->pfd[i].events = POLLIN | POLLHUP;
1555
0
      pp->pfd[i].fd = -1;
1556
0
    }
1557
0
  }
1558
1559
0
  pp_sig->pp = pp;
1560
0
  pp_sig->opts = opts;
1561
0
  pp_for_signal = pp_sig;
1562
0
  sigchain_push_common(handle_children_on_signal);
1563
0
}
1564
1565
static void pp_cleanup(struct parallel_processes *pp,
1566
           const struct run_process_parallel_opts *opts)
1567
0
{
1568
0
  trace_printf("run_processes_parallel: done");
1569
0
  for (size_t i = 0; i < opts->processes; i++) {
1570
0
    strbuf_release(&pp->children[i].err);
1571
0
    child_process_clear(&pp->children[i].process);
1572
0
  }
1573
1574
0
  free(pp->children);
1575
0
  free(pp->pfd);
1576
1577
  /*
1578
   * When get_next_task added messages to the buffer in its last
1579
   * iteration, the buffered output is non empty.
1580
   */
1581
0
  strbuf_write(&pp->buffered_output, stderr);
1582
0
  strbuf_release(&pp->buffered_output);
1583
1584
0
  sigchain_pop_common();
1585
0
}
1586
1587
/* returns
1588
 *  0 if a new task was started.
1589
 *  1 if no new jobs was started (get_next_task ran out of work, non critical
1590
 *    problem with starting a new command)
1591
 * <0 no new job was started, user wishes to shutdown early. Use negative code
1592
 *    to signal the children.
1593
 */
1594
static int pp_start_one(struct parallel_processes *pp,
1595
      const struct run_process_parallel_opts *opts)
1596
0
{
1597
0
  size_t i;
1598
0
  int code;
1599
1600
0
  for (i = 0; i < opts->processes; i++)
1601
0
    if (pp->children[i].state == GIT_CP_FREE)
1602
0
      break;
1603
0
  if (i == opts->processes)
1604
0
    BUG("bookkeeping is hard");
1605
1606
  /*
1607
   * By default, do not inherit stdin from the parent process - otherwise,
1608
   * all children would share stdin! Users may overwrite this to provide
1609
   * something to the child's stdin by having their 'get_next_task'
1610
   * callback assign 0 to .no_stdin and an appropriate integer to .in.
1611
   */
1612
0
  pp->children[i].process.no_stdin = 1;
1613
1614
0
  code = opts->get_next_task(&pp->children[i].process,
1615
0
           opts->ungroup ? NULL : &pp->children[i].err,
1616
0
           opts->data,
1617
0
           &pp->children[i].data);
1618
0
  if (!code) {
1619
0
    if (!opts->ungroup) {
1620
0
      strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1621
0
      strbuf_reset(&pp->children[i].err);
1622
0
    }
1623
0
    return 1;
1624
0
  }
1625
0
  if (!opts->ungroup) {
1626
0
    pp->children[i].process.err = -1;
1627
0
    pp->children[i].process.stdout_to_stderr = 1;
1628
0
  }
1629
1630
0
  if (start_command(&pp->children[i].process)) {
1631
0
    if (opts->start_failure)
1632
0
      code = opts->start_failure(opts->ungroup ? NULL :
1633
0
               &pp->children[i].err,
1634
0
               opts->data,
1635
0
               pp->children[i].data);
1636
0
    else
1637
0
      code = 0;
1638
1639
0
    if (!opts->ungroup) {
1640
0
      strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1641
0
      strbuf_reset(&pp->children[i].err);
1642
0
    }
1643
0
    if (code)
1644
0
      pp->shutdown = 1;
1645
0
    return code;
1646
0
  }
1647
1648
0
  pp->nr_processes++;
1649
0
  pp->children[i].state = GIT_CP_WORKING;
1650
0
  if (pp->pfd)
1651
0
    pp->pfd[i].fd = pp->children[i].process.err;
1652
0
  return 0;
1653
0
}
1654
1655
static void pp_buffer_stderr(struct parallel_processes *pp,
1656
           const struct run_process_parallel_opts *opts,
1657
           int output_timeout)
1658
0
{
1659
0
  while (poll(pp->pfd, opts->processes, output_timeout) < 0) {
1660
0
    if (errno == EINTR)
1661
0
      continue;
1662
0
    pp_cleanup(pp, opts);
1663
0
    die_errno("poll");
1664
0
  }
1665
1666
  /* Buffer output from all pipes. */
1667
0
  for (size_t i = 0; i < opts->processes; i++) {
1668
0
    if (pp->children[i].state == GIT_CP_WORKING &&
1669
0
        pp->pfd[i].revents & (POLLIN | POLLHUP)) {
1670
0
      int n = strbuf_read_once(&pp->children[i].err,
1671
0
             pp->children[i].process.err, 0);
1672
0
      if (n == 0) {
1673
0
        close(pp->children[i].process.err);
1674
0
        pp->children[i].state = GIT_CP_WAIT_CLEANUP;
1675
0
      } else if (n < 0)
1676
0
        if (errno != EAGAIN)
1677
0
          die_errno("read");
1678
0
    }
1679
0
  }
1680
0
}
1681
1682
static void pp_output(const struct parallel_processes *pp)
1683
0
{
1684
0
  size_t i = pp->output_owner;
1685
1686
0
  if (pp->children[i].state == GIT_CP_WORKING &&
1687
0
      pp->children[i].err.len) {
1688
0
    strbuf_write(&pp->children[i].err, stderr);
1689
0
    strbuf_reset(&pp->children[i].err);
1690
0
  }
1691
0
}
1692
1693
static int pp_collect_finished(struct parallel_processes *pp,
1694
             const struct run_process_parallel_opts *opts)
1695
0
{
1696
0
  int code;
1697
0
  size_t i;
1698
0
  int result = 0;
1699
1700
0
  while (pp->nr_processes > 0) {
1701
0
    for (i = 0; i < opts->processes; i++)
1702
0
      if (pp->children[i].state == GIT_CP_WAIT_CLEANUP)
1703
0
        break;
1704
0
    if (i == opts->processes)
1705
0
      break;
1706
1707
0
    code = finish_command(&pp->children[i].process);
1708
1709
0
    if (opts->task_finished)
1710
0
      code = opts->task_finished(code, opts->ungroup ? NULL :
1711
0
               &pp->children[i].err, opts->data,
1712
0
               pp->children[i].data);
1713
0
    else
1714
0
      code = 0;
1715
1716
0
    if (code)
1717
0
      result = code;
1718
0
    if (code < 0)
1719
0
      break;
1720
1721
0
    pp->nr_processes--;
1722
0
    pp->children[i].state = GIT_CP_FREE;
1723
0
    if (pp->pfd)
1724
0
      pp->pfd[i].fd = -1;
1725
0
    child_process_init(&pp->children[i].process);
1726
1727
0
    if (opts->ungroup) {
1728
0
      ; /* no strbuf_*() work to do here */
1729
0
    } else if (i != pp->output_owner) {
1730
0
      strbuf_addbuf(&pp->buffered_output, &pp->children[i].err);
1731
0
      strbuf_reset(&pp->children[i].err);
1732
0
    } else {
1733
0
      const size_t n = opts->processes;
1734
1735
0
      strbuf_write(&pp->children[i].err, stderr);
1736
0
      strbuf_reset(&pp->children[i].err);
1737
1738
      /* Output all other finished child processes */
1739
0
      strbuf_write(&pp->buffered_output, stderr);
1740
0
      strbuf_reset(&pp->buffered_output);
1741
1742
      /*
1743
       * Pick next process to output live.
1744
       * NEEDSWORK:
1745
       * For now we pick it randomly by doing a round
1746
       * robin. Later we may want to pick the one with
1747
       * the most output or the longest or shortest
1748
       * running process time.
1749
       */
1750
0
      for (i = 0; i < n; i++)
1751
0
        if (pp->children[(pp->output_owner + i) % n].state == GIT_CP_WORKING)
1752
0
          break;
1753
0
      pp->output_owner = (pp->output_owner + i) % n;
1754
0
    }
1755
0
  }
1756
0
  return result;
1757
0
}
1758
1759
void run_processes_parallel(const struct run_process_parallel_opts *opts)
1760
0
{
1761
0
  int i, code;
1762
0
  int output_timeout = 100;
1763
0
  int spawn_cap = 4;
1764
0
  struct parallel_processes_for_signal pp_sig;
1765
0
  struct parallel_processes pp = {
1766
0
    .buffered_output = STRBUF_INIT,
1767
0
  };
1768
  /* options */
1769
0
  const char *tr2_category = opts->tr2_category;
1770
0
  const char *tr2_label = opts->tr2_label;
1771
0
  const int do_trace2 = tr2_category && tr2_label;
1772
1773
0
  if (do_trace2)
1774
0
    trace2_region_enter_printf(tr2_category, tr2_label, NULL,
1775
0
             "max:%"PRIuMAX,
1776
0
             (uintmax_t)opts->processes);
1777
1778
0
  pp_init(&pp, opts, &pp_sig);
1779
0
  while (1) {
1780
0
    for (i = 0;
1781
0
        i < spawn_cap && !pp.shutdown &&
1782
0
        pp.nr_processes < opts->processes;
1783
0
        i++) {
1784
0
      code = pp_start_one(&pp, opts);
1785
0
      if (!code)
1786
0
        continue;
1787
0
      if (code < 0) {
1788
0
        pp.shutdown = 1;
1789
0
        kill_children(&pp, opts, -code);
1790
0
      }
1791
0
      break;
1792
0
    }
1793
0
    if (!pp.nr_processes)
1794
0
      break;
1795
0
    if (opts->ungroup) {
1796
0
      for (size_t i = 0; i < opts->processes; i++)
1797
0
        pp.children[i].state = GIT_CP_WAIT_CLEANUP;
1798
0
    } else {
1799
0
      pp_buffer_stderr(&pp, opts, output_timeout);
1800
0
      pp_output(&pp);
1801
0
    }
1802
0
    code = pp_collect_finished(&pp, opts);
1803
0
    if (code) {
1804
0
      pp.shutdown = 1;
1805
0
      if (code < 0)
1806
0
        kill_children(&pp, opts,-code);
1807
0
    }
1808
0
  }
1809
1810
0
  pp_cleanup(&pp, opts);
1811
1812
0
  if (do_trace2)
1813
0
    trace2_region_leave(tr2_category, tr2_label, NULL);
1814
0
}
1815
1816
int prepare_auto_maintenance(int quiet, struct child_process *maint)
1817
0
{
1818
0
  int enabled, auto_detach;
1819
1820
0
  if (!repo_config_get_bool(the_repository, "maintenance.auto", &enabled) &&
1821
0
      !enabled)
1822
0
    return 0;
1823
1824
  /*
1825
   * When `maintenance.autoDetach` isn't set, then we fall back to
1826
   * honoring `gc.autoDetach`. This is somewhat weird, but required to
1827
   * retain behaviour from when we used to run git-gc(1) here.
1828
   */
1829
0
  if (repo_config_get_bool(the_repository, "maintenance.autodetach", &auto_detach) &&
1830
0
      repo_config_get_bool(the_repository, "gc.autodetach", &auto_detach))
1831
0
    auto_detach = 1;
1832
1833
0
  maint->git_cmd = 1;
1834
0
  maint->close_object_store = 1;
1835
0
  strvec_pushl(&maint->args, "maintenance", "run", "--auto", NULL);
1836
0
  strvec_push(&maint->args, quiet ? "--quiet" : "--no-quiet");
1837
0
  strvec_push(&maint->args, auto_detach ? "--detach" : "--no-detach");
1838
1839
0
  return 1;
1840
0
}
1841
1842
int run_auto_maintenance(int quiet)
1843
0
{
1844
0
  struct child_process maint = CHILD_PROCESS_INIT;
1845
0
  if (!prepare_auto_maintenance(quiet, &maint))
1846
0
    return 0;
1847
0
  return run_command(&maint);
1848
0
}
1849
1850
void prepare_other_repo_env(struct strvec *env, const char *new_git_dir)
1851
0
{
1852
0
  const char * const *var;
1853
1854
0
  for (var = local_repo_env; *var; var++) {
1855
0
    if (strcmp(*var, CONFIG_DATA_ENVIRONMENT) &&
1856
0
        strcmp(*var, CONFIG_COUNT_ENVIRONMENT))
1857
0
      strvec_push(env, *var);
1858
0
  }
1859
0
  strvec_pushf(env, "%s=%s", GIT_DIR_ENVIRONMENT, new_git_dir);
1860
0
}
1861
1862
enum start_bg_result start_bg_command(struct child_process *cmd,
1863
              start_bg_wait_cb *wait_cb,
1864
              void *cb_data,
1865
              unsigned int timeout_sec)
1866
0
{
1867
0
  enum start_bg_result sbgr = SBGR_ERROR;
1868
0
  int ret;
1869
0
  int wait_status;
1870
0
  pid_t pid_seen;
1871
0
  time_t time_limit;
1872
1873
  /*
1874
   * We do not allow clean-on-exit because the child process
1875
   * should persist in the background and possibly/probably
1876
   * after this process exits.  So we don't want to kill the
1877
   * child during our atexit routine.
1878
   */
1879
0
  if (cmd->clean_on_exit)
1880
0
    BUG("start_bg_command() does not allow non-zero clean_on_exit");
1881
1882
0
  if (!cmd->trace2_child_class)
1883
0
    cmd->trace2_child_class = "background";
1884
1885
0
  ret = start_command(cmd);
1886
0
  if (ret) {
1887
    /*
1888
     * We assume that if `start_command()` fails, we
1889
     * either get a complete `trace2_child_start() /
1890
     * trace2_child_exit()` pair or it fails before the
1891
     * `trace2_child_start()` is emitted, so we do not
1892
     * need to worry about it here.
1893
     *
1894
     * We also assume that `start_command()` does not add
1895
     * us to the cleanup list.  And that it calls
1896
     * `child_process_clear()`.
1897
     */
1898
0
    sbgr = SBGR_ERROR;
1899
0
    goto done;
1900
0
  }
1901
1902
0
  time(&time_limit);
1903
0
  time_limit += timeout_sec;
1904
1905
0
wait:
1906
0
  pid_seen = waitpid(cmd->pid, &wait_status, WNOHANG);
1907
1908
0
  if (!pid_seen) {
1909
    /*
1910
     * The child is currently running.  Ask the callback
1911
     * if the child is ready to do work or whether we
1912
     * should keep waiting for it to boot up.
1913
     */
1914
0
    ret = (*wait_cb)(cmd, cb_data);
1915
0
    if (!ret) {
1916
      /*
1917
       * The child is running and "ready".
1918
       */
1919
0
      trace2_child_ready(cmd, "ready");
1920
0
      sbgr = SBGR_READY;
1921
0
      goto done;
1922
0
    } else if (ret > 0) {
1923
      /*
1924
       * The callback said to give it more time to boot up
1925
       * (subject to our timeout limit).
1926
       */
1927
0
      time_t now;
1928
1929
0
      time(&now);
1930
0
      if (now < time_limit)
1931
0
        goto wait;
1932
1933
      /*
1934
       * Our timeout has expired.  We don't try to
1935
       * kill the child, but rather let it continue
1936
       * (hopefully) trying to startup.
1937
       */
1938
0
      trace2_child_ready(cmd, "timeout");
1939
0
      sbgr = SBGR_TIMEOUT;
1940
0
      goto done;
1941
0
    } else {
1942
      /*
1943
       * The cb gave up on this child.  It is still running,
1944
       * but our cb got an error trying to probe it.
1945
       */
1946
0
      trace2_child_ready(cmd, "error");
1947
0
      sbgr = SBGR_CB_ERROR;
1948
0
      goto done;
1949
0
    }
1950
0
  }
1951
1952
0
  else if (pid_seen == cmd->pid) {
1953
0
    int child_code = -1;
1954
1955
    /*
1956
     * The child started, but exited or was terminated
1957
     * before becoming "ready".
1958
     *
1959
     * We try to match the behavior of `wait_or_whine()`
1960
     * WRT the handling of WIFSIGNALED() and WIFEXITED()
1961
     * and convert the child's status to a return code for
1962
     * tracing purposes and emit the `trace2_child_exit()`
1963
     * event.
1964
     *
1965
     * We do not want the wait_or_whine() error message
1966
     * because we will be called by client-side library
1967
     * routines.
1968
     */
1969
0
    if (WIFEXITED(wait_status))
1970
0
      child_code = WEXITSTATUS(wait_status);
1971
0
    else if (WIFSIGNALED(wait_status))
1972
0
      child_code = WTERMSIG(wait_status) + 128;
1973
0
    trace2_child_exit(cmd, child_code);
1974
1975
0
    sbgr = SBGR_DIED;
1976
0
    goto done;
1977
0
  }
1978
1979
0
  else if (pid_seen < 0 && errno == EINTR)
1980
0
    goto wait;
1981
1982
0
  trace2_child_exit(cmd, -1);
1983
0
  sbgr = SBGR_ERROR;
1984
1985
0
done:
1986
0
  child_process_clear(cmd);
1987
0
  invalidate_lstat_cache();
1988
0
  return sbgr;
1989
0
}