-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathprocess.cppm
More file actions
1001 lines (920 loc) · 43.3 KB
/
Copy pathprocess.cppm
File metadata and controls
1001 lines (920 loc) · 43.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// mcpp.platform.process — platform-aware process runner.
//
// Centralises all popen/system usage so callers do not scatter #if _WIN32
// guards or duplicate the popen-read loop. All functions automatically
// seal stdin (redirect from /dev/null on POSIX, from NUL on Windows) to
// prevent interactive prompts from child processes:
// - POSIX: fixes macOS first-run hangs where xcrun / xcode-select would
// block waiting for user input.
// - Windows: fixes first-run hangs where xlings / xim / curl / git child
// processes would block on terminal stdin, forcing the user to press
// Enter repeatedly to advance bootstrap / toolchain install.
//
// Entry points:
// capture — run a command, capture stdout
// run_silent — run a command, discard output
// run_streaming — run a command, stream stdout line by line
//
// NOTE: These functions run commands through the platform shell (sh/cmd.exe).
// Callers are responsible for shell-quoting arguments (see platform.shell).
module;
#ifndef _GNU_SOURCE
#define _GNU_SOURCE // for posix_spawn_file_actions_addchdir_np (glibc)
#endif
#include <cstdio>
#include <cstdlib>
#if defined(_WIN32)
#include <stdlib.h> // _putenv_s
#define popen _popen
#define pclose _pclose
#elif defined(__linux__) || defined(__APPLE__)
// Linux and macOS launchers do a direct exec (see run_exec / capture_exec
// below); only Windows keeps the std::system shell path (#248).
#include <unistd.h> // pipe, dup2, close, read
#include <sys/wait.h> // waitpid
#include <spawn.h> // posix_spawnp, posix_spawn_file_actions_* (incl. addchdir_np)
// The deadline runners' headers (signal.h, errno, poll.h, fcntl.h, time.h)
// left with them: bounded runs now live in mcpp.platform.unix.bounded_process
// and mcpp.platform.windows.bounded_process, and this file only dispatches.
#if defined(__APPLE__)
#include <crt_externs.h> // _NSGetEnviron — direct `environ` is only linkable
// from executables on Apple, not from dylibs
#else
extern "C" char **environ;
#endif
#endif
export module mcpp.platform.process;
import std;
import mcpp.platform.common; // is_windows, for the dispatch
import mcpp.platform.env;
import mcpp.platform.shell;
import mcpp.platform.unix.bounded_process;
import mcpp.platform.windows.bounded_process;
export namespace mcpp::platform::process {
struct RunResult {
int exit_code = 0;
std::string output;
};
// Run `command` via the platform shell, capture stdout.
// On POSIX, stdin is automatically redirected from /dev/null.
RunResult capture(std::string_view command);
// Run a host tool while clearing target runtime library search variables.
// This prevents target/program LD_LIBRARY_PATH from poisoning system tools
// such as sha256sum, compiler probes, env, or the shell itself.
RunResult capture_host_tool(std::string_view command);
// Run `command` with extra environment variables (additive).
// Windows: _putenv_s (mutates calling process env).
// POSIX: prefixes command with VAR=val tokens (no mutation).
RunResult capture_with_env(
std::string_view command,
const std::vector<std::pair<std::string, std::string>>& env);
// Launch a program DIRECTLY (no shell), inheriting stdio. argv[0] is the
// program (PATH-searched). `extraEnv` is applied to the CHILD ONLY — the
// calling process environment is never mutated, so a target's loader vars
// (LD_LIBRARY_PATH) cannot poison mcpp itself or any sibling host process.
// Returns a platform-normalized exit code, or 127 if exec fails.
//
// ⚠️ A SPAWN FAILURE IS REPORTED EXACTLY ONCE AND NEVER DROPPED (#544). Every
// launcher below follows one rule: when the child could not be started it
// returns 127 and either (a) stores the errno in `*spawn_error` and prints
// nothing, because a caller that asked for the errno owns the report, or
// (b) with `spawn_error == nullptr`, reports it itself — on stderr here, into
// `output` for the capturing variants. Before this rule `run_exec` turned
// every posix_spawnp failure into a bare 127: `mcpp run` on an artifact the
// kernel refused printed "Running …", a blank line, and exited 1.
//
// `*spawn_error` is 0 whenever the child was spawned, whatever it then did.
// On the residual Windows std::system branch the launch cannot be told apart
// from the child, so it stays 0 and the shell's own message is what is seen.
int run_exec(const std::vector<std::string>& argv,
const std::vector<std::pair<std::string, std::string>>& extraEnv = {},
int* spawn_error = nullptr);
// Same as run_exec but captures stdout AND stderr combined (replaces the old
// `… 2>&1` redirect) into RunResult::output. Required because the only consumer
// (ninja fast-path) parses error text — which ninja writes to stderr — via
// is_stale_ninja_failure / filter_ninja_output. No shell → no quoting/injection.
// `spawn_error`: the same contract as run_exec's.
RunResult capture_exec(
const std::vector<std::string>& argv,
const std::vector<std::pair<std::string, std::string>>& extraEnv = {},
std::string_view cwd = {},
int* spawn_error = nullptr);
// Deadline variants: kill the child once `deadline` elapses and set
// *timed_out. A zero deadline means no limit.
//
// The implementations live per platform — mcpp.platform.unix.bounded_process
// (posix_spawn + SIGKILL) and mcpp.platform.windows.bounded_process
// (CreateProcess + a Job object, so the kill takes the whole tree rather than
// just the direct child). This file dispatches between them ONCE, in
// dispatch_bounded below.
//
// BOTH are real bounds now. They were not: the Windows side used to fall
// through to the unbounded launcher, so every timeout knob (`mcpp test
// --timeout`, `--build-timeout`, `[build] build_program_timeout`) was a silent
// no-op there — set, reported nowhere, and doing nothing.
// `spawn_error`: run_exec's contract. A refused spawn is typed here from the
// bounded launcher's own attempt; there is no second spawn.
int run_exec_deadline(const std::vector<std::string>& argv,
const std::vector<std::pair<std::string, std::string>>& extraEnv,
std::chrono::milliseconds deadline,
bool* timed_out,
int* spawn_error = nullptr);
// Run one host-shell command with inherited stdio, a working directory and a
// real deadline. POSIX uses /bin/sh; Windows uses cmd.exe. This is for
// user-authored command strings such as project hooks — programmatic launches
// keep using the argv-based run_exec_deadline API above.
//
// `cwd` is where the command runs; empty means "inherit ours". It is a
// PARAMETER rather than something the caller arranges with a chdir: the
// process-wide working directory is shared state, and the launchers underneath
// already carry a per-child cwd (posix_spawn_file_actions_addchdir_np /
// CreateProcess's lpCurrentDirectory).
//
// Returns 127 when the shell itself could not be started — the same code a
// shell uses for a command it cannot find, and never confusable with a
// command that ran.
int run_shell_deadline(std::string_view command,
std::string_view cwd,
std::chrono::milliseconds deadline,
bool* timed_out);
// ─── A shell command mcpp owns for longer than one call (#496) ───────────
//
// `run_shell_deadline` owns its child for the length of the call. A project
// `[hooks] during_build` command is owned for the length of the BUILD, so it
// is started here, polled while the build runs, and stopped afterwards.
//
// The handle is opaque and carries whichever platform's identity is real: a
// process GROUP on POSIX, a job object on Windows. Neither is a pid, and that
// is deliberate — the command is user-authored shell, so the thing that must
// die is a tree, not a process.
struct BackgroundCommand {
bool ok = false;
long long group = 0; // POSIX: process-group id
unsigned long long job = 0; // Windows: job object
unsigned long long process = 0; // Windows: the child
};
// `inheritStdio == false` discards the child's output. That is the right
// default for anything running alongside the build: its writes would otherwise
// interleave into the middle of a compiler diagnostic.
BackgroundCommand start_shell_background(std::string_view command,
std::string_view cwd,
bool inheritStdio);
// True while it is still up. When it has exited and `exitCode` is given, the
// code is written there — "the player finished the track" and "the command
// does not exist" are the same event to a poller that only answers yes/no, and
// the `loop` supervisor has to tell them apart.
bool background_running(const BackgroundCommand& child, int* exitCode = nullptr);
// Asks, waits `grace`, then takes the tree.
void stop_background(const BackgroundCommand& child,
std::chrono::milliseconds grace);
// Ctrl-C. Registering the child means an interrupted build does not leave it
// running — which, for the case this exists for, is a background player the
// user can no longer name. Only one command is guarded at a time; a build owns
// at most one.
void guard_background_on_signal(const BackgroundCommand& child);
void clear_background_guard(const BackgroundCommand& child);
// `spawn_error`: run_exec's contract; with it null a refused spawn is
// formatted into `output`, as capture_exec does.
RunResult capture_exec_deadline(
const std::vector<std::string>& argv,
const std::vector<std::pair<std::string, std::string>>& extraEnv,
std::chrono::milliseconds deadline,
bool* timed_out,
std::string_view cwd = {},
int* spawn_error = nullptr);
// Run `command` silently (discard stdout/stderr).
// On POSIX, stdin is automatically redirected from /dev/null.
int run_silent(std::string_view command);
// Run `command`, stream stdout line-by-line via callback.
// On POSIX, stdin is automatically redirected from /dev/null.
int run_streaming(std::string_view command,
std::function<void(std::string_view line)> on_line);
// Run `command`, passing stdout/stderr through to the terminal.
// Optionally captures stdout into `output` if non-null.
// Returns a platform-normalized exit code (WEXITSTATUS on POSIX).
int run_passthrough(std::string_view command,
std::string* output = nullptr);
// Extract a platform-normalized exit code from a raw system()/pclose()
// return value. Windows returns the exit code directly; POSIX returns
// a wait-status word requiring WIFEXITED/WEXITSTATUS unwrapping.
int extract_exit_code(int raw_status);
// ─── Windows command-line shaping (host-independent, for testing) ─────────
//
// `cmd.exe /c <string>` applies a quote rule that silently mangles most
// command lines (`cmd /?`, /C section): unless the whole string is exactly
// one quoted executable name, cmd removes the FIRST character and the LAST
// quote character, then runs the remainder. A correctly quoted line like
//
// "C:\Program Files\gcc\g++.exe" -c "main.cpp"
//
// therefore arrives as
//
// C:\Program Files\gcc\g++.exe" -c "main.cpp
//
// The fix is to hand cmd an outer pair to consume. These two functions build
// exactly that shape and are compiled on every platform so the rule can be
// unit-tested from Linux/macOS — the Windows branch below is otherwise
// unreachable in every environment mcpp is normally developed on, which is
// how the unquoted-argv[0] bug survived.
std::string windows_command_from_argv(const std::vector<std::string>& argv);
std::string windows_wrap_for_cmd_c(std::string_view cmd);
// The command line that runs a USER-AUTHORED shell command through cmd.exe.
//
// ⚠️ NOT `windows_command_from_argv({"cmd.exe", "/d", "/s", "/c", command})`.
// That shape is for a program plus its argv, where CreateProcess's parsing is
// what has to be satisfied. cmd.exe is not parsed that way: its switches must
// arrive BARE (quoted, they are no longer switches), and the command tail is
// governed by the /C quote rule above rather than by argv quoting — so an
// argv-quoted command arrives carrying a pair cmd does not consume. That is
// #425 one layer up, and it is why this is its own shape:
//
// cmd.exe /d /s /c "<command>"
//
// /s makes the rule unconditional (strip exactly the outer pair), so the
// command reaches cmd verbatim no matter how many quotes it contains; /d skips
// AutoRun so a user's registry-installed shell hook cannot alter it.
std::string windows_shell_command_line(std::string_view command);
} // namespace mcpp::platform::process
// ─── Implementation ──────────────────────────────────────────────────────
namespace mcpp::platform::process {
// Host-independent (see the declarations): always the Windows shape.
std::string windows_command_from_argv(const std::vector<std::string>& argv) {
if (argv.empty()) return "";
std::string cmd = mcpp::platform::shell::quote_windows(argv[0]);
for (std::size_t i = 1; i < argv.size(); ++i) {
cmd += ' ';
cmd += mcpp::platform::shell::quote_windows(argv[i]);
}
return cmd;
}
std::string windows_wrap_for_cmd_c(std::string_view cmd) {
return "\"" + std::string(cmd) + "\"";
}
std::string windows_shell_command_line(std::string_view command) {
// One derivation for the outer pair: the same wrap the /c rule above is
// written against.
return "cmd.exe /d /s /c " + windows_wrap_for_cmd_c(command);
}
namespace {
// Append a non-interactive stdin redirect to prevent child processes from
// blocking on terminal input.
// - POSIX: "< /dev/null" — fixes macOS xcrun / xcode-select hangs.
// - Windows: "<NUL" — fixes xlings / xim / curl / git hangs on
// first-run toolchain install (user otherwise
// had to press Enter repeatedly to advance).
// `cmd.exe` accepts `<NUL` as a redirect for an immediately-EOF stdin.
std::string seal_stdin(std::string_view cmd) {
#if defined(_WIN32)
return std::string(cmd) + " <NUL";
#else
return std::string(cmd) + " </dev/null";
#endif
}
// Everything that reaches _popen / std::system on Windows is run by
// `cmd.exe /c <string>`, and cmd applies a quote rule that mangles any
// command line carrying more than one pair of quotes (`cmd /?`, the /C
// section): unless the whole string is exactly one quoted executable name,
// cmd strips the FIRST character and the LAST quote character and runs what
// is left. So
//
// "C:\Program Files\gcc\g++.exe" -c "main.cpp"
//
// becomes
//
// C:\Program Files\gcc\g++.exe" -c "main.cpp
//
// which is why command_from_argv used to leave argv[0] unquoted — the
// program path then survived, at the cost of breaking as soon as it
// contained a space, which every default install path does
// (`C:\Program Files\...`, or any user whose account name has a space).
//
// The documented fix is to give cmd an outer pair to eat, so the inner
// quoting arrives intact. Applied at the single point where a command
// string becomes a child process, so no caller has to remember it, and the
// redirects appended by seal_stdin / silent_redirect stay inside the wrap
// where cmd still parses them after stripping.
std::string wrap_for_cmd_c(std::string_view cmd) {
#if defined(_WIN32)
return windows_wrap_for_cmd_c(cmd);
#else
return std::string(cmd);
#endif
}
// Seal stdin AND wrap. Kept separate from wrap_for_cmd_c because run_exec
// deliberately inherits stdio — `mcpp run` hands the terminal to the program
// being run, and sealing its stdin would break every interactive one.
std::string finalize_shell_command(std::string_view cmd) {
return wrap_for_cmd_c(seal_stdin(cmd));
}
int normalize_exit_code(int rc) {
#if defined(_WIN32)
return rc;
#else
if (WIFEXITED(rc))
return WEXITSTATUS(rc);
// Shell convention for signaled children: 128 + signal number. The raw
// wait-status word only *happens* to look right when the core-dump bit
// is set (SIGSEGV+core → 0x8B = 139); without it a SIGTERM death would
// surface as "exit 15" and be indistinguishable from a normal exit code.
if (WIFSIGNALED(rc))
return 128 + WTERMSIG(rc);
return rc;
#endif
}
// The one sentence every launcher prints for a refused spawn. Platform-neutral
// on purpose: the bounded launchers on both platforms now hand their spawn
// error up (DeadlineRun::spawn_error), and the wrappers that receive it are
// compiled everywhere. `error` is an errno on POSIX and a GetLastError() value
// on Windows; the category below renders each in its own vocabulary.
std::string spawn_failure(std::string_view program, int error) {
#if defined(_WIN32)
return std::format("CreateProcess('{}') failed (error {}): {}\n",
program, error, std::system_category().message(error));
#else
return std::format("posix_spawnp('{}') failed (error {}): {}\n",
program, error, std::generic_category().message(error));
#endif
}
#if defined(__linux__) || defined(__APPLE__)
// Portable accessor for the host environment block. On Apple, `environ` is
// only linkable from executables (not dylibs), so _NSGetEnviron() is the
// sanctioned spelling; Linux keeps the plain `environ` symbol.
char** host_environ() {
#if defined(__APPLE__)
return *::_NSGetEnviron();
#else
return environ;
#endif
}
// An outer `mcpp run`/`mcpp test` points LD_LIBRARY_PATH at mcpp's private
// glibc payload so ITS child (a sandbox-linked user binary) can load. When
// that child spawns mcpp again (e.g. a course provider driving `mcpp test`),
// the same value would flow on into the inner mcpp's own children — and the
// sandbox ninja/gcc (host-glibc binaries) then resolve a MISMATCHED libc and
// segfault inside the dynamic linker before main (trace signature: a bare
// `__vdso_time` line). Strip exactly the private-glibc payload entries from
// inherited loader paths: user-supplied entries survive, and an `extra`
// override (the correct per-child value) always wins over the inherited var.
//
// The predicate itself lives in mcpp.platform.env, because the OTHER half of
// this guarantee is there: a composed override (dirs + inherited tail) arrives
// here as `extra` and therefore bypasses the sanitation below, so
// prepend_path_list has to sanitize the tail it carries.
using mcpp::platform::env::strip_private_glibc;
// Build a child environment block = the current environ with `extra` overrides
// applied. Returned vector owns the strings; the caller derives a NUL-terminated
// char* array from it. Built in the PARENT so the child env never requires a
// post-fork setenv and mcpp's own environment is never touched.
std::vector<std::string> merged_environ(
const std::vector<std::pair<std::string, std::string>>& extra)
{
std::vector<std::string> out;
std::set<std::string> overridden;
for (auto& [k, v] : extra) { out.push_back(k + "=" + v); overridden.insert(k); }
for (char** e = host_environ(); e && *e; ++e) {
std::string_view entry(*e);
auto eq = entry.find('=');
std::string key(eq == std::string_view::npos ? entry : entry.substr(0, eq));
if (overridden.contains(key)) continue;
if (eq != std::string_view::npos
&& (key == "LD_LIBRARY_PATH" || key == "DYLD_LIBRARY_PATH")) {
auto cleaned = strip_private_glibc(entry.substr(eq + 1));
if (!cleaned.empty()) out.push_back(key + "=" + cleaned);
continue; // nothing legitimate left → drop the var entirely
}
out.emplace_back(entry);
}
return out;
}
#else
// Build a shell command line from an argv vector (Windows + residual non-POSIX
// fallback only; Linux/macOS exec directly, #248). EVERY token is shell-quoted,
// including the program — a payload under `C:\Program Files\...` or a home
// directory with a space in the user name is otherwise cut at the first space
// and reported as `'C:\Program' is not recognized`.
//
// argv[0] used to be left raw here to survive cmd.exe's /c quote stripping.
// That traded one bug for another; finalize_shell_command now feeds cmd the
// outer quote pair it insists on eating, so the quoting below arrives intact.
std::string command_from_argv(const std::vector<std::string>& argv) {
#if defined(_WIN32)
// One derivation: the tested, host-independent shaper above.
return windows_command_from_argv(argv);
#else
if (argv.empty()) return "";
std::string cmd = mcpp::platform::shell::quote(argv[0]);
for (std::size_t i = 1; i < argv.size(); ++i) {
cmd += ' ';
cmd += mcpp::platform::shell::quote(argv[i]);
}
return cmd;
#endif
}
#endif
} // namespace
int extract_exit_code(int raw_status) {
return normalize_exit_code(raw_status);
}
RunResult capture(std::string_view command) {
auto cmd = finalize_shell_command(command);
RunResult result;
std::FILE* fp = ::popen(cmd.c_str(), "r");
if (!fp) {
result.exit_code = -1;
return result;
}
std::array<char, 4096> buf{};
while (std::fgets(buf.data(), static_cast<int>(buf.size()), fp) != nullptr)
result.output += buf.data();
result.exit_code = normalize_exit_code(::pclose(fp));
return result;
}
RunResult capture_host_tool(std::string_view command) {
auto key = mcpp::platform::env::host_tool_runtime_library_path_key();
std::optional<mcpp::platform::env::ScopedEnv> runtime_env;
if (!key.empty())
runtime_env.emplace(key, std::nullopt);
return capture(command);
}
RunResult capture_with_env(
std::string_view command,
const std::vector<std::pair<std::string, std::string>>& env)
{
#if defined(_WIN32)
for (auto& [k, v] : env)
_putenv_s(k.c_str(), v.c_str());
return capture(command);
#else
std::string prefixed;
for (auto& [k, v] : env) {
prefixed += k;
prefixed += '=';
// Simple quoting for env values
prefixed += '\'';
for (char c : v) {
if (c == '\'') prefixed += "'\\''";
else prefixed += c;
}
prefixed += '\'';
prefixed += ' ';
}
prefixed += command;
return capture(prefixed);
#endif
}
int run_silent(std::string_view command) {
auto cmd = finalize_shell_command(command);
return normalize_exit_code(std::system(cmd.c_str()));
}
int run_streaming(std::string_view command,
std::function<void(std::string_view line)> on_line)
{
auto cmd = finalize_shell_command(command);
std::FILE* fp = ::popen(cmd.c_str(), "r");
if (!fp) return -1;
std::array<char, 16384> buf{};
std::string acc;
while (std::fgets(buf.data(), static_cast<int>(buf.size()), fp) != nullptr) {
acc += buf.data();
std::size_t pos;
while ((pos = acc.find('\n')) != std::string::npos) {
if (on_line) {
auto line = std::string_view{acc}.substr(0, pos);
while (!line.empty() && line.back() == '\r')
line.remove_suffix(1);
on_line(line);
}
acc.erase(0, pos + 1);
}
}
if (!acc.empty() && on_line) {
std::string_view line{acc};
while (!line.empty() && line.back() == '\r')
line.remove_suffix(1);
if (!line.empty()) on_line(line);
}
return normalize_exit_code(::pclose(fp));
}
int run_passthrough(std::string_view command, std::string* output) {
auto cmd = finalize_shell_command(command);
std::FILE* fp = ::popen(cmd.c_str(), "r");
if (!fp) return -1;
std::array<char, 8192> buf{};
while (std::fgets(buf.data(), static_cast<int>(buf.size()), fp) != nullptr) {
if (output) *output += buf.data();
std::fputs(buf.data(), stdout);
}
return normalize_exit_code(::pclose(fp));
}
// run_exec / capture_exec are split by platform on purpose:
//
// Linux /
// macOS — DIRECT exec via posix_spawn (unified in #248). The extra env goes
// into the child's envp ONLY (merged_environ); it never enters
// mcpp's own environment nor a host /bin/sh. On Linux that is the
// exact fix for the newer-glibc `sh:` crash; on macOS the old shell
// path built `KEY='v' cd <cwd> && prog`, where POSIX binds the env
// assignments to `cd` alone — the real program (build.mcpp, the
// only env+cwd call site) received NO extra env and lost the whole
// MCPP_* contract. Direct exec also drops the shell quoting /
// signal / injection surface entirely. cwd is applied via
// posix_spawn_file_actions_addchdir_np, available on both glibc
// and macOS 10.15+ (mcpp's floor is macOS 14).
// Windows — KEEP the proven std::system shell path. The env-binding hazard
// does not exist here (env goes through _putenv_s, not a prefix),
// so we deliberately do not swap the launch primitive on a platform
// we cannot iterate on locally.
//
// TODO(launcher-unify): Windows is the remaining exception; if it ever needs
// child-only env isolation, move it onto a CreateProcess/_spawn equivalent and
// delete the residual shell branch below.
int run_exec(const std::vector<std::string>& argv,
const std::vector<std::pair<std::string, std::string>>& extraEnv,
int* spawn_error)
{
if (spawn_error) *spawn_error = 0;
if (argv.empty()) return 127;
#if defined(__linux__) || defined(__APPLE__)
auto envStore = merged_environ(extraEnv);
std::vector<char*> envp;
for (auto& s : envStore) envp.push_back(s.data());
envp.push_back(nullptr);
std::vector<char*> cargv;
for (auto& a : argv) cargv.push_back(const_cast<char*>(a.c_str()));
cargv.push_back(nullptr);
// THE CHILD GETS ITS OWN PROCESS GROUP, AND mcpp KILLS THAT GROUP IF IT IS
// ITSELF KILLED.
//
// Without this, terminating mcpp leaves the child running. Measured: every
// `timeout`-terminated `mcpp run` left an orphaned ninja spinning at 100%
// of a core, and one of them outlived the removal of the entire sandbox it
// belonged to — its working directory read `(deleted)` and it was still
// burning a core half an hour later. Any CI that wraps mcpp in `timeout`
// leaks a busy core per timeout.
//
// The group rather than the pid, because the child starts children of its
// own: killing ninja alone would leave its compilers behind.
//
// A signal is not enough on its own, which is why the guard sends SIGKILL.
// ninja records a signal in a flag and acts on it where it waits for a
// subprocess; a ninja with no command running never reaches that check, so
// a polite signal is recorded and never obeyed.
posix_spawnattr_t attr;
::posix_spawnattr_init(&attr);
::posix_spawnattr_setpgroup(&attr, 0); // 0 ⇒ new group, id == pid
::posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETPGROUP);
pid_t pid = 0;
int sp = ::posix_spawnp(&pid, cargv[0], nullptr, &attr, cargv.data(), envp.data());
::posix_spawnattr_destroy(&attr);
if (sp != 0) {
// Reported once: by the caller when it asked for the errno, here
// otherwise. Never dropped — the errno in hand at this line is the
// whole difference between "Exec format error" and a blank line.
if (spawn_error) *spawn_error = sp;
else std::fputs(spawn_failure(argv.front(), sp).c_str(), stderr);
return 127;
}
mcpp::platform::unixproc::guard_group_on_signal(pid);
int status = 0;
while (::waitpid(pid, &status, 0) < 0) { /* EINTR retry */ }
mcpp::platform::unixproc::unguard_group(pid);
return normalize_exit_code(status);
#else
// THE SAME OWNERSHIP AS THE POSIX BRANCH, EXPRESSED IN THIS PLATFORM'S TERMS.
//
// `std::system` gave the child away: it runs through a cmd.exe mcpp does not
// hold a handle to, so terminating mcpp left the tree running exactly as the
// POSIX branch did before its process group. A job object with
// JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE is the equivalent unit — it takes the
// whole tree, which matters here for the same reason the group does there:
// the child starts compilers of its own.
//
// The command line is built by the same `windows_shell_command_line` the
// rest of this file uses, so the cmd.exe quoting rule has ONE derivation.
// Re-deriving it here is how `/d /s /c` loses an argument.
std::string prefix = mcpp::platform::env::build_env_prefix(extraEnv);
// wrap only — run_exec inherits stdio on purpose (see finalize_shell_command).
std::string cmd = windows_shell_command_line(prefix + command_from_argv(argv));
auto child = mcpp::platform::winproc::spawn_background(cmd.c_str(), nullptr, 1);
if (!child.ok) {
const int refused = static_cast<int>(child.refused);
if (spawn_error) *spawn_error = refused;
else std::fputs(spawn_failure(argv.front(), refused).c_str(), stderr);
return 127;
}
mcpp::platform::winproc::guard_job_on_signal(child.job);
int code = 127;
mcpp::platform::winproc::wait_background(child.process, &code);
mcpp::platform::winproc::unguard_job(child.job);
// Closes both handles; the child has already exited, so this is cleanup
// rather than a kill.
mcpp::platform::winproc::background_stop(child.job, child.process, 0);
return code;
#endif
}
RunResult capture_exec(
const std::vector<std::string>& argv,
const std::vector<std::pair<std::string, std::string>>& extraEnv,
std::string_view cwd,
int* spawn_error)
{
RunResult result;
if (spawn_error) *spawn_error = 0;
if (argv.empty()) { result.exit_code = 127; return result; }
#if defined(__linux__) || defined(__APPLE__)
// posix_spawn + a pipe; stdout and stderr both go to the pipe so the
// captured text is combined (replaces the old `2>&1`).
int fds[2];
if (::pipe(fds) != 0) { result.exit_code = 127; return result; }
auto envStore = merged_environ(extraEnv);
std::vector<char*> envp;
for (auto& s : envStore) envp.push_back(s.data());
envp.push_back(nullptr);
std::vector<char*> cargv;
for (auto& a : argv) cargv.push_back(const_cast<char*>(a.c_str()));
cargv.push_back(nullptr);
posix_spawn_file_actions_t fa;
::posix_spawn_file_actions_init(&fa);
// Run the child in `cwd` when requested (e.g. build.mcpp, whose relative
// file writes must land in the project root regardless of mcpp's own cwd).
std::string cwdStore(cwd);
if (!cwdStore.empty())
::posix_spawn_file_actions_addchdir_np(&fa, cwdStore.c_str());
::posix_spawn_file_actions_adddup2(&fa, fds[1], 1); // stdout → pipe
::posix_spawn_file_actions_adddup2(&fa, fds[1], 2); // stderr → same pipe
::posix_spawn_file_actions_addclose(&fa, fds[0]);
::posix_spawn_file_actions_addclose(&fa, fds[1]);
// Owned exactly as `run_exec`'s child is, and for the same reason: this is
// the launcher a FULL build uses, so a `mcpp build` interrupted here is the
// common case rather than the rare one. Fixing only `run_exec` left the
// orphan in place — measured, with the two launchers giving opposite
// answers to the same test.
posix_spawnattr_t attr;
::posix_spawnattr_init(&attr);
::posix_spawnattr_setpgroup(&attr, 0);
::posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETPGROUP);
pid_t pid = 0;
int sp = ::posix_spawnp(&pid, cargv[0], &fa, &attr, cargv.data(), envp.data());
::posix_spawnattr_destroy(&attr);
::posix_spawn_file_actions_destroy(&fa);
::close(fds[1]);
if (sp == 0) mcpp::platform::unixproc::guard_group_on_signal(pid);
if (sp != 0) {
::close(fds[0]);
result.exit_code = 127;
if (spawn_error) *spawn_error = sp;
else result.output = spawn_failure(argv.front(), sp);
return result;
}
std::array<char, 4096> buf{};
ssize_t n;
while ((n = ::read(fds[0], buf.data(), buf.size())) > 0)
result.output.append(buf.data(), static_cast<size_t>(n));
::close(fds[0]);
int status = 0;
while (::waitpid(pid, &status, 0) < 0) { /* EINTR retry */ }
mcpp::platform::unixproc::unguard_group(pid);
result.exit_code = normalize_exit_code(status);
return result;
#else
std::string cmd = command_from_argv(argv) + " 2>&1";
if (!cwd.empty()) {
#if defined(_WIN32)
// cmd.exe `cd` without /d does not switch drives — a project on a
// different drive than mcpp's own cwd would run the child (the
// build.mcpp contract's only cwd consumer) in the wrong directory.
cmd = "cd /d " + mcpp::platform::shell::quote(cwd) + " && " + cmd;
#else
cmd = "cd " + mcpp::platform::shell::quote(cwd) + " && " + cmd;
#endif
}
return capture_with_env(cmd, extraEnv);
#endif
}
// ─── The ONE place the platform question is asked for a bounded run ────────
//
// Both launchers answer the same contract behind a `std`-free interface (see
// either module for the BMI corruption that forced that), so everything
// platform-specific about a bounded child is this dispatch plus the two
// implementations — instead of the branches that used to be spread through
// both functions below, with the Windows half of them a silent no-op.
//
// The two calls differ in ONE way, and it is a real difference rather than an
// abstraction leak: POSIX names a program with an argv array, Windows with a
// single quoted command line. Flattening that would move the quoting rules
// somewhere they could not be unit-tested — they are tested right here, via
// windows_command_from_argv.
struct BoundedOutcome {
bool supported = false;
int exit_code = 0;
bool timed_out = false;
int spawn_error = 0; // see DeadlineRun::spawn_error in either launcher
std::string output;
};
// `capture == false` runs the child on the caller's stdio: live output, and a
// real terminal for anything that checks. `run_exec_deadline` needs that; the
// capturing variants need the pipe.
// `windowsCommandLine` overrides what the Windows branch launches. Empty (the
// normal case) means "derive it from argv". A shell command is the one caller
// that must NOT be derived that way — see windows_shell_command_line — and the
// POSIX branch is unaffected either way, because it never flattens argv.
BoundedOutcome dispatch_bounded(
const std::vector<std::string>& argv,
const std::vector<std::pair<std::string, std::string>>& extraEnv,
std::string_view cwd,
std::chrono::milliseconds deadline,
bool capture,
std::string_view windowsCommandLine = {})
{
BoundedOutcome outcome;
std::vector<std::string> envStore;
envStore.reserve(extraEnv.size());
for (auto const& [k, v] : extraEnv) envStore.push_back(k + "=" + v);
std::vector<const char*> envPtrs;
envPtrs.reserve(envStore.size());
for (auto const& e : envStore) envPtrs.push_back(e.c_str());
const char* const* envArg = envPtrs.empty() ? nullptr : envPtrs.data();
const auto envCount = static_cast<unsigned long>(envPtrs.size());
std::string cwdStore(cwd);
const char* cwdArg = cwdStore.empty() ? nullptr : cwdStore.c_str();
const auto ms = static_cast<long long>(deadline.count());
// One sink for both, appending into the outcome's own buffer. Null when the
// caller wants the child on its own stdio.
using Sink = void (*)(void*, const char*, unsigned long);
const Sink sink = capture
? +[](void* ctx, const char* data, unsigned long len) {
static_cast<std::string*>(ctx)->append(data, len);
}
: nullptr;
if constexpr (mcpp::platform::is_windows) {
const auto cmd = windowsCommandLine.empty()
? windows_command_from_argv(argv)
: std::string(windowsCommandLine);
auto r = mcpp::platform::winproc::capture_with_deadline(
cmd.c_str(), envArg, envCount, cwdArg, ms, sink, &outcome.output);
outcome.supported = r.supported;
outcome.exit_code = r.exit_code;
outcome.timed_out = r.timed_out;
outcome.spawn_error = r.spawn_error;
} else {
std::vector<const char*> argvPtrs;
argvPtrs.reserve(argv.size());
for (auto const& a : argv) argvPtrs.push_back(a.c_str());
auto r = mcpp::platform::unixproc::capture_with_deadline(
argvPtrs.data(), static_cast<unsigned long>(argvPtrs.size()),
envArg, envCount, cwdArg, ms, sink, &outcome.output);
outcome.supported = r.supported;
outcome.exit_code = r.exit_code;
outcome.timed_out = r.timed_out;
outcome.spawn_error = r.spawn_error;
}
return outcome;
}
int run_exec_deadline(const std::vector<std::string>& argv,
const std::vector<std::pair<std::string, std::string>>& extraEnv,
std::chrono::milliseconds deadline,
bool* timed_out,
int* spawn_error)
{
if (timed_out) *timed_out = false;
if (spawn_error) *spawn_error = 0;
if (deadline.count() <= 0) return run_exec(argv, extraEnv, spawn_error);
if (argv.empty()) return 127;
// capture=false: identical stdio behaviour to `run_exec` — the child writes
// straight to our terminal as it goes. `mcpp test`'s non-JSON path runs
// test binaries through here, and buffering their output until exit would
// undo the observability work that path exists for (and would hide gtest's
// colors by making its stdout a pipe).
auto r = dispatch_bounded(argv, extraEnv, {}, deadline, /*capture=*/false);
if (!r.supported) {
// Attempted and refused: the errno is in hand, so type it or report
// it here. Spawning again through run_exec — what this did before —
// paid for a second refusal and threw the first errno away (#544).
if (r.spawn_error != 0) {
if (spawn_error) *spawn_error = r.spawn_error;
else std::fputs(spawn_failure(argv.front(), r.spawn_error).c_str(), stderr);
return 127;
}
return run_exec(argv, extraEnv, spawn_error); // no bounded launcher here
}
if (timed_out) *timed_out = r.timed_out;
return r.exit_code;
}
int run_shell_deadline(std::string_view command,
std::string_view cwd,
std::chrono::milliseconds deadline,
bool* timed_out)
{
if (timed_out) *timed_out = false;
if (command.empty() || deadline.count() <= 0) return 127;
// argv is what the POSIX branch launches; the Windows branch takes the
// shaped command line instead. Both are built here so neither platform's
// spelling can drift into a launcher that does not use it.
const std::vector<std::string> argv{"/bin/sh", "-c", std::string(command)};
auto r = dispatch_bounded(argv, {}, cwd, deadline, /*capture=*/false,
windows_shell_command_line(command));
// No fallback to the unbounded launcher here, unlike run_exec_deadline: a
// hook's deadline and its working directory are both part of what the
// caller asked for, and the unbounded path can honour neither.
if (!r.supported) return 127;
if (timed_out) *timed_out = r.timed_out;
return r.exit_code;
}
// The same split as dispatch_bounded, for the same reason: POSIX names a
// program with an argv array, Windows with a single command line. Both
// spellings are built here so neither can drift into a launcher that does not
// use it.
BackgroundCommand start_shell_background(std::string_view command,
std::string_view cwd,
bool inheritStdio)
{
BackgroundCommand out;
if (command.empty()) return out;
const std::string cwdStore(cwd);
const char* cwdArg = cwdStore.empty() ? nullptr : cwdStore.c_str();
if constexpr (mcpp::platform::is_windows) {
const auto line = windows_shell_command_line(command);
auto r = mcpp::platform::winproc::spawn_background(
line.c_str(), cwdArg, inheritStdio ? 1 : 0);
out.ok = r.ok;
out.job = r.job;
out.process = r.process;
} else {
const std::string cmdStore(command);
const char* argv[] = {"/bin/sh", "-c", cmdStore.c_str()};
auto r = mcpp::platform::unixproc::spawn_background(
argv, 3, cwdArg, inheritStdio ? 1 : 0);
out.ok = r.ok;
out.group = r.group;
}
return out;
}
bool background_running(const BackgroundCommand& child, int* exitCode) {
if (!child.ok) return false;
if constexpr (mcpp::platform::is_windows)
return mcpp::platform::winproc::background_running(child.process,
exitCode) == 1;
else
return mcpp::platform::unixproc::background_running(child.group,
exitCode) == 1;
}
void stop_background(const BackgroundCommand& child,
std::chrono::milliseconds grace)
{
if (!child.ok) return;
if constexpr (mcpp::platform::is_windows)
mcpp::platform::winproc::background_stop(child.job, child.process,
grace.count());
else
mcpp::platform::unixproc::background_stop(child.group, grace.count());
}
void guard_background_on_signal(const BackgroundCommand& child) {
if (!child.ok) return;
if constexpr (mcpp::platform::is_windows)
mcpp::platform::winproc::guard_job_on_signal(child.job);
else
mcpp::platform::unixproc::guard_group_on_signal(child.group);
}
// Releases THIS child, not the guard as a whole: a build's ninja is guarded at
// the same time as a spanning hook, and disarming everything when either
// finishes would leave the other able to outlive mcpp.
void clear_background_guard(const BackgroundCommand& child) {
if constexpr (mcpp::platform::is_windows)
mcpp::platform::winproc::unguard_job(child.job);
else
mcpp::platform::unixproc::unguard_group(child.group);
}
RunResult capture_exec_deadline(
const std::vector<std::string>& argv,
const std::vector<std::pair<std::string, std::string>>& extraEnv,
std::chrono::milliseconds deadline,
bool* timed_out,
std::string_view cwd,
int* spawn_error)
{
if (timed_out) *timed_out = false;
if (spawn_error) *spawn_error = 0;
if (deadline.count() <= 0) return capture_exec(argv, extraEnv, cwd, spawn_error);
RunResult result;
if (argv.empty()) { result.exit_code = 127; return result; }
auto r = dispatch_bounded(argv, extraEnv, cwd, deadline, /*capture=*/true);
// `supported == false` means the child COULD NOT BE SPAWNED — not that it
// ran and failed. Reporting those the same way would hide a launcher
// problem behind a child's exit code. When the launcher attempted the
// spawn, its errno is the diagnostic and there is nothing to retry; only
// a build with no bounded launcher at all falls back to the untimed path.
if (!r.supported) {
if (r.spawn_error != 0) {
result.exit_code = 127;
if (spawn_error) *spawn_error = r.spawn_error;
else result.output = spawn_failure(argv.front(), r.spawn_error);
return result;
}
return capture_exec(argv, extraEnv, cwd, spawn_error);
}
result.exit_code = r.exit_code;
result.output = std::move(r.output);
if (timed_out) *timed_out = r.timed_out;
return result;
}