-
Notifications
You must be signed in to change notification settings - Fork 296
/
Copy pathsystem.process.cpp
1893 lines (1678 loc) · 68.4 KB
/
system.process.cpp
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
#include <vcpkg/base/system-headers.h>
#include <vcpkg/base/checks.h>
#include <vcpkg/base/chrono.h>
#include <vcpkg/base/files.h>
#include <vcpkg/base/parallel-algorithms.h>
#include <vcpkg/base/parse.h>
#include <vcpkg/base/strings.h>
#include <vcpkg/base/system.debug.h>
#include <vcpkg/base/system.h>
#include <vcpkg/base/system.process.h>
#include <vcpkg/base/util.h>
#include <map>
#include <set>
#if defined(__APPLE__)
extern char** environ;
#include <mach-o/dyld.h>
#endif
#if defined(__FreeBSD__)
extern char** environ;
#include <sys/sysctl.h>
#include <sys/wait.h>
#endif
#if defined(_WIN32)
#include <Psapi.h>
#include <TlHelp32.h>
#include <sddl.h>
#pragma comment(lib, "Advapi32")
#else
#include <fcntl.h>
#include <poll.h>
#include <spawn.h>
#include <sys/wait.h>
#endif
namespace
{
using namespace vcpkg;
#if defined(_WIN32)
using error_value_type = unsigned long;
#else // ^^^ _WIN32 // !_WIN32 vvv
using error_value_type = int;
#endif // ^^^ !_WIN32
LocalizedString format_system_error_message(StringLiteral api_name, error_value_type error_value)
{
return msg::format_error(msgSystemApiErrorMessage,
msg::system_api = api_name,
msg::exit_code = error_value,
msg::error_msg = std::system_category().message(static_cast<int>(error_value)));
}
static std::atomic_int32_t debug_id_counter{1000};
#if defined(_WIN32)
struct CtrlCStateMachine
{
CtrlCStateMachine() : m_number_of_external_processes(0), m_global_job(NULL), m_in_interactive(0) { }
void transition_to_spawn_process() noexcept
{
int cur = 0;
while (!m_number_of_external_processes.compare_exchange_strong(cur, cur + 1))
{
if (cur < 0)
{
// Ctrl-C was hit and is asynchronously executing on another thread.
// Some other processes are outstanding.
// Sleep forever -- the other process will complete and exit the program
while (true)
{
std::this_thread::sleep_for(std::chrono::seconds(10));
msg::println(msgWaitingForChildrenToExit);
}
}
}
}
void transition_from_spawn_process() noexcept
{
auto previous = m_number_of_external_processes.fetch_add(-1);
if (previous == INT_MIN + 1)
{
// Ctrl-C was hit while blocked on the child process
// This is the last external process to complete
// Therefore, exit
Checks::final_cleanup_and_exit(1);
}
else if (previous < 0)
{
// Ctrl-C was hit while blocked on the child process
// Some other processes are outstanding.
// Sleep forever -- the other process will complete and exit the program
while (true)
{
std::this_thread::sleep_for(std::chrono::seconds(10));
msg::println(msgWaitingForChildrenToExit);
}
}
}
void transition_handle_ctrl_c() noexcept
{
int old_value = 0;
while (!m_number_of_external_processes.compare_exchange_strong(old_value, old_value + INT_MIN))
{
if (old_value < 0)
{
// Repeat calls to Ctrl-C -- a previous one succeeded.
return;
}
}
if (old_value == 0)
{
// Not currently blocked on a child process
Checks::final_cleanup_and_exit(1);
}
else
{
// We are currently blocked on a child process.
// If none of the child processes are interactive, use the Job Object to terminate the tree.
if (m_in_interactive.load() == 0)
{
auto job = m_global_job.exchange(NULL);
if (job != NULL)
{
::CloseHandle(job);
}
}
}
}
void initialize_job()
{
m_global_job = CreateJobObjectW(NULL, NULL);
if (m_global_job != NULL)
{
JOBOBJECT_EXTENDED_LIMIT_INFORMATION info = {};
info.BasicLimitInformation.LimitFlags =
JOB_OBJECT_LIMIT_BREAKAWAY_OK | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
::SetInformationJobObject(m_global_job, JobObjectExtendedLimitInformation, &info, sizeof(info));
::AssignProcessToJobObject(m_global_job, ::GetCurrentProcess());
}
}
void enter_interactive() { ++m_in_interactive; }
void exit_interactive() { --m_in_interactive; }
private:
std::atomic<int> m_number_of_external_processes;
std::atomic<HANDLE> m_global_job;
std::atomic<int> m_in_interactive;
};
static CtrlCStateMachine g_ctrl_c_state;
struct SpawnProcessGuard
{
SpawnProcessGuard() { g_ctrl_c_state.transition_to_spawn_process(); }
SpawnProcessGuard(const SpawnProcessGuard&) = delete;
SpawnProcessGuard& operator=(const SpawnProcessGuard&) = delete;
~SpawnProcessGuard() { g_ctrl_c_state.transition_from_spawn_process(); }
};
#endif // ^^^ _WIN32
} // unnamed namespace
namespace vcpkg
{
void append_shell_escaped(std::string& target, StringView content)
{
if (Strings::find_first_of(content, " \t\n\r\"\\`$,;&^|'()") != content.end())
{
// TODO: improve this to properly handle all escaping
#if _WIN32
// On Windows, `\`s before a double-quote must be doubled. Inner double-quotes must be escaped.
target.push_back('"');
size_t n_slashes = 0;
for (auto ch : content)
{
if (ch == '\\')
{
++n_slashes;
}
else if (ch == '"')
{
target.append(n_slashes + 1, '\\');
n_slashes = 0;
}
else
{
n_slashes = 0;
}
target.push_back(ch);
}
target.append(n_slashes, '\\');
target.push_back('"');
#else
// On non-Windows, `\` is the escape character and always requires doubling. Inner double-quotes must be
// escaped. Additionally, '`' and '$' must be escaped or they will retain their special meaning in the
// shell.
target.push_back('"');
for (auto ch : content)
{
if (ch == '\\' || ch == '"' || ch == '`' || ch == '$') target.push_back('\\');
target.push_back(ch);
}
target.push_back('"');
#endif
}
else
{
target.append(content.data(), content.size());
}
}
static std::atomic<uint64_t> g_subprocess_stats(0);
#if defined(_WIN32)
void initialize_global_job_object() { g_ctrl_c_state.initialize_job(); }
void enter_interactive_subprocess() { g_ctrl_c_state.enter_interactive(); }
void exit_interactive_subprocess() { g_ctrl_c_state.exit_interactive(); }
#endif
Path get_exe_path_of_current_process()
{
#if defined(_WIN32)
wchar_t buf[_MAX_PATH];
const int bytes = GetModuleFileNameW(nullptr, buf, _MAX_PATH);
if (bytes == 0) std::abort();
return Strings::to_utf8(buf, bytes);
#elif defined(__APPLE__)
static constexpr const uint32_t buff_size = 1024 * 32;
uint32_t size = buff_size;
char buf[buff_size] = {};
int result = _NSGetExecutablePath(buf, &size);
Checks::check_exit(VCPKG_LINE_INFO, result != -1, "Could not determine current executable path.");
std::unique_ptr<char> canonicalPath(realpath(buf, NULL));
Checks::check_exit(VCPKG_LINE_INFO, result != -1, "Could not determine current executable path.");
return canonicalPath.get();
#elif defined(__FreeBSD__)
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
char exePath[2048];
size_t len = sizeof(exePath);
auto rcode = sysctl(mib, 4, exePath, &len, nullptr, 0);
Checks::check_exit(VCPKG_LINE_INFO, rcode == 0, "Could not determine current executable path.");
Checks::check_exit(VCPKG_LINE_INFO, len > 0, "Could not determine current executable path.");
return Path(exePath, len - 1);
#elif defined(__OpenBSD__)
const char* progname = getprogname();
char resolved_path[PATH_MAX];
auto ret = realpath(progname, resolved_path);
Checks::check_exit(VCPKG_LINE_INFO, ret != nullptr, "Could not determine current executable path.");
return resolved_path;
#else /* LINUX */
char buf[1024 * 4] = {};
auto written = readlink("/proc/self/exe", buf, sizeof(buf));
Checks::check_exit(VCPKG_LINE_INFO, written != -1, "Could not determine current executable path.");
return Path(buf, written);
#endif
}
Optional<ProcessStat> try_parse_process_stat_file(const FileContents& contents)
{
ParserBase p(contents.content, contents.origin);
p.match_while(ParserBase::is_ascii_digit); // pid %d (ignored)
p.skip_whitespace();
p.require_character('(');
// From: https://man7.org/linux/man-pages/man5/procfs.5.html
//
// /proc/[pid]/stat
//
// (2) comm %s
// The filename of the executable, in parentheses.
// Strings longer than TASK_COMM_LEN (16) characters (including the terminating null byte) are silently
// truncated. This is visible whether or not the executable is swapped out.
const auto start = p.it().pointer_to_current();
const auto end = p.it().end();
size_t len = 0, last_seen = 0;
for (auto it = p.it(); len < 17 && it != end; ++len, ++it)
{
if (*it == ')') last_seen = len;
}
for (size_t i = 0; i < last_seen; ++i)
{
p.next();
}
p.require_character(')');
p.skip_whitespace();
p.next(); // state %c (ignored)
p.skip_whitespace();
auto ppid_str = p.match_while(ParserBase::is_ascii_digit);
auto maybe_ppid = Strings::strto<int>(ppid_str);
if (auto ppid = maybe_ppid.get())
{
return ProcessStat{
*ppid,
std::string(start, last_seen),
};
}
return nullopt;
}
} // namespace vcpkg
namespace
{
#if defined(_WIN32)
struct ToolHelpProcessSnapshot
{
ToolHelpProcessSnapshot() noexcept : snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) { }
ToolHelpProcessSnapshot(const ToolHelpProcessSnapshot&) = delete;
ToolHelpProcessSnapshot& operator=(const ToolHelpProcessSnapshot&) = delete;
~ToolHelpProcessSnapshot()
{
if (snapshot != INVALID_HANDLE_VALUE)
{
CloseHandle(snapshot);
}
}
explicit operator bool() const noexcept { return snapshot != INVALID_HANDLE_VALUE; }
BOOL Process32First(PPROCESSENTRY32W entry) const noexcept { return ::Process32FirstW(snapshot, entry); }
BOOL Process32Next(PPROCESSENTRY32W entry) const noexcept { return ::Process32NextW(snapshot, entry); }
private:
HANDLE snapshot;
};
#elif defined(__linux__)
Optional<ProcessStat> try_get_process_stat_by_pid(int pid)
{
auto filepath = fmt::format("/proc/{}/stat", pid);
auto maybe_contents = real_filesystem.try_read_contents(filepath);
if (auto contents = maybe_contents.get())
{
return try_parse_process_stat_file(*contents);
}
return nullopt;
}
#endif // ^^^ __linux__
} // unnamed namespace
namespace vcpkg
{
void get_parent_process_list(std::vector<std::string>& ret)
{
ret.clear();
#if defined(_WIN32)
// Enumerate all processes in the system snapshot.
std::map<DWORD, DWORD> pid_ppid_map;
std::map<DWORD, std::string> pid_exe_path_map;
std::set<DWORD> seen_pids;
PROCESSENTRY32W entry{};
entry.dwSize = sizeof(entry);
{
ToolHelpProcessSnapshot snapshot;
if (!snapshot)
{
return;
}
if (snapshot.Process32First(&entry))
{
do
{
pid_ppid_map.emplace(entry.th32ProcessID, entry.th32ParentProcessID);
pid_exe_path_map.emplace(entry.th32ProcessID, Strings::to_utf8(entry.szExeFile));
} while (snapshot.Process32Next(&entry));
}
} // destroy snapshot
// Find hierarchy of current process
for (DWORD next_parent = GetCurrentProcessId();;)
{
if (Util::Sets::contains(seen_pids, next_parent))
{
// parent graph loops, for example if a parent terminates and the PID is reused by a child launch
break;
}
seen_pids.insert(next_parent);
auto it = pid_ppid_map.find(next_parent);
if (it == pid_ppid_map.end())
{
break;
}
ret.push_back(pid_exe_path_map[it->first]);
next_parent = it->second;
}
#elif defined(__linux__)
std::set<int> seen_pids;
auto maybe_vcpkg_stat = try_get_process_stat_by_pid(getpid());
if (auto vcpkg_stat = maybe_vcpkg_stat.get())
{
for (auto next_parent = vcpkg_stat->ppid; next_parent != 0;)
{
if (Util::Sets::contains(seen_pids, next_parent))
{
// parent graph loops, for example if a parent terminates and the PID is reused by a child launch
break;
}
seen_pids.insert(next_parent);
auto maybe_next_parent_stat = try_get_process_stat_by_pid(next_parent);
if (auto next_parent_stat = maybe_next_parent_stat.get())
{
ret.push_back(next_parent_stat->executable_name);
next_parent = next_parent_stat->ppid;
}
else
{
break;
}
}
}
#endif
}
CMakeVariable::CMakeVariable(const StringView varname, const char* varvalue)
: s(format_cmake_variable(varname, varvalue))
{
}
CMakeVariable::CMakeVariable(const StringView varname, const std::string& varvalue)
: s(format_cmake_variable(varname, varvalue))
{
}
CMakeVariable::CMakeVariable(const StringView varname, StringLiteral varvalue)
: s(format_cmake_variable(varname, varvalue))
{
}
CMakeVariable::CMakeVariable(const StringView varname, const Path& varvalue)
: s(format_cmake_variable(varname, varvalue.generic_u8string()))
{
}
CMakeVariable::CMakeVariable(const std::string& var) : s(var) { }
std::string format_cmake_variable(StringView key, StringView value) { return fmt::format("-D{}={}", key, value); }
Command make_basic_cmake_cmd(const Path& cmake_tool_path,
const Path& cmake_script,
const std::vector<CMakeVariable>& pass_variables)
{
Command cmd{cmake_tool_path};
for (auto&& var : pass_variables)
{
cmd.string_arg(var.s);
}
cmd.string_arg("-P").string_arg(cmake_script);
return cmd;
}
Command& Command::string_arg(StringView s) &
{
if (!buf.empty()) buf.push_back(' ');
append_shell_escaped(buf, s);
return *this;
}
#if defined(_WIN32)
Environment get_modified_clean_environment(const std::unordered_map<std::string, std::string>& extra_env,
StringView prepend_to_path)
{
const std::string& system_root_env = get_system_root().value_or_exit(VCPKG_LINE_INFO).native();
const std::string& system32_env = get_system32().value_or_exit(VCPKG_LINE_INFO).native();
std::string new_path;
if (!prepend_to_path.empty())
{
Strings::append(new_path, prepend_to_path);
if (prepend_to_path.back() != ';')
{
new_path.push_back(';');
}
}
Strings::append(new_path,
system32_env,
';',
system_root_env,
';',
system32_env,
"\\Wbem;",
system32_env,
"\\WindowsPowerShell\\v1.0\\");
std::vector<std::string> env_strings = {
"ALLUSERSPROFILE",
"APPDATA",
"CommonProgramFiles",
"CommonProgramFiles(x86)",
"CommonProgramW6432",
"COMPUTERNAME",
"ComSpec",
"HOMEDRIVE",
"HOMEPATH",
"LOCALAPPDATA",
"LOGONSERVER",
"NUMBER_OF_PROCESSORS",
"OS",
"PATHEXT",
"PROCESSOR_ARCHITECTURE",
"PROCESSOR_ARCHITEW6432",
"PROCESSOR_IDENTIFIER",
"PROCESSOR_LEVEL",
"PROCESSOR_REVISION",
"ProgramData",
"ProgramFiles",
"ProgramFiles(x86)",
"ProgramW6432",
"PROMPT",
"PSModulePath",
"PUBLIC",
"SystemDrive",
"SystemRoot",
"TEMP",
"TMP",
"USERDNSDOMAIN",
"USERDOMAIN",
"USERDOMAIN_ROAMINGPROFILE",
"USERNAME",
"USERPROFILE",
"windir",
// Enables proxy information to be passed to Curl, the underlying download library in cmake.exe
"http_proxy",
"https_proxy",
// Environment variables to tell git to use custom SSH executable or command
"GIT_SSH",
"GIT_SSH_COMMAND",
// Points to a credential-manager binary for git authentication
"GIT_ASKPASS",
// Environment variables needed for ssh-agent based authentication
"SSH_AUTH_SOCK",
"SSH_AGENT_PID",
// Enables find_package(CUDA) and enable_language(CUDA) in CMake
"CUDA_PATH",
"CUDA_PATH_V9_0",
"CUDA_PATH_V9_1",
"CUDA_PATH_V10_0",
"CUDA_PATH_V10_1",
"CUDA_PATH_V10_2",
"CUDA_PATH_V11_0",
"CUDA_PATH_V11_1",
"CUDA_PATH_V11_2",
"CUDA_TOOLKIT_ROOT_DIR",
// Environment variable generated automatically by CUDA after installation
"NVCUDASAMPLES_ROOT",
"NVTOOLSEXT_PATH",
// Enables find_package(Vulkan) in CMake. Environment variable generated by Vulkan SDK installer
"VULKAN_SDK",
// Enable targeted Android NDK
"ANDROID_NDK_HOME",
// Environment variables generated automatically by Intel oneAPI after installation
"ONEAPI_ROOT",
"IFORT_COMPILER19",
"IFORT_COMPILER20",
"IFORT_COMPILER21",
// Environment variables used by wrapper scripts to allow us to set environment variables in parent shells
"Z_VCPKG_POSTSCRIPT",
"Z_VCPKG_UNDO",
// Ensures that the escape hatch persists to recursive vcpkg invocations like x-download
"VCPKG_KEEP_ENV_VARS",
// Enables Xbox SDKs
"GameDKLatest",
"GRDKLatest",
"GXDKLatest",
};
const Optional<std::string> keep_vars = get_environment_variable("VCPKG_KEEP_ENV_VARS");
const auto k = keep_vars.get();
if (k && !k->empty())
{
auto vars = Strings::split(*k, ';');
for (auto&& var : vars)
{
if (Strings::case_insensitive_ascii_equals(var, "PATH"))
{
new_path.assign(prepend_to_path.data(), prepend_to_path.size());
if (!new_path.empty()) new_path.push_back(';');
new_path.append(get_environment_variable("PATH").value_or(""));
}
else
{
env_strings.push_back(std::move(var));
}
}
}
Environment env;
for (auto&& env_string : env_strings)
{
const Optional<std::string> value = get_environment_variable(env_string);
const auto v = value.get();
if (!v || v->empty()) continue;
env.add_entry(env_string, *v);
}
if (extra_env.find("PATH") != extra_env.end())
{
new_path.push_back(';');
new_path += extra_env.find("PATH")->second;
}
env.add_entry("PATH", new_path);
// NOTE: we support VS's without the english language pack,
// but we still want to default to english just in case your specific
// non-standard build system doesn't support non-english
env.add_entry("VSLANG", "1033");
env.add_entry("VSCMD_SKIP_SENDTELEMETRY", "1");
for (const auto& item : extra_env)
{
if (item.first == "PATH") continue;
env.add_entry(item.first, item.second);
}
return env;
}
#else
Environment get_modified_clean_environment(const std::unordered_map<std::string, std::string>&,
StringView prepend_to_path)
{
Environment env;
if (!prepend_to_path.empty())
{
env.add_entry(
"PATH",
Strings::concat(prepend_to_path, ':', get_environment_variable("PATH").value_or_exit(VCPKG_LINE_INFO)));
}
return env;
}
#endif
void Environment::add_entry(StringView key, StringView value)
{
#if defined(_WIN32)
m_env_data.append(Strings::to_utf16(key));
m_env_data.push_back(L'=');
m_env_data.append(Strings::to_utf16(value));
m_env_data.push_back(L'\0');
#else
Strings::append(m_env_data, key);
m_env_data.push_back('=');
append_shell_escaped(m_env_data, value);
m_env_data.push_back(' ');
#endif
}
const Environment::string_t& Environment::get() const { return m_env_data; }
const Environment& get_clean_environment()
{
static const Environment clean_env = get_modified_clean_environment({});
return clean_env;
}
std::vector<ExpectedL<ExitCodeAndOutput>> cmd_execute_and_capture_output_parallel(View<Command> commands)
{
RedirectedProcessLaunchSettings default_redirected_process_launch_settings;
return cmd_execute_and_capture_output_parallel(commands, default_redirected_process_launch_settings);
}
std::vector<ExpectedL<ExitCodeAndOutput>> cmd_execute_and_capture_output_parallel(
View<Command> commands, const RedirectedProcessLaunchSettings& settings)
{
std::vector<ExpectedL<ExitCodeAndOutput>> res(commands.size(), LocalizedString{});
parallel_transform(
commands, res.begin(), [&](const Command& cmd) { return cmd_execute_and_capture_output(cmd, settings); });
return res;
}
} // namespace vcpkg
namespace
{
#if defined(_WIN32)
void close_handle_mark_invalid(HANDLE& target) noexcept
{
auto to_close = std::exchange(target, INVALID_HANDLE_VALUE);
if (to_close != INVALID_HANDLE_VALUE && to_close)
{
CloseHandle(to_close);
}
}
struct ProcessInfo : PROCESS_INFORMATION
{
ProcessInfo() noexcept : PROCESS_INFORMATION{INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE, 0, 0} { }
ProcessInfo(const ProcessInfo&) = delete;
ProcessInfo& operator=(const ProcessInfo&) = delete;
~ProcessInfo()
{
close_handle_mark_invalid(hThread);
close_handle_mark_invalid(hProcess);
}
unsigned int wait()
{
close_handle_mark_invalid(hThread);
const DWORD result = WaitForSingleObject(hProcess, INFINITE);
Checks::check_exit(VCPKG_LINE_INFO, result != WAIT_FAILED, "WaitForSingleObject failed");
DWORD exit_code = 0;
GetExitCodeProcess(hProcess, &exit_code);
close_handle_mark_invalid(hProcess);
return exit_code;
}
};
ExpectedL<Unit> windows_create_process(std::int32_t debug_id,
ProcessInfo& process_info,
StringView command_line,
const Optional<Path>& working_directory,
const Optional<Environment>& environment,
BOOL bInheritHandles,
DWORD dwCreationFlags,
STARTUPINFOEXW& startup_info) noexcept
{
Debug::print(fmt::format("{}: CreateProcessW({})\n", debug_id, command_line));
// Flush stdout before launching external process
fflush(nullptr);
Optional<std::wstring> working_directory_wide = working_directory.map([](const Path& wd) {
// this only fails if we can't get the current working directory of vcpkg, and we assume that we have that,
// so it's fine anyways
return Strings::to_utf16(real_filesystem.absolute(wd, VCPKG_LINE_INFO));
});
LPCWSTR working_directory_arg = nullptr;
if (auto wd = working_directory_wide.get())
{
working_directory_arg = wd->c_str();
}
std::wstring environment_block;
LPVOID call_environment = nullptr;
if (auto env_unpacked = environment.get())
{
environment_block = env_unpacked->get();
environment_block.push_back('\0');
call_environment = environment_block.data();
}
// Leaking process information handle 'process_info.proc_info.hProcess'
// /analyze can't tell that we transferred ownership here
VCPKG_MSVC_WARNING(suppress : 6335)
if (!CreateProcessW(nullptr,
Strings::to_utf16(command_line).data(),
nullptr,
nullptr,
bInheritHandles,
IDLE_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT | EXTENDED_STARTUPINFO_PRESENT |
dwCreationFlags,
call_environment,
working_directory_arg,
&startup_info.StartupInfo,
&process_info))
{
return format_system_error_message("CreateProcessW", GetLastError());
}
return Unit{};
}
// Used to, among other things, control which handles are inherited by child processes.
// from https://devblogs.microsoft.com/oldnewthing/20111216-00/?p=8873
struct ProcAttributeList
{
ExpectedL<Unit> create(DWORD dwAttributeCount)
{
Checks::check_exit(VCPKG_LINE_INFO, buffer.empty());
SIZE_T size = 0;
if (InitializeProcThreadAttributeList(nullptr, dwAttributeCount, 0, &size) ||
GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
return format_system_error_message("InitializeProcThreadAttributeList nullptr", GetLastError());
}
Checks::check_exit(VCPKG_LINE_INFO, size > 0);
ASSUME(size > 0);
buffer.resize(size);
if (!InitializeProcThreadAttributeList(
reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(buffer.data()), dwAttributeCount, 0, &size))
{
return format_system_error_message("InitializeProcThreadAttributeList attribute_list", GetLastError());
}
return Unit{};
}
ExpectedL<Unit> update_attribute(DWORD_PTR Attribute, PVOID lpValue, SIZE_T cbSize)
{
if (!UpdateProcThreadAttribute(get(), 0, Attribute, lpValue, cbSize, nullptr, nullptr))
{
return format_system_error_message("InitializeProcThreadAttributeList attribute_list", GetLastError());
}
return Unit{};
}
LPPROC_THREAD_ATTRIBUTE_LIST get() noexcept
{
return reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(buffer.data());
}
ProcAttributeList() = default;
ProcAttributeList(const ProcAttributeList&) = delete;
ProcAttributeList& operator=(const ProcAttributeList&) = delete;
~ProcAttributeList()
{
if (!buffer.empty())
{
DeleteProcThreadAttributeList(get());
}
}
private:
std::vector<unsigned char> buffer;
};
struct AnonymousPipe
{
HANDLE read_pipe = INVALID_HANDLE_VALUE;
HANDLE write_pipe = INVALID_HANDLE_VALUE;
AnonymousPipe() = default;
AnonymousPipe(const AnonymousPipe&) = delete;
AnonymousPipe& operator=(const AnonymousPipe&) = delete;
~AnonymousPipe()
{
close_handle_mark_invalid(read_pipe);
close_handle_mark_invalid(write_pipe);
}
ExpectedL<Unit> create()
{
Checks::check_exit(VCPKG_LINE_INFO, read_pipe == INVALID_HANDLE_VALUE);
Checks::check_exit(VCPKG_LINE_INFO, write_pipe == INVALID_HANDLE_VALUE);
SECURITY_ATTRIBUTES anonymousSa{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
if (!CreatePipe(&read_pipe, &write_pipe, &anonymousSa, 0))
{
return format_system_error_message("CreatePipe", GetLastError());
}
return Unit{};
}
};
struct CreatorOnlySecurityDescriptor
{
PSECURITY_DESCRIPTOR sd;
CreatorOnlySecurityDescriptor() : sd{}
{
// DACL:
// ACE 0: Allow; FILE_READ;;;OWNER_RIGHTS
Checks::check_exit(
VCPKG_LINE_INFO,
ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:(A;;FR;;;OW)", SDDL_REVISION_1, &sd, 0));
}
~CreatorOnlySecurityDescriptor() { LocalFree(sd); }
CreatorOnlySecurityDescriptor(const CreatorOnlySecurityDescriptor&) = delete;
CreatorOnlySecurityDescriptor& operator=(const CreatorOnlySecurityDescriptor&) = delete;
};
// An output pipe to use as stdin for a child process
struct OverlappedOutputPipe
{
HANDLE read_pipe = INVALID_HANDLE_VALUE;
HANDLE write_pipe = INVALID_HANDLE_VALUE;
OverlappedOutputPipe() = default;
OverlappedOutputPipe(const OverlappedOutputPipe&) = delete;
OverlappedOutputPipe& operator=(const OverlappedOutputPipe&) = delete;
~OverlappedOutputPipe()
{
close_handle_mark_invalid(read_pipe);
close_handle_mark_invalid(write_pipe);
}
ExpectedL<Unit> create(std::int32_t debug_id)
{
Checks::check_exit(VCPKG_LINE_INFO, read_pipe == INVALID_HANDLE_VALUE);
Checks::check_exit(VCPKG_LINE_INFO, write_pipe == INVALID_HANDLE_VALUE);
static CreatorOnlySecurityDescriptor creator_owner_sd;
SECURITY_ATTRIBUTES namedPipeSa{sizeof(SECURITY_ATTRIBUTES), creator_owner_sd.sd, FALSE};
std::wstring pipe_name{Strings::to_utf16(
fmt::format(R"(\\.\pipe\local\vcpkg-to-stdin-A8B4F218-4DB1-4A3E-8E5B-C41F1633F627-{}-{})",
GetCurrentProcessId(),
debug_id))};
write_pipe = CreateNamedPipeW(pipe_name.c_str(),
PIPE_ACCESS_OUTBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE | PIPE_REJECT_REMOTE_CLIENTS,
1, // nMaxInstances
65535, // nOutBufferSize
0, // nInBufferSize (unused / PIPE_ACCESS_OUTBOUND)
0, // nDefaultTimeout (only for WaitPipe; unused)
&namedPipeSa);
if (write_pipe == INVALID_HANDLE_VALUE)
{
return format_system_error_message("CreateNamedPipeW stdin", GetLastError());
}
SECURITY_ATTRIBUTES openSa{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
read_pipe = CreateFileW(pipe_name.c_str(), FILE_GENERIC_READ, 0, &openSa, OPEN_EXISTING, 0, 0);
if (read_pipe == INVALID_HANDLE_VALUE)
{
return format_system_error_message("CreateFileW stdin", GetLastError());
}
return Unit{};
}
};
// Ensure that all asynchronous procedure calls pending for this thread are called
void drain_apcs()
{
switch (SleepEx(0, TRUE))
{
case 0:
// timeout expired, OK
break;
case WAIT_IO_COMPLETION:
// completion queue drained completed, OK
break;
default: vcpkg::Checks::unreachable(VCPKG_LINE_INFO); break;
}
}
struct OverlappedStatus : OVERLAPPED
{
DWORD expected_write;
HANDLE* target;
int32_t debug_id;
};
struct RedirectedProcessInfo
{
AnonymousPipe stdout_pipe;
OverlappedOutputPipe stdin_pipe;
ProcessInfo proc_info;
RedirectedProcessInfo() = default;
RedirectedProcessInfo(const RedirectedProcessInfo&) = delete;
RedirectedProcessInfo& operator=(const RedirectedProcessInfo&) = delete;
~RedirectedProcessInfo() = default;
VCPKG_MSVC_WARNING(suppress : 6262) // function uses 32k of stack
int wait_and_stream_output(int32_t debug_id,
const char* input,
DWORD input_size,
const std::function<void(char*, size_t)>& raw_cb)
{
static const auto stdin_completion_routine =
[](DWORD dwErrorCode, DWORD dwNumberOfBytesTransferred, LPOVERLAPPED pOverlapped) {
const auto status = static_cast<OverlappedStatus*>(pOverlapped);
switch (dwErrorCode)
{
case 0:
// OK, done
Checks::check_exit(VCPKG_LINE_INFO, dwNumberOfBytesTransferred == status->expected_write);
break;
case ERROR_BROKEN_PIPE:
case ERROR_OPERATION_ABORTED:
// OK, child didn't want all the data
break;
default:
Debug::print(fmt::format("{}: Unexpected error writing to stdin of a child process: {:X}\n",
status->debug_id,
dwErrorCode));
break;
}
close_handle_mark_invalid(*status->target);
};
OverlappedStatus stdin_write{};
stdin_write.expected_write = input_size;
stdin_write.target = &stdin_pipe.write_pipe;
stdin_write.debug_id = debug_id;
if (input_size == 0)
{
close_handle_mark_invalid(stdin_pipe.write_pipe);
}
else
{
stdin_write.expected_write = input_size;
if (WriteFileEx(stdin_pipe.write_pipe, input, input_size, &stdin_write, stdin_completion_routine))