-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwix.cppm
More file actions
964 lines (900 loc) · 48.1 KB
/
Copy pathwix.cppm
File metadata and controls
964 lines (900 loc) · 48.1 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
// mcpp.dist.wix -- an MSI from a linked program, and a definition this member
// renders around it.
//
// WHY THIS IS NEITHER A RULE NOR A TOOL. A rule states how a translation unit
// is compiled by a compiler mcpp does not drive. A tool states something the
// build program needs that no compiler performs, and does it while the
// program runs. This member does neither: it consumes a LINK OUTPUT and
// produces something a user installs. That is the third category `dist/
// appimage.cppm` establishes, and the prefix says which of the three
// questions a member answers -- a consumer reading `rules-wix` would expect a
// compiler and a translation unit, and there is neither.
//
// THE ENGINE HOLDS THE DISPATCH AND NOT THE FORMAT. `mcpp pack --format msi`
// finds the package that declared the name and hands it the same graph
// mechanism every other format uses; nothing about WiX's schema, its
// preprocessor, or its table model is in mcpp. Binding any of it there would
// couple an mcpp release to a release mcpp does not control -- WiX 4, 5 and 6
// are three such releases sharing one schema, and this member already has to
// track which one it is talking to without the engine's help.
//
// NAME THE INPUT; DO NOT HARVEST A DIRECTORY. This is the load-bearing
// decision in this file, and it is measured rather than argued. An earlier
// working implementation of this exact step bound a directory and harvested
// it -- `-bindpath Application=bin` -- and let WiX's own harvester decide what
// went in the `File` table. When that bind path resolved to nothing on
// Windows, wix produced a **valid, empty, 52 KB installer with no diagnostic
// at all**: no missing-file error, no empty-harvest warning, an exit code of
// zero. The rule this produces: a path that RESOLVES TO NOTHING is silent,
// and a NAMED INPUT that is missing is an error. `${mcpp.target_file:<name>}`
// is what gives this member the second shape instead of the first -- a build
// program is told neither the triple nor the fingerprint that produced the
// path, and the engine refuses an unknown target name rather than expanding
// it to an empty string -- so the program arrives as that placeholder and
// never as a directory this member goes looking through.
//
// THE STAGED TREE IS READ, BUT NEVER HARVESTED. The program arrives as the
// placeholder above; the files `mcpp pack` staged beside it -- deployed data,
// resolved DLLs -- are enumerated while the tree exists and named one by one
// (`staged_files_for`), so the rule above keeps holding for them too.
// `mcpp pack --format msi` reports as the distributable whatever artifact
// action the REQUEST introduced, so a member that names its files and no
// directory needs nothing extra to be recognised. An earlier engine
// revision asked the narrower question -- which action named
// `${mcpp.stage_dir}` -- and refused this member for following section 6's
// guidance, which is why the engine's criterion is presence in the dispatch
// pass rather than a property of the member.
//
// THE PROGRAM'S PATH CROSSES TWO SUBSTITUTION PASSES, AND THAT IS WHY IT IS A
// WiX VARIABLE AND NOT LITERAL TEXT. `${mcpp.stage_dir}` and
// `${mcpp.target_file:<name>}` are interpolated by the ENGINE, and only
// inside an action's own argv -- not inside a file this build program happens
// to write to disk, which is why the `.wxs` below cannot simply spell the
// program's path out. So the path is carried in the argv, where the engine's
// substitution applies (`-d Executable=${mcpp.target_file:<target>}`), as a
// WiX preprocessor variable; the `.wxs` then references `$(Executable)`,
// which is WiX's OWN substitution, run later, when `wix build` itself
// executes. Two passes, chained: the engine resolves the argv token before
// the command runs, and wix resolves its own token while it runs.
//
// WHERE THE TOOL COMES FROM. A member locates its tool through a declared
// payload and nothing else, so the installer a build produces depends on a
// declaration in a manifest rather than on what a machine happens to hold.
// `dist-appimage` has always done this; an earlier revision of this member
// searched `MCPP_WIX` and `PATH` instead, on the belief that WiX could not be
// redistributed. That belief was wrong, measured 2026-09-11 against
// `https://api.nuget.org/v3-flatcontainer/wix/6.0.2/wix.6.0.2.nupkg`: the
// package is anonymously fetchable and immutable, the software is under the
// Microsoft Reciprocal License, and its `OSMFEULA.txt` states that "the
// Software's source code is licensed to User under the OSI License and
// remains freely distributable". `xim:wix` (5.0.2) is in the index and is
// what this member declares under `[target.windows.feature-xlings.dist-wix]`.
//
// The payload is `tool/tools/net6.0/any/wix.exe`, a framework-dependent .NET 6
// executable. The .NET runtime is a Windows component with its own installer;
// the recipe deliberately does not pretend to own it, and neither does this
// member: `wix --version` names the missing runtime itself. That is the one
// host dependency left on this path, and it is of the kind the design admits,
// a proprietary runtime that exists only where it is installed.
//
// A host lookup therefore exists only where nothing can be shipped, and WiX is
// no longer such a case. `options::tool` remains for a project that builds the
// tool itself.
//
// `--format setup` IS A BURN BUNDLE THAT CHAINS THE MSI. Two actions: the MSI
// above, and a second `wix build` over a bundle definition whose `<Chain>` holds
// that MSI and whose user interface is WiX's stock bootstrapper application
// (`bal:WixStandardBootstrapperApplication`). The stock application is an
// extension, `WixToolset.BootstrapperApplications.wixext`, which `xim:wix`
// carries from 5.0.2-1 and which `wix build` loads by path (`-ext`); without it
// the bundle is refused (WIX0200, measured on windows-2022 by xim-pkgindex's
// install check). The bundle is written as `<product_name>-<arch>.exe` and never
// as `setup.exe`, a name `wix` refuses (WIX0388: Windows loads compatibility
// shims into an executable named like an installer). A project with its own
// bootstrapper application supplies its own bundle definition.
module;
#include <cstdio>
export module mcpp.dist.wix;
import std;
import mcpp;
import mcpp.plugins;
// Nothing here uses `std::println`, and that is not a style choice: both of
// its overloads reach into the libc++ dylib for symbols macOS 14 does not
// ship, so a member that printed with it compiled and then failed to link.
// `std::format` is header-only. The full measurement is in `rules/spirv.cppm`.
// This member never runs on macOS, but it is compiled as a host module
// everywhere `mcpp-plugins` is built, `tests/all-rules-compile` included, so
// the same rule applies to it.
export namespace mcpp::dist::wix {
// ─── Options ───────────────────────────────────────────────────────────────
struct options {
// The program target this MSI wraps. Empty means the package name, which
// is the target `mcpp pack` itself selects by convention.
std::string target;
// `Package/@Name`. Empty means the target name, then the package name,
// then "app" -- the same fallback chain `dist/appimage.cppm` uses for its
// own app name, so a project that names nothing still gets one answer
// rather than an MSI with a blank product name.
std::string product_name;
// `Package/@Manufacturer`. Empty means the first of `package_authors()`
// (';'-separated), then `package_namespace()`, then a literal fallback --
// see `manufacturer_for` for why a final fallback exists at all: WiX
// requires this attribute to be non-empty.
std::string manufacturer;
// `Package/@Version`, in the project's OWN numbering, used as given with
// no conversion. Set this when `[package] version` is not already an MSI
// version WiX will accept (see `msi_version_from` for what mcpp's own
// four-segment date version needs done to it, which this member does
// automatically when this option is left empty).
std::string version;
// `Package/@UpgradeCode`, a literal `{GUID}`. Empty derives one
// deterministically from `package_namespace()` and `package_name()`; see
// `upgrade_code_for` for why determinism is the requirement, not merely a
// convenience.
std::string upgrade_code;
// A project-supplied `.wxs` that wins over the one this member generates.
// It must reference `$(Executable)` the same way the generated
// definition does if it wants the built program named at all -- this
// member always passes that one variable through `-d`, generated
// definition or not, because that is the one value this build program
// cannot bake in as literal text (see the header comment).
//
// `$(Executable)`, NOT `$(var.Executable)`, AND THE DIFFERENCE IS A
// MEASUREMENT RATHER THAN A READING. WiX's own documentation spells a
// `-d` define as `$(var.Name)`, which is v3's form, and that is what this
// member first generated. A working implementation that is green on
// Windows CI uses the bare form -- HuxerUI's
// `mcpp/huxerui-build-rules/wix/Package.wxs.in`, `<File
// Source="$(Executable)" ...>`, against the same `-d Executable=` argv
// this member builds. Neither spelling could be run here, so the one with
// a measurement behind it is the one shipped.
//
// The rest of the staged tree reaches a project definition the same way it
// reaches the generated one: `wix` always compiles the `StagedFiles`
// component group this member writes beside the definition
// (`staged_document`), and a definition that declares a directory with the
// Id `INSTALLFOLDER` installs those files with
// `<ComponentGroupRef Id="StagedFiles" />`.
std::string wxs;
// An explicit `wix` wins over the declared payload. Set it to pin a build
// other than `xim:wix`, for instance one the project compiled itself.
std::string tool;
// Where the produced file lands. Empty means
// `<out_dir>/<product_name>-<arch>.msi`.
std::string output;
// `--format setup`. `bundle_wxs` is a project-supplied bundle definition
// that wins over the generated one; it receives the MSI's path as the
// preprocessor variable `$(Msi)`. `license_url` is the stock application's
// `LicenseUrl`; empty hides the licence link. `extension` names the
// `WixToolset.BootstrapperApplications.wixext.dll` to load, and empty means
// the one `xim:wix` carries. `bundle_output` is where the bundle lands;
// empty means `<out_dir>/<product_name>-<arch>.exe`.
std::string bundle_wxs;
std::string license_url;
std::string extension;
std::string bundle_output;
// The files a project-supplied `wxs` (`inputs`) or `bundle_wxs`
// (`bundle_inputs`) names beyond what this member passes it -- an icon, a
// bootstrapper application and its payloads -- declared as inputs of the
// action that reads them, so a change to one rebuilds the installer. WiX
// reads what the definition names whether or not it is declared here; an
// undeclared file is only missing from the build graph.
std::vector<std::string> inputs;
std::vector<std::string> bundle_inputs;
std::string out_dir = std::string(mcpp::out_dir());
};
// ─── The plan ──────────────────────────────────────────────────────────────
// What this member would submit, without submitting it.
//
// A PLAN AND A SUBMIT, BECAUSE A DISTRIBUTABLE IS THE LAST THING BEFORE A
// USER'S HANDS. It is therefore the part of a build most likely to need a
// project-specific edit -- a second file in the `.wxs`, a UI sequence, a
// launch condition -- and `generate()` being exactly `submit(plan_for())` is
// what keeps such an edit from becoming a reimplementation of this member.
struct plan {
// False when this build is not `mcpp pack --format msi`, which is every
// ordinary build. `reason` then says which of the several ways.
bool applies = false;
std::string reason;
std::string output; // the .msi path
std::string wxs_path; // generated or project-supplied
std::string target_name; // for the opportunistic size probe below
std::vector<std::string> argv;
std::vector<std::string> inputs;
// `--format setup` only: the bundle that chains the MSI above. Empty
// otherwise.
std::string bundle_output;
std::string bundle_wxs_path;
std::vector<std::string> bundle_argv;
std::vector<std::string> bundle_inputs;
// `<out_dir>/<product_name>-staged.wxs`: the `StagedFiles` component group
// naming every file `mcpp pack` staged beside the program, one entry per
// file (see `staged_files_for`).
std::string staged_wxs_path;
std::vector<std::string> staged_files;
explicit operator bool() const { return applies; }
};
// ─── Internals ─────────────────────────────────────────────────────────────
inline bool is_file(const std::string& p) {
std::error_code ec;
return !p.empty() && std::filesystem::is_regular_file(p, ec);
}
// Written only when the bytes differ, for the reason `dist/appimage.cppm`
// gives: rewriting identical bytes moves the mtime, and a moved mtime on a
// declared input is indistinguishable from a changed one -- so a second pack
// of an unchanged project would rebuild the MSI.
inline bool write_if_different(const std::filesystem::path& path,
std::string_view bytes) {
std::error_code ec;
std::filesystem::create_directories(path.parent_path(), ec);
if (std::ifstream in(path, std::ios::binary); in) {
std::string old((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
if (old == bytes) return true;
}
std::ofstream out(path, std::ios::binary | std::ios::trunc);
if (!out) return false;
out.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
return static_cast<bool>(out);
}
// Records a refusal on stderr and as a `mcpp::warning`. A member that refuses
// submits no action and its build program exits 0, and the engine discards the
// output of a build program that succeeded; its own error, "no action claimed
// --format 'msi'", names no reason. The warning channel is one line per
// directive, so line breaks are folded into spaces.
inline plan& refuse(plan& p, std::string reason, const std::string& message) {
std::cerr << message << '\n';
std::string folded;
folded.reserve(message.size());
bool space = false;
for (std::size_t i = 0; i < message.size(); ++i) {
const char c = message[i];
if (c == '\n' || c == '\r') { space = true; continue; }
if (space) {
if (c == ' ') continue;
folded += ' ';
space = false;
}
folded += c;
}
mcpp::warning(folded.c_str());
p.reason = std::move(reason);
return p;
}
inline std::string target_for(const options& opt) {
if (!opt.target.empty()) return opt.target;
const char* n = mcpp::package_name();
return (n && *n) ? std::string(n) : std::string();
}
inline std::string product_name_for(const options& opt) {
if (!opt.product_name.empty()) return opt.product_name;
if (!opt.target.empty()) return opt.target;
const char* n = mcpp::package_name();
return (n && *n) ? std::string(n) : std::string("app");
}
inline std::string first_before(std::string_view s, char sep) {
auto pos = s.find(sep);
return std::string(pos == std::string_view::npos ? s : s.substr(0, pos));
}
// A FINAL FALLBACK THAT DOES NOT EXIST FOR appimage's DESKTOP `Comment=`.
//
// An AppImage's desktop entry tolerates an empty `Comment=`; WiX does not
// tolerate an empty `Manufacturer`, so this chain ends in a literal rather
// than in an empty string the way `dist/appimage.cppm`'s optional fields do.
inline std::string manufacturer_for(const options& opt) {
if (!opt.manufacturer.empty()) return opt.manufacturer;
if (const char* a = mcpp::package_authors(); a && *a) {
if (auto first = first_before(a, ';'); !first.empty()) return first;
}
if (const char* ns = mcpp::package_namespace(); ns && *ns) return ns;
return "Unknown";
}
// WiX's own architecture vocabulary, from the target mcpp resolved. Refused
// for anything else rather than guessed: an MSI built for the wrong
// architecture installs and then fails to run, with nothing in this build's
// own log pointing back at the guess that produced it.
inline std::string wix_arch_for(const std::string& arch) {
if (arch == "x86_64") return "x64";
if (arch == "aarch64") return "arm64";
return {};
}
// Splits "a.b.c.d" into unsigned fields, or an empty vector for anything that
// is not purely digits separated by single dots -- including a leading,
// trailing or doubled dot. A caller that gets an empty vector refuses by
// NAMING the string, rather than this function throwing through a build
// program the engine would then have to diagnose generically.
inline std::vector<unsigned long> numeric_fields(std::string_view s) {
std::vector<unsigned long> out;
if (s.empty()) return out;
std::size_t i = 0;
while (i <= s.size()) {
auto dot = s.find('.', i);
auto part = s.substr(i, dot == std::string_view::npos ? s.size() - i : dot - i);
if (part.empty()) return {};
unsigned long v = 0;
for (char c : part) {
if (c < '0' || c > '9') return {};
v = v * 10 + static_cast<unsigned long>(c - '0');
}
out.push_back(v);
if (dot == std::string_view::npos) break;
i = dot + 1;
}
return out;
}
struct msi_version { std::string text; bool lossy = false; bool ok = false; };
// MSI PACKS ProductVersion INTO Major.Minor.Build WITH HARD PER-FIELD
// CEILINGS -- 255, 255, 65535 -- because Windows Installer stores the three
// fields in a single 32-bit integer (8+8+16 bits). WiX enforces the same
// ceiling at compile time, error CNDL0242 ("Invalid product version"). That
// is documented Windows Installer and WiX behaviour, not something measured
// on this host: wix does not run on Linux, so nothing here has produced or
// rejected a real MSI. A raw calendar year overflows the first field by a
// factor of eight, so mcpp's own `YYYY.M.D.N` convention cannot be copied
// into Major.Minor.Build positionally -- and Windows Installer's comparison
// ignores whatever the fourth field holds regardless, so the release counter
// cannot simply ride along as a fourth field either.
//
// The fields are therefore RE-PACKED rather than truncated:
//
// Major = year modulo 100 -- wraps every century; always under 255
// Minor = month -- 1..12 for mcpp's own scheme, clamped
// Build = day * 1000 + counter -- keeps SAME-DAY releases ordered
//
// This repository has itself shipped 2026.9.10.1 and 2026.9.10.2 -- two
// releases on one calendar day -- so folding the day and the release counter
// into the one field Windows Installer actually compares is not a
// hypothetical: a naive Major.Minor.Build = Year.Month.Day mapping would have
// made those two collide as "the same version", and an upgrade would need
// `AllowSameVersionUpgrades` just to be recognised as one. What this loses:
// the day and the release counter are no longer independently readable from
// the MSI version the way they are from `package_version()`, and a project
// shipping past the year 2125 loses century information this scheme wraps at
// -- 2026 and 2126 both become Major 26.
//
// A version that is not already four numeric dotted fields is assumed to
// already be MSI-shaped -- an ordinary project version such as "1.2.3" -- and
// is passed through with only the same per-field ceiling applied, because
// nothing here knows it is a date, and re-packing it would invent structure
// that is not there.
inline msi_version msi_version_from(std::string_view v) {
msi_version out;
auto f = numeric_fields(v);
if (f.empty()) return out;
out.ok = true;
if (f.size() >= 4) {
unsigned long major = f[0] % 100;
unsigned long minor = f[1] > 255 ? 255 : f[1];
unsigned long build = f[2] * 1000 + f[3];
if (build > 65535) build = 65535;
out.text = std::format("{}.{}.{}", major, minor, build);
out.lossy = true;
} else {
static constexpr unsigned long kCaps[3] = {255, 255, 65535};
bool clamped = false;
std::string joined;
for (std::size_t i = 0; i < f.size(); ++i) {
unsigned long v2 = f[i];
if (v2 > kCaps[i]) { v2 = kCaps[i]; clamped = true; }
if (i) joined += '.';
joined += std::to_string(v2);
}
out.text = joined;
out.lossy = clamped;
}
return out;
}
// FNV-1a, run twice with different seeds to produce 128 bits. Chosen over
// `std::hash<std::string>` because `std::hash` is not specified to produce
// the same digest across standard library implementations, versions, or even
// process runs -- and the one property an UpgradeCode needs for the whole
// life of a product is to be the SAME value every time this identity string
// is hashed, on whatever machine and whatever toolchain builds it. A GUID
// that silently changed because a CI runner's C++ runtime was upgraded would
// present Windows Installer with what looks like an unrelated product, with
// nothing in this build's log pointing at the cause -- exactly the failure
// category the rest of this file exists to refuse.
inline std::uint64_t fnv1a64(std::string_view s, std::uint64_t seed) {
std::uint64_t h = seed;
for (unsigned char c : s) { h ^= c; h *= 0x100000001b3ULL; }
return h;
}
// A hash formatted as a GUID, not an RFC 4122 version-5 UUID -- that
// specifies SHA-1 over a namespace and a name, and nothing here claims that
// stronger guarantee. What is claimed is narrower and is all this needs: the
// same identity string always produces the same 16 bytes. The version and
// variant nibbles below are set anyway, for the benefit of any tool that
// validates a GUID's structure rather than only its punctuation; wix itself
// only parses the punctuation.
inline std::string upgrade_code_for(const std::string& identity) {
const std::uint64_t hi = fnv1a64(identity, 0x9e3779b97f4a7c15ULL);
const std::uint64_t lo = fnv1a64(identity, 0xcbf29ce484222325ULL);
unsigned char b[16];
for (int i = 0; i < 8; ++i) b[i] = static_cast<unsigned char>(hi >> (56 - 8 * i));
for (int i = 0; i < 8; ++i) b[8 + i] = static_cast<unsigned char>(lo >> (56 - 8 * i));
b[6] = static_cast<unsigned char>((b[6] & 0x0F) | 0x50); // version nibble
b[8] = static_cast<unsigned char>((b[8] & 0x3F) | 0x80); // RFC 4122 variant
static const char* kHex = "0123456789ABCDEF";
std::string out = "{";
for (int i = 0; i < 16; ++i) {
if (i == 4 || i == 6 || i == 8 || i == 10) out += '-';
out += kHex[b[i] >> 4];
out += kHex[b[i] & 0x0F];
}
out += "}";
return out;
}
inline std::string xml_escape(std::string_view s) {
std::string out;
out.reserve(s.size());
for (char c : s) {
switch (c) {
case '&': out += "&"; break;
case '<': out += "<"; break;
case '>': out += ">"; break;
case '"': out += """; break;
default: out += c;
}
}
return out;
}
// Discovery: what the project named, else the declared payload. There is no
// environment tier and no PATH tier -- see the header comment.
inline std::string wix_payload_exe() {
const std::string dir = mcpp::xpkg_dir("xim", "wix");
if (dir.empty()) return {};
// The recipe registers `wix` with this directory as its bindir: wix.exe
// loads `runtimes/win-x64/native` and `x64/burn.exe` from beside itself.
const auto exe = std::filesystem::path(dir) / "tool" / "tools" / "net6.0" / "any" / "wix.exe";
return is_file(exe.string()) ? exe.string() : std::string();
}
inline std::string discover_tool(const options& opt) {
if (!opt.tool.empty()) return opt.tool;
return wix_payload_exe();
}
// The stock bootstrapper application's extension: what the project named, else
// the one `xim:wix` carries beside its tool (5.0.2-1 and later).
inline std::string discover_bal_extension(const options& opt) {
if (!opt.extension.empty()) return opt.extension;
const std::string dir = mcpp::xpkg_dir("xim", "wix");
if (dir.empty()) return {};
const auto dll = std::filesystem::path(dir) / "bal" / "wixext5"
/ "WixToolset.BootstrapperApplications.wixext.dll";
return is_file(dll.string()) ? dll.string() : std::string();
}
// A Burn bundle with WiX's stock bootstrapper application and one package, the
// MSI, named through `$(Msi)` for the reason `$(Executable)` is (the header's
// two substitution passes). The bundle carries its own UpgradeCode, derived
// from the product's identity and distinct from the MSI's: a bundle and the
// package it installs are two products to Windows.
//
// NO TEXT IN THE DOCUMENT MAY HOLD TWO HYPHENS IN A ROW OUTSIDE AN ATTRIBUTE.
// XML forbids `--` inside a comment, and `wix build` refused this document
// when its comment named the command line's `--format` (WIX0104, measured on
// windows-2022); `tests/msi-consumer/check-wix-plan.sh` parses both generated
// documents on every host.
inline std::string bundle_document(const std::string& name, const std::string& manufacturer,
const std::string& version, const std::string& upgrade_code,
const std::string& license_url) {
return std::format(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<Wix xmlns=\"http://wixtoolset.org/schemas/v4/wxs\"\n"
" xmlns:bal=\"http://wixtoolset.org/schemas/v4/wxs/bal\">\n"
" <!-- Generated by mcpp.dist.wix for the setup format. A project with\n"
" its own bootstrapper application supplies options::bundle_wxs,\n"
" which receives the path of the MSI as the variable Msi. -->\n"
" <Bundle Name=\"{0}\" Manufacturer=\"{1}\" Version=\"{2}\" "
"UpgradeCode=\"{3}\">\n"
" <BootstrapperApplication>\n"
" <bal:WixStandardBootstrapperApplication Theme=\"hyperlinkLicense\" "
"LicenseUrl=\"{4}\" />\n"
" </BootstrapperApplication>\n"
" <Chain>\n"
" <MsiPackage SourceFile=\"$(Msi)\" />\n"
" </Chain>\n"
" </Bundle>\n"
"</Wix>\n",
xml_escape(name), xml_escape(manufacturer), xml_escape(version), upgrade_code,
xml_escape(license_url));
}
// THE REST OF THE STAGED TREE, NAMED FILE BY FILE. `mcpp pack` stages the
// program and, beside it, everything the program needs at run time: the files
// a build program deploys (`mcpp::deploy`, `[runtime] deploy`) and the DLLs its
// closure resolved. An installer that carried the program alone installs
// something that cannot find its own data. The header's rule still holds -- a
// directory is never handed to WiX's harvester, which turns a path resolving
// to nothing into a valid empty installer -- so each file is enumerated here,
// while the staged tree exists, and named as a `<File Source>`, which is an
// error when it is missing.
//
// BESIDE THE PROGRAM, WHEREVER THAT IS. A PE program is staged at the root of
// the tree with its DLLs and deployed files around it (the Win32 loader looks
// beside the executable, and that is the layout mcpp's `.zip` carries); every
// other program under `bin/`. Measured on windows-2022 with mcpp 2026.9.14.2:
// the root. The directory the program was found in is the one enumerated, and
// at the root the three files mcpp writes there for an archive's reader --
// `README.md`, `LICENSE` and `HOST-REQUIREMENTS` -- are not installed, as a
// CMake install of the same program does not install them.
//
// Returned as (absolute source, install path relative to INSTALLFOLDER),
// sorted, the program itself excluded: `$(Executable)` already names it.
inline std::vector<std::pair<std::string, std::string>>
staged_files_for(const std::string& stage, const std::string& target) {
std::vector<std::pair<std::string, std::string>> files;
if (stage.empty()) return files;
std::error_code ec;
const std::filesystem::path root(stage);
std::filesystem::path beside;
for (const std::filesystem::path& dir : { root / "bin", root }) {
if (std::filesystem::is_regular_file(dir / target, ec) ||
std::filesystem::is_regular_file(dir / (target + ".exe"), ec)) {
beside = dir;
break;
}
}
if (beside.empty()) return files;
const bool atRoot = beside == root;
for (auto it = std::filesystem::recursive_directory_iterator(beside, ec);
it != std::filesystem::recursive_directory_iterator(); it.increment(ec)) {
if (ec) break;
if (!it->is_regular_file(ec)) continue;
const std::string relative = std::filesystem::relative(it->path(), beside, ec).generic_string();
if (ec || relative.empty()) continue;
if (relative == target || relative == target + ".exe") continue;
if (atRoot && (relative == "README.md" || relative == "LICENSE" || relative == "HOST-REQUIREMENTS"))
continue;
files.emplace_back(it->path().string(), relative);
}
std::sort(files.begin(), files.end(),
[](const auto& a, const auto& b) { return a.second < b.second; });
return files;
}
// The `StagedFiles` component group, always written so a definition can
// reference it whether or not anything was staged. One component per file,
// placed by `Subdirectory` under INSTALLFOLDER, so the installed tree is the
// staged one. A definition that does not reference the group leaves it out of
// the link, as WiX does with any unreferenced fragment.
inline std::string staged_document(const std::vector<std::pair<std::string, std::string>>& files) {
std::string doc =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<Wix xmlns=\"http://wixtoolset.org/schemas/v4/wxs\">\n"
" <!-- Generated by mcpp.dist.wix: every file mcpp pack staged beside the\n"
" program, installed at the same path under INSTALLFOLDER. A\n"
" definition installs them with <ComponentGroupRef Id=\"StagedFiles\" />. -->\n"
" <Fragment>\n"
" <ComponentGroup Id=\"StagedFiles\" Directory=\"INSTALLFOLDER\">\n";
for (const auto& [source, relative] : files) {
std::string subdirectory = std::filesystem::path(relative).parent_path().generic_string();
for (std::size_t i = 0; i < subdirectory.size(); ++i)
if (subdirectory[i] == '/') subdirectory[i] = '\\';
doc += " <Component";
if (!subdirectory.empty()) doc += " Subdirectory=\"" + xml_escape(subdirectory) + "\"";
doc += "><File Source=\"" + xml_escape(source) + "\" /></Component>\n";
}
doc += " </ComponentGroup>\n"
" </Fragment>\n"
"</Wix>\n";
return doc;
}
// A minimal WiX v4/v5/v6 definition: one `Package`, one `Component` carrying
// the program this member wraps, one `Feature` referencing it and the
// `StagedFiles` group beside it (`staged_document`). WiX can
// derive a stable Component GUID from the component's own target path by
// itself when `Component/@Guid` is omitted -- that is why only one GUID is
// minted here rather than two: `UpgradeCode` expresses identity across the
// WHOLE product, across every rebuild, which is ecosystem knowledge
// (`package_namespace()` plus `package_name()`) the compiler has no way to
// see on its own.
//
// `Codepage="65001"` (UTF-8) is stated explicitly because `product_name` and
// `manufacturer` come from project metadata that may not be ASCII, and this
// member has no reason to assume WiX's default matches.
inline std::string wxs_document(const std::string& name, const std::string& manufacturer,
const std::string& version, const std::string& upgrade_code) {
return std::format(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<Wix xmlns=\"http://wixtoolset.org/schemas/v4/wxs\">\n"
" <!-- Generated by mcpp.dist.wix. A project that needs a different\n"
" definition supplies its own through options::wxs; see that\n"
" option's comment for the one variable such a file must still\n"
" reference. -->\n"
" <Package Codepage=\"65001\" Name=\"{0}\" Manufacturer=\"{1}\" "
"Version=\"{2}\" UpgradeCode=\"{3}\">\n"
" <MajorUpgrade DowngradeErrorMessage=\"A newer version of "
"[ProductName] is already installed.\" />\n"
" <StandardDirectory Id=\"ProgramFiles6432Folder\">\n"
" <Directory Id=\"INSTALLFOLDER\" Name=\"{0}\">\n"
" <Component Id=\"MainExecutable\">\n"
" <File Id=\"MainExecutable\" Source=\"$(Executable)\" "
"KeyPath=\"yes\" />\n"
" </Component>\n"
" </Directory>\n"
" </StandardDirectory>\n"
" <Feature Id=\"MainFeature\" Title=\"{0}\" Level=\"1\">\n"
" <ComponentRef Id=\"MainExecutable\" />\n"
" <ComponentGroupRef Id=\"StagedFiles\" />\n"
" </Feature>\n"
" </Package>\n"
"</Wix>\n",
xml_escape(name), xml_escape(manufacturer), xml_escape(version), upgrade_code);
}
// ─── Plan ──────────────────────────────────────────────────────────────────
inline plan plan_for(options opt = {}) {
plan p;
// NOT THIS PASS. Every ordinary build lands here, and the empty
// `pack_format()` is what says so -- see `generate` for why the
// DECLARATION must not be gated the same way.
const std::string requested = mcpp::pack_format();
if (requested != "msi" && requested != "setup") {
p.reason = requested.empty()
? "this build is not packaging"
: std::format("--format {} was requested, not msi or setup", requested);
return p;
}
const bool setup = requested == "setup";
// Windows only, and this is a refusal rather than a silent skip: a user
// who typed `--format msi` on Linux asked for something that does not
// exist there, and the engine has already accepted the value because the
// graph declared it.
if (const std::string os = mcpp::target_os(); os != "windows") {
return refuse(p, "not a Windows target", std::format(
"mcpp.dist.wix: an MSI is a Windows format, and this build targets "
"'{}'.\n"
" use: --format tar, or build for a Windows target",
os.empty() ? "unknown" : os));
}
const std::string target = target_for(opt);
if (target.empty()) {
return refuse(p, "no target", "mcpp.dist.wix: no target to package. Set "
"`options::target` to the program target's name.");
}
const std::string tool = discover_tool(opt);
if (tool.empty()) {
return refuse(p, "wix not found", std::format(
"mcpp.dist.wix: the wix CLI was not found.\n"
" xpkg_dir(\"xim\", \"wix\") answered \"{}\"; the payload's tool is "
"tool/tools/net6.0/any/wix.exe beneath it.\n"
" `xim:wix` is declared by this feature under "
"[target.windows.feature-xlings.dist-wix], so an empty answer means "
"the payload is not installed for this build (mcpp provisions it "
"when the feature is active on a Windows target)\n"
" or set `options::tool` to name one explicitly.",
mcpp::xpkg_dir("xim", "wix")));
}
const std::string hostArch = mcpp::target_arch();
const std::string arch = wix_arch_for(hostArch);
if (arch.empty()) {
return refuse(p, "unknown architecture", std::format(
"mcpp.dist.wix: WiX has no architecture spelling this member "
"knows for '{}'. Known: x86_64 -> x64, aarch64 -> arm64.",
hostArch.empty() ? "unknown" : hostArch));
}
const std::string name = product_name_for(opt);
// THE PRODUCT'S METADATA, read once for whichever definition this member
// generates: the MSI's when the project supplies none, the bundle's under
// `--format setup` when the project supplies none.
const bool generatesMsi = opt.wxs.empty();
const bool generatesBundle = setup && opt.bundle_wxs.empty();
std::string version, manufacturer, identity;
if (generatesMsi || generatesBundle) {
const char* pv = mcpp::package_version();
const std::string rawVersion = !opt.version.empty() ? opt.version
: (pv && *pv ? std::string(pv) : std::string());
if (rawVersion.empty()) {
return refuse(p, "no version", "mcpp.dist.wix: no version to state. Set "
"`[package] version` or `options::version`.");
}
const auto mv = msi_version_from(rawVersion);
if (!mv.ok) {
return refuse(p, "version not numeric", std::format(
"mcpp.dist.wix: '{}' is not a purely numeric, dot-separated "
"version, which is what an MSI's Version attribute requires.",
rawVersion));
}
version = mv.text;
manufacturer = manufacturer_for(opt);
const char* nsC = mcpp::package_namespace();
const char* nmC = mcpp::package_name();
identity = (nsC && *nsC ? std::string(nsC) : std::string())
+ "/" + (nmC && *nmC ? std::string(nmC) : std::string());
}
std::string wxsPath;
if (!generatesMsi) {
if (!is_file(opt.wxs)) {
return refuse(p, "definition file not found", std::format(
"mcpp.dist.wix: the definition file {} was not found", opt.wxs));
}
wxsPath = opt.wxs;
} else {
const std::string upgradeCode = !opt.upgrade_code.empty() ? opt.upgrade_code
: upgrade_code_for(identity);
wxsPath = (std::filesystem::path(opt.out_dir) / (name + ".wxs")).string();
if (!write_if_different(wxsPath, wxs_document(name, manufacturer, version, upgradeCode))) {
return refuse(p, "cannot write definition", std::format("mcpp.dist.wix: cannot write {}", wxsPath));
}
}
p.output = !opt.output.empty() ? opt.output
: (std::filesystem::path(opt.out_dir)
/ std::format("{}-{}.msi", name, arch)).string();
p.wxs_path = wxsPath;
p.target_name = target;
const std::vector<std::pair<std::string, std::string>> staged =
staged_files_for(mcpp::pack_stage_dir(), target);
p.staged_wxs_path = (std::filesystem::path(opt.out_dir) / (name + "-staged.wxs")).string();
if (!write_if_different(p.staged_wxs_path, staged_document(staged))) {
return refuse(p, "cannot write the staged files", std::format("mcpp.dist.wix: cannot write {}", p.staged_wxs_path));
}
for (const auto& file : staged) p.staged_files.push_back(file.first);
const std::string targetFile = std::format("${{mcpp.target_file:{}}}", target);
p.argv = {
tool, "build",
"-arch", arch,
// The one value this build program cannot bake in as literal text --
// see the header comment for why it crosses two substitution passes
// instead.
"-d", "Executable=" + targetFile,
"-o", p.output,
wxsPath,
p.staged_wxs_path,
};
// The program, the definition, the staged-files fragment and each staged
// file it names are what this action reads, so editing any of them
// rebuilds the MSI; `options::inputs` adds what a project's own definition
// names beyond them.
p.inputs = { targetFile, wxsPath, p.staged_wxs_path };
p.inputs.insert(p.inputs.end(), p.staged_files.begin(), p.staged_files.end());
p.inputs.insert(p.inputs.end(), opt.inputs.begin(), opt.inputs.end());
// `--format setup`: the bundle that chains the MSI above.
if (setup) {
const std::string extension = discover_bal_extension(opt);
if (extension.empty()) {
return refuse(p, "bootstrapper application extension not found", std::format(
"mcpp.dist.wix: a bundle with WiX's stock bootstrapper application "
"needs WixToolset.BootstrapperApplications.wixext, and none was found "
"beneath xpkg_dir(\"xim\", \"wix\") = \"{}\" at "
"bal/wixext5/WixToolset.BootstrapperApplications.wixext.dll. "
"xim:wix carries it from 5.0.2-1; or set `options::extension`.",
mcpp::xpkg_dir("xim", "wix")));
}
std::string bundleWxs;
if (!generatesBundle) {
if (!is_file(opt.bundle_wxs)) {
return refuse(p, "bundle definition file not found", std::format(
"mcpp.dist.wix: the bundle definition file {} was not found",
opt.bundle_wxs));
}
bundleWxs = opt.bundle_wxs;
} else {
bundleWxs = (std::filesystem::path(opt.out_dir) / (name + "-bundle.wxs")).string();
const std::string doc = bundle_document(name, manufacturer, version,
upgrade_code_for(identity + "#bundle"),
opt.license_url);
if (!write_if_different(bundleWxs, doc)) {
return refuse(p, "cannot write bundle definition", std::format("mcpp.dist.wix: cannot write {}", bundleWxs));
}
}
p.bundle_output = !opt.bundle_output.empty() ? opt.bundle_output
: (std::filesystem::path(opt.out_dir)
/ std::format("{}-{}.exe", name, arch)).string();
{
std::string leaf = std::filesystem::path(p.bundle_output).filename().string();
for (std::size_t i = 0; i < leaf.size(); ++i)
if (leaf[i] >= 'A' && leaf[i] <= 'Z') leaf[i] = static_cast<char>(leaf[i] - 'A' + 'a');
if (leaf == "setup.exe") {
return refuse(p, "bundle named setup.exe", "mcpp.dist.wix: a bundle named setup.exe is refused by wix "
"(WIX0388: Windows loads compatibility shims into an "
"executable named like an installer). Choose another "
"`options::bundle_output`.");
}
}
p.bundle_wxs_path = bundleWxs;
p.bundle_argv = {
tool, "build",
"-arch", arch,
"-ext", extension,
"-d", "Msi=" + p.output,
"-o", p.bundle_output,
bundleWxs,
};
// The MSI is an input, which is what orders the bundle after it and
// makes the bundle the request's one terminal artifact.
p.bundle_inputs = { p.output, bundleWxs, extension };
p.bundle_inputs.insert(p.bundle_inputs.end(), opt.bundle_inputs.begin(), opt.bundle_inputs.end());
}
p.applies = true;
return p;
}
// ─── Submit ────────────────────────────────────────────────────────────────
inline bool submit(const plan& p) {
if (!p.applies) return true;
mcpp::action a;
a.id = "mcpp.dist.wix";
a.role = "artifact";
a.description = "MSI";
for (auto const& tok : p.argv) a.arg(tok.c_str());
for (auto const& in : p.inputs) a.input(in.c_str());
a.output(p.output.c_str());
a.submit();
if (!p.bundle_argv.empty()) {
mcpp::action b;
b.id = "mcpp.dist.wix.bundle";
b.role = "artifact";
b.description = "BURN BUNDLE";
for (auto const& tok : p.bundle_argv) b.arg(tok.c_str());
for (auto const& in : p.bundle_inputs) b.input(in.c_str());
b.output(p.bundle_output.c_str());
b.submit();
}
// A FLOOR ON THIS MEMBER'S OWN OUTPUT, ON THE SUCCESS PATH -- IN TWO
// HALVES, BECAUSE ONE THING IS ALWAYS MEASURABLE AND THE OTHER IS NOT.
//
// The MSI itself does not exist when this program runs -- wix has not
// been invoked yet, only declared -- so nothing here can open it. What
// this member CAN see: the definition it just wrote or was handed, and,
// opportunistically, a copy of the program inside whatever `mcpp pack`
// staged. Both are best-effort in different ways: the first is exact but
// narrow (it catches an empty definition, not a broken one); the second
// depends on a staging convention this member does not otherwise rely on
// -- see `plan_for`, which never reads the staged tree -- so it is
// skipped rather than refused when nothing recognisable turns up there.
// Neither half can catch a wix invocation that fails, a signature that
// does not verify, or an identity the machine does not have -- those run
// after this program has already exited.
std::string text;
if (std::ifstream in(p.wxs_path, std::ios::binary); in)
text.assign((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
if (text.find("<File") == std::string::npos) {
static char msg[512];
std::snprintf(msg, sizeof msg,
"mcpp.dist.wix: the definition at %s declares no <File> element; "
"the MSI wix builds from it will install nothing",
p.wxs_path.c_str());
mcpp::warning(msg);
}
if (const std::string stage = mcpp::pack_stage_dir(); !stage.empty()) {
std::string found;
for (auto candidate : { stage + "/" + p.target_name,
stage + "/bin/" + p.target_name,
stage + "/" + p.target_name + ".exe",
stage + "/bin/" + p.target_name + ".exe" })
if (is_file(candidate)) { found = candidate; break; }
if (!found.empty()) {
std::error_code ec;
std::uintmax_t bytes = std::filesystem::file_size(found, ec);
// A SIZE BOUND IS DEFENSIBLE HERE AND WAS NOT IN
// `dist/appimage.cppm`, which is worth stating because the two
// look alike. That member measured a whole staged TREE and 16 KB
// was wrong on its first fixture -- a stripped hello-world stages
// at 14999 bytes -- so it counts files instead. This measures ONE
// LINKED PROGRAM, and no linked program is under a kilobyte on any
// platform this member serves. It exists to catch "nothing was
// linked", not to police a size budget.
if (!ec && bytes < 1024u) {
static char msg2[512];
std::snprintf(msg2, sizeof msg2,
"mcpp.dist.wix: %s is %llu bytes, which is implausibly "
"small for a linked program; the MSI may be carrying a "
"stub",
found.c_str(), static_cast<unsigned long long>(bytes));
mcpp::warning(msg2);
}
}
}
return true;
}
// ─── The one call a consumer makes ─────────────────────────────────────────
// DECLARE UNCONDITIONALLY, SUBMIT CONDITIONALLY -- and both halves are here so
// a consumer cannot do one without the other.
//
// The declaration is what lets the engine answer a question the requesting
// build cannot: `mcpp pack --format bogus` names what is available, and
// `--help` says "any format the resolved graph provides". Both read the set
// collected from a pass that asked for nothing. A member that declared only
// when asked still works for its author -- they always pass their own
// format -- and makes the set unknowable for everyone else.
inline bool generate(options opt = {}) {
mcpp::provides_pack_format("msi");
mcpp::provides_pack_format("setup");
return submit(plan_for(std::move(opt)));
}
} // namespace mcpp::dist::wix