Repository navigation
Expand file tree
/
Copy pathsupport.cpp
More file actions
1710 lines (1591 loc) · 71.4 KB
/
Copy pathsupport.cpp
File metadata and controls
1710 lines (1591 loc) · 71.4 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
module;
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <arpa/inet.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <poll.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
extern char** environ;
#endif
module mcpp.test.support;
import std;
namespace mcpp::test::support {
// ---- the machine -------------------------------------------------------------------------------
bool on_windows() noexcept {
#if defined(_WIN32)
return true;
#else
return false;
#endif
}
bool on_macos() noexcept {
#if defined(__APPLE__)
return true;
#else
return false;
#endif
}
bool on_linux() noexcept {
#if defined(__linux__)
return true;
#else
return false;
#endif
}
bool on_x86_64() noexcept {
#if defined(__x86_64__) || defined(_M_X64)
return true;
#else
return false;
#endif
}
std::string exe(std::string_view name) {
return on_windows() ? std::string(name) + ".exe" : std::string(name);
}
std::optional<std::string> env(std::string_view name) {
if (const char* v = std::getenv(std::string(name).c_str()))
return std::string(v);
return std::nullopt;
}
std::optional<fs::path> on_path(std::string_view name) {
const auto path = env("PATH");
if (!path)
return std::nullopt;
const char sep = on_windows() ? ';' : ':';
for (auto part : std::views::split(std::string_view(*path), sep)) {
const fs::path dir(std::string(part.begin(), part.end()));
if (dir.empty())
continue;
std::error_code ec;
for (const auto& candidate : {dir / name, dir / (std::string(name) + ".exe")})
if (fs::is_regular_file(candidate, ec))
return candidate;
}
return std::nullopt;
}
std::optional<fs::path> host_cc() {
static const std::optional<fs::path> found = [] () -> std::optional<fs::path> {
std::vector<fs::path> candidates;
for (std::string_view name : {"gcc", "cc"})
if (auto p = on_path(name)) candidates.push_back(*p);
for (std::string_view p : {"/usr/bin/gcc", "/usr/bin/cc"}) candidates.emplace_back(p);
const auto dir = fs::temp_directory_path() / std::format("mcpp-e2e-cc-{:x}", std::random_device{}());
fs::create_directories(dir);
{ std::ofstream(dir / "probe.c") << "int probe(void) { return 1; }\n"; }
std::optional<fs::path> works;
for (const auto& c : candidates) {
std::error_code ec;
if (!fs::is_regular_file(c, ec)) continue;
auto r = e2e::run({.argv = {c.string(), "-shared", "-fPIC", (dir / "probe.c").string(), "-o", (dir / "libprobe.so").string()}});
if (r) { works = c; break; }
}
std::error_code ec;
fs::remove_all(dir, ec);
return works;
}();
return found;
}
// ---- what payloads and the system provide (the capabilities of support.cppm) ----------------
namespace {
fs::path home_dir() {
if (auto h = env("MCPP_HOME"); h && !h->empty())
return *h;
return fs::path(env(on_windows() ? "USERPROFILE" : "HOME").value_or("")) / ".mcpp";
}
fs::path user_dir() { return env(on_windows() ? "USERPROFILE" : "HOME").value_or(""); }
// A payload under the registry of the home or of the user's xlings: `<xpkgs>/<pattern>`.
bool payload(std::string_view pattern, bool xlings_too = true) {
if (!glob(home_dir() / "registry/data/xpkgs", pattern).empty())
return true;
return xlings_too && !glob(user_dir() / ".xlings/data/xpkgs", pattern).empty();
}
} // namespace
bool provides(std::string_view c) {
if (c == "musl")
return on_path("x86_64-linux-musl-g++") || payload("xim-x-musl-gcc/*/bin/x86_64-linux-musl-g++");
if (c == "mingw-cross") return payload("xim-x-mingw-cross-gcc/*/bin/x86_64-w64-mingw32-g++");
if (c == "llvm") return payload("xim-x-llvm/*/bin/clang++", false);
if (c == "mingw-host-headers") {
if (fs::is_directory("/usr/x86_64-w64-mingw32/include")) return true;
auto root = env("MCPP_E2E_HOST_MINGW_ROOT");
return root && !root->empty() && fs::is_regular_file(fs::path(*root) / "x86_64-w64-mingw32/include/io.h");
}
if (c == "qemu-arm") return on_path("qemu-system-arm") || payload("xim-x-qemu-arm/*/bin/qemu-system-arm");
if (c == "android-ndk") return payload("xim-x-android-ndk/*/toolchains/llvm/prebuilt/*/bin/clang++");
if (c == "android-device") {
// An arm64 device (not an emulator) answering the platform-tools' adb.
std::vector<fs::path> adbs = glob(user_dir() / ".xlings/data/xpkgs", "xim-x-android-platform-tools/*/adb");
for (auto& a : glob(home_dir() / "registry/data/xpkgs", "xim-x-android-platform-tools/*/adb")) adbs.push_back(a);
for (const auto& adb : adbs) {
auto r = e2e::run({.argv = {adb.string(), "devices"}});
for (auto line : std::views::split(std::string_view(r.out), '\n')) {
std::string_view l(line.begin(), line.end());
const auto tab = l.find('\t');
if (tab == std::string_view::npos || l.starts_with("emulator-") || !l.substr(tab + 1).starts_with("device"))
continue;
auto abi = e2e::run({.argv = {adb.string(), "shell", "getprop", "ro.product.cpu.abi"},
.env = {{"ANDROID_SERIAL", std::string(l.substr(0, tab))}}});
if (abi.out.starts_with("arm64-v8a")) return true;
}
}
return false;
}
if (c == "msvc") {
const fs::path vswhere = "C:/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe";
if (!fs::is_regular_file(vswhere)) return false;
auto r = e2e::run({.argv = {vswhere.string(), "-latest", "-products", "*", "-requires",
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property",
"installationPath"}});
return r.out.find_first_not_of(" \r\n") != std::string::npos;
}
if (c == "mingw") return payload("xim-x-mingw-gcc/*/bin/g++.exe");
if (c == "nasm") return on_path("nasm") || payload("xim-x-nasm/*/nasm", false) || payload("xim-x-nasm/*/bin/nasm", false);
if (c == "scan-deps")
return on_path("clang-scan-deps") || payload("xim-x-llvm/*/bin/clang-scan-deps", false) ||
payload("xim-x-llvm/*/bin/clang-scan-deps.exe", false);
if (c == "import-std-libcxx") return payload("xim-x-llvm/*/share/libc++/v1/std.cppm", false);
mcpplibs::mtest::fail(std::format("no probe provides '{}'", c));
}
namespace {
// `sort -V` order of two versions: numbers as numbers, the rest as text.
bool version_less(std::string_view a, std::string_view b) {
std::size_t i = 0, j = 0;
while (i < a.size() && j < b.size()) {
if (std::isdigit(static_cast<unsigned char>(a[i])) && std::isdigit(static_cast<unsigned char>(b[j]))) {
std::size_t ie = i, je = j;
while (ie < a.size() && std::isdigit(static_cast<unsigned char>(a[ie]))) ++ie;
while (je < b.size() && std::isdigit(static_cast<unsigned char>(b[je]))) ++je;
const auto x = std::stoull(std::string(a.substr(i, ie - i)));
const auto y = std::stoull(std::string(b.substr(j, je - j)));
if (x != y) return x < y;
i = ie; j = je;
} else {
if (a[i] != b[j]) return a[i] < b[j];
++i; ++j;
}
}
return a.size() - i < b.size() - j;
}
} // namespace
std::optional<std::string> newest_payload(std::string_view package, std::string_view probe) {
for (const auto& root : {home_dir() / "registry/data/xpkgs", user_dir() / ".xlings/data/xpkgs"}) {
std::vector<std::string> versions;
for (const auto& v : glob(root / package, "*"))
if (probe.empty() || !glob(v, probe).empty())
versions.push_back(v.filename().string());
if (!versions.empty())
return *std::ranges::max_element(versions, version_less);
}
return std::nullopt;
}
std::string family_version(std::string_view package, std::string_view override, std::string_view fallback) {
if (auto v = env(override); v && !v->empty())
return *v;
// _toolchain_env.sh reads the home's registry only (USERPROFILE's on Windows when unset).
std::vector<std::string> versions;
static const std::regex numeric{R"(^[0-9]+(\.[0-9]+)*$)"};
for (const auto& v : glob(home_dir() / "registry/data/xpkgs" / package, "*")) {
const auto name = v.filename().string();
if (std::regex_match(name, numeric))
versions.push_back(name);
}
if (versions.empty())
return std::string(fallback);
return *std::ranges::max_element(versions, version_less);
}
fs::path payload_root(std::string_view package, std::string_view version) {
const auto mine = home_dir() / "registry/data/xpkgs" / package / version;
if (std::error_code ec; fs::exists(mine, ec))
return mine;
return user_dir() / ".xlings/data/xpkgs" / package / version;
}
// ---- mcpp ----------------------------------------------------------------------------------------
fs::path repository() {
// The directory holding tests/support/mcpp.toml: above this source file when the compiler
// named it absolutely, else above the working directory (`mcpp test` runs in the package).
const auto holds = [](const fs::path& d) {
std::error_code ec;
return fs::is_regular_file(d / "tests/support/mcpp.toml", ec);
};
std::vector<fs::path> starts;
if (const fs::path here = std::source_location::current().file_name(); here.is_absolute())
starts.push_back(here.parent_path());
starts.push_back(fs::current_path());
for (auto d : starts)
for (; !d.empty(); d = d.parent_path()) {
if (holds(d))
return d;
if (d == d.parent_path())
break;
}
mcpplibs::mtest::fail("the mcpp repository was not found above this program");
}
std::string mcpp_path() {
if (auto v = env("MCPP_E2E_MCPP"); v && !v->empty())
return *v;
if (auto v = env("MCPP_BIN_MCPP"); v && !v->empty())
return *v;
if (auto v = env("MCPP"); v && !v->empty())
return *v;
return e2e::program("mcpp");
}
namespace {
// "\r\n" read as "\n" on Windows, as the POSIX tools of a Windows shell read lines.
std::string lines_as_text(std::string t) {
if (!on_windows()) return t;
std::string lf;
lf.reserve(t.size());
for (std::size_t i = 0; i < t.size(); ++i)
if (!(t[i] == '\r' && i + 1 < t.size() && t[i + 1] == '\n')) lf.push_back(t[i]);
return lf;
}
} // namespace
e2e::outcome as_text(e2e::outcome r) {
r.out = lines_as_text(std::move(r.out));
r.err = lines_as_text(std::move(r.err));
return r;
}
namespace {
// THE SURFACE A COMMAND USED (design 2026-11-20 §5.16, SPEC-017 P5.6). mcpp appends the items it
// used -- the command and flags it was given, the manifest keys it read, the reasons it recorded --
// to the file MCPP_SURFACE_RECORD names; the case states them as its `exercise`, which the ledger
// of the surface reads. Every command the kit composes has a record, placed first, so that a case
// that names its own record keeps it: `mcpp()` states its command's when it ends, and the case's
// end states the rest -- the commands a case ran as a session, under another program, or by its
// own means from `mcpp_command`.
constexpr std::string_view kRecordPrefix = ".surface-";
fs::path surface_record() {
static std::atomic<unsigned> n{0};
return case_dir() / std::format("{}{}", kRecordPrefix, n++);
}
void report_surface(const fs::path& record) {
std::error_code ec;
if (!fs::exists(record, ec)) return;
std::set<std::string> items;
for (auto part : std::views::split(read_file(record), '\n')) {
std::string line(part.begin(), part.end());
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.find(' ') != std::string::npos) items.insert(std::move(line));
}
fs::remove(record, ec);
if (!items.empty()) mcpplibs::mtest::exercise({items.begin(), items.end()});
}
void report_remaining_surface() {
std::error_code ec;
std::vector<fs::path> records;
for (const auto& e : fs::directory_iterator(case_dir(), ec))
if (e.path().filename().string().starts_with(kRecordPrefix)) records.push_back(e.path());
for (const auto& r : records) report_surface(r);
}
} // namespace
// THE SHARED HOME IS A RUN FIXTURE (SPEC-017 P11, design 2026-11-20 §5.10). Its contents -- the
// index, the default toolchain, the standard library's modules -- were filled by whichever case ran
// first, and that case's time held them. Served once per run, the filling is the fixture's own
// (`fixtures.ndjson`): a project made and built in the home. A filling that fails is printed and
// the home is served as it is, since a case that needs no toolchain still runs in it.
mcpplibs::mtest::run_fixture shared_home_fixture{"home", [](mcpplibs::mtest::serving& serve) {
const auto home = home_dir();
const auto scratch = fs::temp_directory_path() / std::format("mcpp-e2e-home-{:08x}", std::random_device{}());
std::error_code ec;
fs::create_directories(scratch, ec);
std::vector<std::pair<std::string, std::optional<std::string>>> env{{"MCPP_HOME", home.string()},
{"MCPP_VERBOSE", std::nullopt}};
auto made = e2e::run({.argv = {mcpp_path(), "new", "filling"}, .cwd = scratch, .env = env,
.timeout = std::chrono::minutes{10}});
auto built = made ? e2e::run({.argv = {mcpp_path(), "build"}, .cwd = scratch / "filling", .env = env,
.timeout = std::chrono::minutes{30}})
: made;
if (!built)
std::println(std::cerr, "the shared home {} was not filled (status {}):\n{}{}", home.string(),
built.status, built.out, built.err);
fs::remove_all(scratch, ec);
serve.ready(home.string());
serve.stopped();
}};
// THE DIAGNOSTIC LINES (design 2026-11-20 §5.18, mtest 0.11.0): a line mcpp writes as a warning or
// an error -- a degradation is written as a warning -- in the output of a program a case ran is the
// case's to declare (`e2e::expect_diagnostic`). Under `report`, the policy the cases migrate under,
// an undeclared line is printed and counted as the case's metric `diagnostics.undeclared`, and the
// case is not failed for it. Declared at the first command, after mtest's own state exists.
void declare_diagnostics() {
static std::once_flag once;
std::call_once(once, [] {
e2e::diagnostics({"^(\\x1b\\[[0-9;]*m)*warning:", "^(\\x1b\\[[0-9;]*m)*error:"});
e2e::diagnostics_policy(e2e::diagnostic_policy::report);
});
}
e2e::outcome mcpp(std::vector<std::string> args, const fs::path& cwd, const options& o) {
auto c = mcpp_command(std::move(args), cwd, o);
declare_diagnostics();
const fs::path record = *c.env.front().second;
auto r = as_text(e2e::run(std::move(c)));
report_surface(record);
return r;
}
std::optional<home> own_home_of_case(); // below, with the case's directories
e2e::command mcpp_command(std::vector<std::string> args, const fs::path& cwd, const options& o) {
e2e::command c;
c.argv = o.wrap;
c.argv.push_back(mcpp_path());
for (auto& a : args) c.argv.push_back(std::move(a));
c.cwd = cwd;
c.env.emplace_back("MCPP_SURFACE_RECORD", surface_record().string());
mcpplibs::mtest::at_case_end("mcpp.test.support.surface", report_remaining_surface);
const auto where = o.where == home::shared ? own_home_of_case().value_or(home::shared) : o.where;
if (where != home::shared) {
c.env.emplace_back("MCPP_HOME", case_home(where).string());
} else if (const auto served = mcpplibs::mtest::fixture_endpoint("home"); !served.empty()) {
c.env.emplace_back("MCPP_HOME", served);
} else if (!env("MCPP_HOME")) {
if (auto u = env(on_windows() ? "USERPROFILE" : "HOME"))
c.env.emplace_back("MCPP_HOME", (fs::path(*u) / ".mcpp").string());
}
// A case reads mcpp's default output: the runner's MCPP_VERBOSE (a CI job sets it for its other
// steps) is not the case's, which states its own.
c.env.emplace_back("MCPP_VERBOSE", std::nullopt);
for (const auto& kv : o.env) c.env.push_back(kv);
c.input = o.input;
// A COMMAND HAS THE TIME ITS CASE HAS LEFT (design 2026-11-20 §5.8, K1). The kit also held each
// command to ten minutes, below the time a suite states: a pack of every system in `sets/985`
// ran past ten minutes beside three other openkal programs on a four-processor runner, its
// suite well within the 45 minutes it states, and failed as a hang (CI, 2026-11-21). A time limit
// bounds a hang; how long work takes is a measure of the run's records, not a verdict. Where no
// scope states a time, ten minutes bounds a command, since the runner's limit would end the
// program without the case's report of it.
c.timeout = o.timeout.value_or(mcpplibs::mtest::time_left().value_or(std::chrono::minutes{10}));
return c;
}
std::string text(const e2e::outcome& r) { return r.out + r.err; }
fs::path shared_home() { return home_dir(); }
std::vector<std::string> through_wine(const fs::path& wine, const fs::path& program,
const std::vector<std::string>& args) {
const auto server = wine.parent_path() / "wineserver";
std::vector<std::string> argv = {"sh", "-c",
std::format("'{}' \"$@\"; status=$?; '{}' -w; exit $status", wine.string(),
fs::exists(server) ? server.string() : std::string("wineserver")),
"wine", program.string()};
argv.insert(argv.end(), args.begin(), args.end());
return argv;
}
namespace {
void link_or_copy(const fs::path& from, const fs::path& to) {
std::error_code ec;
if (fs::exists(fs::symlink_status(to, ec)))
return;
fs::create_directory_symlink(from, to, ec);
if (ec)
fs::copy(from, to, fs::copy_options::recursive, ec);
}
// THE USER'S PAYLOADS ARE UPSTREAMS OF THE CASE'S HOME, NEVER LINKS INTO IT (mcpp#293, design
// 2026-11-20 §5.10). A link to each payload made the user's store part of the case's: a hook the
// case's home ran again (gcc's specs, an ELF patch) wrote through the link into the user's
// toolchain, with paths of the case's temporary home. An upstream is read by link at install and
// never written (docs/25 §3): the case's home installs what it needs from the user's homes.
void name_upstreams(const fs::path& h) {
std::vector<std::string> ups;
std::error_code ec;
for (const auto& u : {home_dir(), user_dir() / ".xlings"})
if (fs::is_directory(u, ec)) ups.push_back(std::format("\"{}\"", u.generic_string()));
if (ups.empty()) return;
std::string line = "upstream = [";
for (std::size_t i = 0; i < ups.size(); ++i) line += (i ? ", " : "") + ups[i];
line += "]";
std::string text = fs::exists(h / "config.toml", ec) ? read_file(h / "config.toml") : std::string{};
std::string out;
bool inXlings = false, placed = false;
for (auto part : std::views::split(text, '\n')) {
std::string l(part.begin(), part.end());
if (l.starts_with('[')) {
if (inXlings && !placed) { out += line + "\n"; placed = true; }
inXlings = l.starts_with("[xlings]");
}
if (inXlings && l.starts_with("upstream")) continue;
out += l + "\n";
}
while (out.ends_with("\n\n")) out.pop_back();
if (inXlings && !placed) { out += line + "\n"; placed = true; }
if (!placed) out += "\n[xlings]\n" + line + "\n";
std::ofstream(h / "config.toml", std::ios::binary) << out;
}
void inherit(const fs::path& h, bool whole) {
const auto user = home_dir();
std::error_code ec;
for (auto name : {"xim-pkgindex", "xim-index-repos"})
if (fs::is_directory(user / "registry/data" / name, ec)) {
fs::create_directories(h / "registry/data");
link_or_copy(user / "registry/data" / name, h / "registry/data" / name);
}
// NO SUBOS IS COPIED: an install by link registers its programs in the case's own subos, and
// a copy of the user's, whose links already name them, made that registration fail (measured:
// `[glibc] failed: declared programs were not registered`).
if (whole && env("MCPP_INHERIT_CONFIG").value_or("1") != "0" && fs::is_regular_file(user / "config.toml", ec))
fs::copy_file(user / "config.toml", h / "config.toml", fs::copy_options::overwrite_existing, ec);
name_upstreams(h);
if (fs::is_directory(user / "bin", ec))
link_or_copy(user / "bin", h / "bin");
// THE SANDBOX, ONCE, WITH THE REAL XLINGS: its runtime contract and the tools every build reads
// (patchelf, ninja), installed from the upstreams by link. A copy of the user's subos and links
// to the payloads gave the home these before; without them a case that runs offline, or that
// puts a stand-in xlings in place, found an uninitialized provider and could install nothing.
// Measured: under a second, and the user's homes unwritten.
std::vector<std::pair<std::string, std::optional<std::string>>> env{{"MCPP_HOME", h.string()},
{"MCPP_VERBOSE", std::nullopt},
{"MCPP_OFFLINE", std::nullopt}};
const auto init = e2e::run({.argv = {mcpp_path(), "self", "init"}, .cwd = h, .env = env,
.timeout = std::chrono::minutes{5}});
if (!init)
std::println(std::cerr, "the case's home {} was not initialized (status {}):\n{}{}", h.string(), init.status,
init.out, init.err);
}
} // namespace
namespace {
// The directories of the cases (their own directory and their homes), made under the system's
// temporary directory. Not the runner's case directory: that lies under the repository's target/,
// and mcpp run in a directory with no manifest of its own would find the repository's mcpp.toml
// and build it; and a payload may hold its install directory in a fixed space (glibc's binaries
// hold 255 bytes), which a case directory under target/ exceeds where `mktemp -d` did not.
//
// Each is filed under the runner's directory of the case that made it (mtest::temp_dir(), which
// mtest removes when the case ends): a directory whose case has ended is removed by the next use
// of this registry, and the rest when the program ends.
struct case_dirs {
std::mutex m;
std::vector<std::pair<fs::path, fs::path>> made; // (the case's runner directory, the directory)
std::map<fs::path, fs::path> own; // the case's own directory, by its runner directory
std::map<fs::path, fs::path> home; // the case's home, by its runner directory
std::map<fs::path, support::home> instead; // the home a case runs mcpp in instead of the shared one
~case_dirs() {
std::error_code ec;
for (const auto& [_, d] : made) fs::remove_all(d, ec);
}
// Removes the directories of the cases that have ended. Called with `m` held.
void sweep() {
std::error_code ec;
std::erase_if(made, [&](const auto& e) {
if (fs::exists(e.first, ec)) return false;
fs::remove_all(e.second, ec);
own.erase(e.first);
home.erase(e.first);
instead.erase(e.first);
return true;
});
}
// A new directory `<temp>/<prefix>-XXXXXXXX` of the current case. Called with `m` held.
fs::path make(std::string_view prefix) {
const auto key = mcpplibs::mtest::temp_dir();
sweep();
std::random_device rd;
fs::path d;
std::error_code ec;
do d = fs::temp_directory_path() / std::format("{}-{:08x}", prefix, rd());
while (!fs::create_directory(d, ec) && !ec);
made.emplace_back(key, d);
return d;
}
};
case_dirs& registry_of_cases() {
static case_dirs h;
return h;
}
void populate_home(const fs::path& h, home kind) {
std::error_code ec;
if (kind == home::linked && fs::is_directory(home_dir() / "registry", ec))
link_or_copy(home_dir() / "registry", h / "registry");
else if (kind == home::inherited || kind == home::payloads)
inherit(h, kind == home::inherited);
else if (kind == home::registry)
std::ofstream(h / "config.toml") << std::format("[xlings]\nhome = \"{}\"\n", (home_dir() / "registry").generic_string());
}
} // namespace
fs::path case_dir() {
auto& all = registry_of_cases();
const auto key = mcpplibs::mtest::temp_dir();
std::scoped_lock lock(all.m);
if (auto it = all.own.find(key); it != all.own.end() && fs::exists(it->second))
return it->second;
const auto d = all.make("mcpp-e2e-case");
all.own[key] = d;
return d;
}
fs::path case_home(home kind) {
auto& all = registry_of_cases();
const auto key = mcpplibs::mtest::temp_dir();
std::scoped_lock lock(all.m);
if (auto it = all.home.find(key); it != all.home.end() && fs::exists(it->second))
return it->second;
const auto h = all.make("mcpp-e2e-home");
all.home[key] = h;
populate_home(h, kind);
return h;
}
void own_home(home kind) {
auto& all = registry_of_cases();
const auto key = mcpplibs::mtest::temp_dir();
std::scoped_lock lock(all.m);
all.sweep();
all.instead[key] = kind;
}
std::optional<home> own_home_of_case() {
auto& all = registry_of_cases();
std::scoped_lock lock(all.m);
if (auto it = all.instead.find(mcpplibs::mtest::temp_dir()); it != all.instead.end()) return it->second;
return std::nullopt;
}
fs::path another_home(home kind) {
auto& all = registry_of_cases();
std::scoped_lock lock(all.m);
const auto h = all.make("mcpp-e2e-home");
populate_home(h, kind);
return h;
}
// ---- a project -----------------------------------------------------------------------------------
namespace {
void write_into(const fs::path& dir, std::string_view relative, std::string_view content) {
const auto file = dir / fs::path(std::u8string(relative.begin(), relative.end()));
if (file.has_parent_path())
fs::create_directories(file.parent_path());
std::ofstream(file, std::ios::binary).write(content.data(), static_cast<std::streamsize>(content.size()));
}
} // namespace
project::project(files contents) : project(case_dir() / "project", contents) {}
project::project(fs::path dir, files contents) : dir_(std::move(dir)) {
fs::create_directories(dir_);
for (const auto& [path, content] : contents)
write_into(dir_, path, content);
}
fs::path project::at(std::string_view relative) const {
return dir_ / fs::path(std::u8string(relative.begin(), relative.end()));
}
void project::write(std::string_view relative, std::string_view content) const { write_into(dir_, relative, content); }
std::string project::read(std::string_view relative) const { return lines_as_text(read_file(at(relative))); }
bool project::exists(std::string_view relative) const { return fs::exists(at(relative)); }
void project::remove(std::string_view relative) const { fs::remove_all(at(relative)); }
e2e::outcome project::mcpp(std::vector<std::string> args, const options& o) const {
return support::mcpp(std::move(args), dir_, o);
}
e2e::outcome project::mcpp_in(std::string_view sub, std::vector<std::string> args, const options& o) const {
return support::mcpp(std::move(args), at(sub), o);
}
std::optional<fs::path> project::artifact(std::string_view name) const {
return find_file(dir_ / "target", name);
}
project project::scaffold(std::string_view name, std::vector<std::string> args) {
const auto parent = case_dir() / "new";
fs::create_directories(parent);
std::vector<std::string> argv{"new", std::string(name)};
argv.insert(argv.end(), args.begin(), args.end());
auto r = support::mcpp(std::move(argv), parent);
if (!r)
mcpplibs::mtest::fail(std::format("mcpp new {} failed: {}\n{}", name, r.line, text(r)));
return project(parent / fs::path(std::u8string(name.begin(), name.end())), {});
}
std::optional<fs::path> find_file(const fs::path& root, std::string_view name) {
std::error_code ec;
if (!fs::is_directory(root, ec))
return std::nullopt;
std::vector<fs::path> found;
for (auto it = fs::recursive_directory_iterator(root, fs::directory_options::skip_permission_denied, ec);
it != fs::recursive_directory_iterator(); it.increment(ec))
if (it->is_regular_file(ec) && it->path().filename() == name)
found.push_back(it->path());
if (found.empty())
return std::nullopt;
std::ranges::sort(found); // the same answer on every run
return found.front();
}
std::vector<fs::path> find_files(const fs::path& root, std::string_view pattern) {
std::vector<fs::path> found;
std::error_code ec;
if (!fs::is_directory(root, ec))
return found;
const std::regex re{std::string(pattern)};
for (auto it = fs::recursive_directory_iterator(root, fs::directory_options::skip_permission_denied, ec);
it != fs::recursive_directory_iterator(); it.increment(ec))
if (it->is_regular_file(ec) && std::regex_match(it->path().filename().string(), re))
found.push_back(it->path());
std::ranges::sort(found);
return found;
}
std::vector<std::string> listing(const fs::path& root) {
std::vector<std::string> out;
std::error_code ec;
for (auto it = fs::recursive_directory_iterator(root, fs::directory_options::skip_permission_denied, ec);
it != fs::recursive_directory_iterator(); it.increment(ec))
out.push_back(it->path().lexically_relative(root).generic_string());
std::ranges::sort(out);
return out;
}
std::optional<fs::path> newest_file(const fs::path& root, std::string_view name) {
std::optional<fs::path> best;
fs::file_time_type when{};
std::error_code ec;
if (!fs::is_directory(root, ec))
return best;
for (auto it = fs::recursive_directory_iterator(root, fs::directory_options::skip_permission_denied, ec);
it != fs::recursive_directory_iterator(); it.increment(ec)) {
if (!it->is_regular_file(ec) || it->path().filename() != name)
continue;
const auto t = fs::last_write_time(it->path(), ec);
if (!best || t > when) { best = it->path(); when = t; }
}
return best;
}
void write_executable(const fs::path& file, std::string_view content) {
write_into(file.parent_path(), file.filename().string(), content);
std::error_code ec;
fs::permissions(file, fs::perms::owner_all | fs::perms::group_read | fs::perms::group_exec |
fs::perms::others_read | fs::perms::others_exec, ec);
}
e2e::outcome run(const fs::path& program, std::vector<std::string> args, const fs::path& cwd,
std::vector<std::pair<std::string, std::optional<std::string>>> env) {
e2e::command c;
c.argv.push_back(program.string());
for (auto& a : args) c.argv.push_back(std::move(a));
c.cwd = cwd;
c.env = std::move(env);
return as_text(e2e::run(std::move(c)));
}
namespace {
// A shell's `*` within one name; no leading dot unless the pattern has one.
bool wildcard(std::string_view pattern, std::string_view name) {
if (name.starts_with('.') && !pattern.starts_with('.'))
return false;
std::size_t p = 0, n = 0, star = std::string_view::npos, mark = 0;
while (n < name.size()) {
if (p < pattern.size() && pattern[p] == '*') { star = p++; mark = n; }
else if (p < pattern.size() && pattern[p] == name[n]) { ++p; ++n; }
else if (star != std::string_view::npos) { p = star + 1; n = ++mark; }
else return false;
}
while (p < pattern.size() && pattern[p] == '*') ++p;
return p == pattern.size();
}
} // namespace
std::vector<fs::path> glob(const fs::path& root, std::string_view pattern) {
std::vector<fs::path> level{root};
for (auto part : std::views::split(pattern, '/')) {
const std::string_view component(part.begin(), part.end());
if (component.empty())
continue;
std::vector<fs::path> next;
std::error_code ec;
for (const auto& dir : level) {
if (!component.contains('*')) {
if (fs::exists(dir / component, ec))
next.push_back(dir / component);
continue;
}
if (!fs::is_directory(dir, ec))
continue;
for (const auto& e : fs::directory_iterator(dir, fs::directory_options::skip_permission_denied, ec))
if (wildcard(component, e.path().filename().string()))
next.push_back(e.path());
}
level = std::move(next);
}
std::ranges::sort(level);
return level;
}
// ---- readings --------------------------------------------------------------------------------------
std::string read_file(const fs::path& file) {
std::ifstream in(file, std::ios::binary);
return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
}
std::vector<std::string> lines_with(std::string_view text, std::string_view needle) {
std::vector<std::string> out;
for (auto line : std::views::split(text, '\n')) {
std::string_view l(line.begin(), line.end());
if (l.ends_with('\r')) l.remove_suffix(1);
if (l.find(needle) != std::string_view::npos)
out.emplace_back(l);
}
return out;
}
std::vector<std::string> file_lines_with(const fs::path& file, std::string_view needle) {
return lines_with(read_file(file), needle);
}
nlohmann::json json(std::string_view text) {
auto whole = nlohmann::json::parse(text, nullptr, false);
if (!whole.is_discarded())
return whole;
for (auto line : std::views::split(text, '\n')) {
auto one = nlohmann::json::parse(std::string_view(line.begin(), line.end()), nullptr, false);
if (!one.is_discarded())
return one;
}
return nlohmann::json{};
}
nlohmann::json json_file(const fs::path& file) { return json(read_file(file)); }
std::vector<nlohmann::json> json_lines(std::string_view text) {
std::vector<nlohmann::json> out;
for (auto line : std::views::split(text, '\n')) {
std::string_view l(line.begin(), line.end());
if (l.empty() || l.front() != '{')
continue;
auto one = nlohmann::json::parse(l, nullptr, false);
if (!one.is_discarded() && one.is_object())
out.push_back(std::move(one));
}
return out;
}
namespace {
std::vector<std::string_view> split_lines(std::string_view text) {
std::vector<std::string_view> out;
for (auto line : std::views::split(text, '\n')) {
std::string_view l(line.begin(), line.end());
if (l.ends_with('\r')) l.remove_suffix(1);
out.push_back(l);
}
return out;
}
std::string tail_of(std::string_view text) {
constexpr std::size_t keep = 3000;
return std::string(text.size() > keep ? text.substr(text.size() - keep) : text);
}
std::string lower(std::string_view s) {
std::string r(s);
for (auto& ch : r) ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
return r;
}
bool any_line(std::string_view text, std::string_view pattern) {
const std::regex re{std::string(pattern)};
for (auto l : split_lines(text))
if (std::regex_search(l.begin(), l.end(), re))
return true;
return false;
}
} // namespace
mcpplibs::mtest::comparison has_line(std::string_view text, std::string_view pattern) {
return {any_line(text, pattern), "has_line", std::format("a line matching /{}/", pattern), tail_of(text)};
}
mcpplibs::mtest::comparison no_line(std::string_view text, std::string_view pattern) {
return {!any_line(text, pattern), "no_line", std::format("no line matching /{}/", pattern), tail_of(text)};
}
mcpplibs::mtest::comparison lacks(std::string_view text, std::string_view needle) {
return {!text.contains(needle), "lacks", std::format("text without \"{}\"", needle), tail_of(text)};
}
mcpplibs::mtest::comparison contains_nocase(std::string_view text, std::string_view needle) {
return {lower(text).contains(lower(needle)), "contains_nocase",
std::format("text containing \"{}\" (any case)", needle), tail_of(text)};
}
mcpplibs::mtest::comparison has_line_nocase(std::string_view text, std::string_view pattern) {
const std::regex re{std::string(pattern), std::regex::ECMAScript | std::regex::icase};
bool held = false;
for (auto l : split_lines(text))
held = held || std::regex_search(l.begin(), l.end(), re);
return {held, "has_line_nocase", std::format("a line matching /{}/i", pattern), tail_of(text)};
}
std::string last_line(std::string_view text) {
auto lines = split_lines(text);
while (!lines.empty() && lines.back().empty()) lines.pop_back();
return lines.empty() ? std::string{} : std::string(lines.back());
}
std::string last_starting(std::string_view text, std::string_view prefix) {
std::string found;
for (auto l : split_lines(text))
if (l.starts_with(prefix)) found = std::string(l);
return found;
}
std::size_t count_matching(std::string_view text, std::string_view pattern) {
const std::regex re{std::string(pattern)};
return static_cast<std::size_t>(std::ranges::count_if(split_lines(text), [&](auto l) { return std::regex_search(l.begin(), l.end(), re); }));
}
std::size_t count_lines(std::string_view text, std::string_view needle) {
return static_cast<std::size_t>(std::ranges::count_if(split_lines(text), [&](auto l) { return l.contains(needle); }));
}
std::optional<std::vector<std::string>> cdb_arguments(const fs::path& cdb, std::string_view file_suffix) {
std::error_code ec;
if (!fs::is_regular_file(cdb, ec))
return std::nullopt;
const auto doc = nlohmann::json::parse(read_file(cdb), nullptr, false);
if (doc.is_discarded() || !doc.is_array())
return std::nullopt;
for (const auto& e : doc) {
auto file = e.value("file", std::string{});
std::ranges::replace(file, '\\', '/');
if (!file.ends_with(file_suffix))
continue;
std::vector<std::string> words;
if (e.contains("arguments") && e["arguments"].is_array()) {
for (const auto& w : e["arguments"]) words.push_back(w.get<std::string>());
} else {
for (auto w : std::views::split(std::string_view(e.value("command", std::string{})), ' '))
if (!std::string_view(w.begin(), w.end()).empty()) words.emplace_back(w.begin(), w.end());
}
return words;
}
return std::nullopt;
}
std::vector<std::string> ninja_log_outputs(const fs::path& build_dir) {
std::vector<std::string> out;
for (auto l : split_lines(read_file(build_dir / ".ninja_log"))) {
if (l.starts_with('#'))
continue;
std::vector<std::string_view> cols;
for (auto c : std::views::split(l, '\t')) cols.emplace_back(c.begin(), c.end());
if (cols.size() >= 4)
out.emplace_back(cols[3]);
}
return out;
}
// ---- executables -------------------------------------------------------------------------------------
namespace {
template <class T>
T get(const std::string& b, std::size_t at, bool big = false) {
T v{};
if (at + sizeof(T) > b.size())
return v;
std::memcpy(&v, b.data() + at, sizeof(T));
if (big) {
T r{};
for (std::size_t i = 0; i < sizeof(T); ++i)
r = static_cast<T>((r << 8) | static_cast<unsigned char>(b[at + i]));
return r;
}
return v;
}
std::string cstring(const std::string& b, std::size_t at) {
if (at >= b.size())
return {};
const auto end = b.find('\0', at);
return b.substr(at, end == std::string::npos ? std::string::npos : end - at);
}
void read_elf(const std::string& b, header& h) {
h.kind = format::elf;
h.wide = b.size() > 4 && b[4] == 2;
h.elf_type = get<std::uint16_t>(b, 16);
h.machine = get<std::uint16_t>(b, 18);
const std::uint64_t phoff = h.wide ? get<std::uint64_t>(b, 32) : get<std::uint32_t>(b, 28);
const std::uint16_t phentsize = get<std::uint16_t>(b, h.wide ? 54 : 42);
const std::uint16_t phnum = get<std::uint16_t>(b, h.wide ? 56 : 44);
std::uint64_t dyn_off = 0, dyn_size = 0;
struct load { std::uint64_t vaddr, offset, filesz; };
std::vector<load> loads;
for (std::uint16_t i = 0; i < phnum; ++i) {
const std::size_t p = static_cast<std::size_t>(phoff) + std::size_t(i) * phentsize;
const auto type = get<std::uint32_t>(b, p);
const std::uint64_t offset = h.wide ? get<std::uint64_t>(b, p + 8) : get<std::uint32_t>(b, p + 4);
const std::uint64_t vaddr = h.wide ? get<std::uint64_t>(b, p + 16) : get<std::uint32_t>(b, p + 8);
const std::uint64_t filesz = h.wide ? get<std::uint64_t>(b, p + 32) : get<std::uint32_t>(b, p + 16);
if (type == 3) { // PT_INTERP
h.elf_interpreter = true;
h.interpreter = cstring(b, static_cast<std::size_t>(offset));
} else if (type == 2) { // PT_DYNAMIC
dyn_off = offset;
dyn_size = filesz;
} else if (type == 1) {
loads.push_back({vaddr, offset, filesz});
}
}
if (!dyn_size)
return;
const std::size_t entry = h.wide ? 16 : 8;
std::uint64_t strtab = 0;
std::vector<std::uint64_t> needed;
std::vector<std::uint64_t> paths;
std::uint64_t soname = 0, rpath = 0;
bool has_soname = false;
for (std::uint64_t at = dyn_off; at + entry <= dyn_off + dyn_size; at += entry) {
const std::int64_t tag = h.wide ? get<std::int64_t>(b, at) : get<std::int32_t>(b, at);
const std::uint64_t val = h.wide ? get<std::uint64_t>(b, at + 8) : get<std::uint32_t>(b, at + 4);
if (tag == 0) break;
if (tag == 5) strtab = val;
else if (tag == 1) needed.push_back(val);
else if (tag == 14) { soname = val; has_soname = true; }
else if (tag == 29 || tag == 15) {
paths.push_back(val);
(tag == 15 ? h.elf_rpath : h.elf_runpath) = true;
if (tag == 15) rpath = val;
}
}
// The string table's address, as a file offset.
std::uint64_t str_off = strtab;
for (const auto& l : loads)
if (strtab >= l.vaddr && strtab < l.vaddr + l.filesz)
str_off = strtab - l.vaddr + l.offset;
for (auto n : needed)
h.needed.push_back(cstring(b, static_cast<std::size_t>(str_off + n)));
for (auto p : paths) {
if (!h.runpath.empty()) h.runpath += ':';
h.runpath += cstring(b, static_cast<std::size_t>(str_off + p));
}
if (has_soname)