-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxpkg-executor.cppm
More file actions
930 lines (839 loc) · 34.1 KB
/
Copy pathxpkg-executor.cppm
File metadata and controls
930 lines (839 loc) · 34.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
module;
export module mcpplibs.xpkg.executor;
import mcpplibs.xpkg;
import mcpplibs.xpkg.lua_stdlib;
import mcpplibs.capi.lua;
import std;
namespace lua = mcpplibs::capi::lua;
namespace fs = std::filesystem;
export namespace mcpplibs::xpkg {
// Slim per-dep export info pre-resolved by xlings: paths are already
// joined with the dep's install_dir, so the Lua side gets ready-to-use
// absolute paths. Only the fields elfpatch.lua actually needs are
// surfaced — additional `exports.*` capabilities (data, build) will be
// injected via separate _RUNTIME tables when those land.
struct DepExport {
std::string loader; // absolute path or empty
std::vector<std::string> libdirs; // absolute paths (already joined)
std::string abi; // e.g. "linux-x86_64-glibc"
};
struct ExecutionContext {
std::string pkg_name, version, platform, arch;
fs::path install_file, install_dir;
fs::path run_dir, xpkg_dir, bin_dir;
fs::path project_data_dir; // project-local data root (empty when no project config)
// `deps_list` retained as the legacy union (runtime ∪ build) for
// backward compat with old install hooks; new code should consult
// `runtime_deps_list` / `build_deps_list` to get the split.
std::vector<std::string> deps_list, args;
std::vector<std::string> runtime_deps_list;
std::vector<std::string> build_deps_list;
// Pre-resolved exports of each runtime dep. Key is the dep spec as
// it appears in runtime_deps_list (e.g. "xim:glibc@2.39"). Only
// deps that actually declare exports show up; missing entries mean
// "this dep declared nothing — fall back to convention".
std::unordered_map<std::string, DepExport> deps_exports;
// The current package's own exports (rule 2 in the predicate trigger).
DepExport self_exports;
std::string subos_sysrootdir;
std::string pkgindex_dir; // package index repo root (for custom module loading)
};
struct HookResult {
bool success = false;
std::string output, error;
std::string version; // non-empty when installed() returns a version string
};
struct XvmOp {
std::string op; // "add" | "remove" | "headers" | "remove_headers"
std::string name;
std::string version;
std::string bindir;
std::string alias;
std::string type; // "program" | "lib"
std::string filename;
std::string binding;
std::string includedir; // for headers/remove_headers ops
std::vector<std::pair<std::string, std::string>> envs; // environment variables
};
struct InstallRequest {
std::string op; // "install" | "remove"
std::string target; // e.g. "scode:linux-headers@5.11.1"
};
enum class HookType { Installed, Build, Install, Config, Uninstall };
} // export namespace mcpplibs::xpkg
// Implementation detail (not exported)
namespace mcpplibs::xpkg::detail {
constexpr std::string_view hook_name(HookType h) {
switch (h) {
case HookType::Installed: return "installed";
case HookType::Build: return "build";
case HookType::Install: return "install";
case HookType::Config: return "config";
case HookType::Uninstall: return "uninstall";
}
return "";
}
// Set a string field on the table at top of stack
void set_string_field(lua::State* L, std::string_view key, std::string_view val) {
lua::pushstring(L, std::string(val).c_str());
lua::setfield(L, -2, std::string(key).c_str());
}
// Register C++ std::filesystem implementations of os.isdir and os.dirs.
// Called after the Lua prelude to override the shell-based versions.
void register_os_funcs(lua::State* L) {
lua::getglobal(L, "os");
if (lua::type(L, -1) != lua::TTABLE) {
lua::pop(L, 1);
lua::newtable(L);
lua::setglobal(L, "os");
lua::getglobal(L, "os");
}
// os.isdir(path) -> bool
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushboolean(L, 0); return 1; }
std::error_code ec;
lua::pushboolean(L, fs::is_directory(fs::path(p), ec) ? 1 : 0);
return 1;
});
lua::setfield(L, -2, "isdir");
// os.dirs(pattern) -> table of absolute dir paths
// Accepts "base/*" style pattern; strips trailing /* to get the base directory.
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* pat = lua::tostring(L, 1);
lua::newtable(L);
if (!pat) return 1;
std::string s(pat);
// Strip trailing /* or \*
if (s.size() >= 2 && s.back() == '*' &&
(s[s.size()-2] == '/' || s[s.size()-2] == '\\')) {
s.pop_back(); s.pop_back();
}
while (!s.empty() && (s.back() == '/' || s.back() == '\\'))
s.pop_back();
fs::path base(s);
std::error_code ec;
if (!fs::is_directory(base, ec)) return 1;
int idx = 1;
for (auto& entry : fs::directory_iterator(base, ec)) {
if (entry.is_directory(ec)) {
lua::pushstring(L, entry.path().string().c_str());
lua::rawseti(L, -2, idx++);
}
}
return 1;
});
lua::setfield(L, -2, "dirs");
// os.cd(dir) -> bool
// Real chdir so that subsequent os.execute / system.exec inherit the new CWD.
// Safe: hook calls are wrapped in ScopedCurrentDir_ which restores CWD on return.
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushboolean(L, 0); return 1; }
std::error_code ec;
fs::current_path(fs::path(p), ec);
lua::pushboolean(L, ec ? 0 : 1);
return 1;
});
lua::setfield(L, -2, "cd");
// os.cp(src, dst) -> bool
// Mimics `cp -a`: when src is a dir and dst is an existing dir,
// copies src as a subdirectory of dst (i.e. dst/src_name/...).
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* src = lua::tostring(L, 1);
const char* dst = lua::tostring(L, 2);
if (!src || !dst) { lua::pushboolean(L, 0); return 1; }
fs::path sp(src), dp(dst);
std::error_code ec;
// cp -a semantics: dir into existing dir → dst/basename(src)/...
if (fs::is_directory(sp, ec) && fs::is_directory(dp, ec))
dp /= sp.filename();
fs::copy(sp, dp,
fs::copy_options::recursive |
fs::copy_options::copy_symlinks |
fs::copy_options::overwrite_existing, ec);
lua::pushboolean(L, ec ? 0 : 1);
return 1;
});
lua::setfield(L, -2, "cp");
// os.trymv(src, dst) -> bool (rename, fallback to copy+remove)
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* s = lua::tostring(L, 1);
const char* d = lua::tostring(L, 2);
if (!s || !d) { lua::pushboolean(L, 0); return 1; }
fs::path src(s), dst(d);
std::error_code ec;
// If dst is existing dir, move into it (unix mv semantics)
if (fs::is_directory(dst, ec)) dst /= src.filename();
fs::rename(src, dst, ec);
if (!ec) { lua::pushboolean(L, 1); return 1; }
// Cross-device: copy + remove
ec.clear();
fs::copy(src, dst,
fs::copy_options::recursive |
fs::copy_options::copy_symlinks |
fs::copy_options::overwrite_existing, ec);
if (ec) { lua::pushboolean(L, 0); return 1; }
fs::remove_all(src, ec);
lua::pushboolean(L, 1);
return 1;
});
lua::setfield(L, -2, "trymv");
// Also set os.mv = os.trymv
lua::getfield(L, -1, "trymv");
lua::setfield(L, -2, "mv");
// os.tryrm(path) -> bool
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushboolean(L, 0); return 1; }
std::error_code ec;
fs::remove_all(fs::path(p), ec);
lua::pushboolean(L, 1);
return 1;
});
lua::setfield(L, -2, "tryrm");
// os.mkdir(path) -> bool
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushboolean(L, 0); return 1; }
std::error_code ec;
fs::create_directories(fs::path(p), ec);
lua::pushboolean(L, ec ? 0 : 1);
return 1;
});
lua::setfield(L, -2, "mkdir");
// os.isfile(path) -> bool
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushboolean(L, 0); return 1; }
std::error_code ec;
lua::pushboolean(L, fs::is_regular_file(fs::path(p), ec) ? 1 : 0);
return 1;
});
lua::setfield(L, -2, "isfile");
// os.iorun(cmd) -> string (capture stdout, discard stderr)
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* cmd = lua::tostring(L, 1);
if (!cmd) { lua::pushstring(L, ""); return 1; }
// Build a temp path for capturing output
std::error_code ec;
auto tmp = fs::temp_directory_path(ec) / ("xpkg_iorun_" +
std::to_string(std::hash<std::string>{}(std::string(cmd) +
std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()))));
std::string full(cmd);
#ifdef _WIN32
full += " 2>nul > \"" + tmp.string() + "\"";
#else
full += " 2>/dev/null > \"" + tmp.string() + "\"";
#endif
std::system(full.c_str());
std::ifstream ifs(tmp);
std::string out;
if (ifs.good()) {
std::ostringstream ss;
ss << ifs.rdbuf();
out = ss.str();
}
ifs.close();
fs::remove(tmp, ec);
lua::pushstring(L, out.c_str());
return 1;
});
lua::setfield(L, -2, "iorun");
lua::pop(L, 1); // pop os table
}
// Register C++-backed fs module into _LIBXPKG_MODULES["fs"].
// Provides filesystem primitives that are missing from the os.* layer:
// symlink creation/reading, file/dir enumeration, single-file copy, etc.
// All functions use std::filesystem — no shell commands.
void register_fs_module(lua::State* L) {
lua::newtable(L); // the fs module table
// fs.symlink(src, dst) -> bool
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* src = lua::tostring(L, 1);
const char* dst = lua::tostring(L, 2);
if (!src || !dst) { lua::pushboolean(L, 0); return 1; }
std::error_code ec;
fs::path sp(src);
if (fs::is_directory(sp, ec))
fs::create_directory_symlink(sp, fs::path(dst), ec);
else
fs::create_symlink(sp, fs::path(dst), ec);
lua::pushboolean(L, ec ? 0 : 1);
return 1;
});
lua::setfield(L, -2, "symlink");
// fs.readlink(path) -> string | nil
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushnil(L); return 1; }
std::error_code ec;
auto target = fs::read_symlink(fs::path(p), ec);
if (ec) { lua::pushnil(L); return 1; }
lua::pushstring(L, target.string().c_str());
return 1;
});
lua::setfield(L, -2, "readlink");
// fs.is_symlink(path) -> bool
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushboolean(L, 0); return 1; }
std::error_code ec;
lua::pushboolean(L, fs::is_symlink(fs::path(p), ec) ? 1 : 0);
return 1;
});
lua::setfield(L, -2, "is_symlink");
// fs.exists(path) -> bool (follows symlinks)
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushboolean(L, 0); return 1; }
std::error_code ec;
lua::pushboolean(L, fs::exists(fs::path(p), ec) ? 1 : 0);
return 1;
});
lua::setfield(L, -2, "exists");
// fs.is_directory(path) -> bool
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushboolean(L, 0); return 1; }
std::error_code ec;
lua::pushboolean(L, fs::is_directory(fs::path(p), ec) ? 1 : 0);
return 1;
});
lua::setfield(L, -2, "is_directory");
// fs.is_file(path) -> bool
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushboolean(L, 0); return 1; }
std::error_code ec;
lua::pushboolean(L, fs::is_regular_file(fs::path(p), ec) ? 1 : 0);
return 1;
});
lua::setfield(L, -2, "is_file");
// fs.mkdir_p(path) -> bool
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushboolean(L, 0); return 1; }
std::error_code ec;
fs::create_directories(fs::path(p), ec);
lua::pushboolean(L, ec ? 0 : 1);
return 1;
});
lua::setfield(L, -2, "mkdir_p");
// fs.remove(path) -> bool (single file or empty dir)
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushboolean(L, 0); return 1; }
std::error_code ec;
lua::pushboolean(L, fs::remove(fs::path(p), ec) ? 1 : 0);
return 1;
});
lua::setfield(L, -2, "remove");
// fs.remove_all(path) -> bool
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushboolean(L, 0); return 1; }
std::error_code ec;
fs::remove_all(fs::path(p), ec);
lua::pushboolean(L, 1);
return 1;
});
lua::setfield(L, -2, "remove_all");
// fs.copy_file(src, dst) -> bool (single file, overwrite)
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* src = lua::tostring(L, 1);
const char* dst = lua::tostring(L, 2);
if (!src || !dst) { lua::pushboolean(L, 0); return 1; }
std::error_code ec;
fs::copy_file(fs::path(src), fs::path(dst),
fs::copy_options::overwrite_existing, ec);
lua::pushboolean(L, ec ? 0 : 1);
return 1;
});
lua::setfield(L, -2, "copy_file");
// fs.entries(dir) -> table of {path, name, type}
// type: "file", "directory", "symlink", "other"
// Non-recursive. Returns full paths.
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* dir = lua::tostring(L, 1);
lua::newtable(L);
if (!dir) return 1;
std::error_code ec;
fs::path dp(dir);
if (!fs::is_directory(dp, ec)) return 1;
int idx = 1;
for (auto& entry : fs::directory_iterator(dp, ec)) {
lua::newtable(L);
lua::pushstring(L, entry.path().string().c_str());
lua::setfield(L, -2, "path");
lua::pushstring(L, entry.path().filename().string().c_str());
lua::setfield(L, -2, "name");
const char* etype = "other";
if (entry.is_symlink(ec)) etype = "symlink";
else if (entry.is_regular_file(ec)) etype = "file";
else if (entry.is_directory(ec)) etype = "directory";
lua::pushstring(L, etype);
lua::setfield(L, -2, "type");
lua::rawseti(L, -2, idx++);
}
return 1;
});
lua::setfield(L, -2, "entries");
// fs.files(dir, recursive?) -> table of file paths
// recursive: optional bool, default false
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* dir = lua::tostring(L, 1);
bool recursive = lua::toboolean(L, 2);
lua::newtable(L);
if (!dir) return 1;
std::error_code ec;
fs::path dp(dir);
if (!fs::is_directory(dp, ec)) return 1;
int idx = 1;
if (recursive) {
for (auto& entry : fs::recursive_directory_iterator(dp, ec)) {
if (entry.is_regular_file(ec)) {
lua::pushstring(L, entry.path().string().c_str());
lua::rawseti(L, -2, idx++);
}
}
} else {
for (auto& entry : fs::directory_iterator(dp, ec)) {
if (entry.is_regular_file(ec)) {
lua::pushstring(L, entry.path().string().c_str());
lua::rawseti(L, -2, idx++);
}
}
}
return 1;
});
lua::setfield(L, -2, "files");
// fs.dirs(dir) -> table of subdirectory paths (non-recursive)
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* dir = lua::tostring(L, 1);
lua::newtable(L);
if (!dir) return 1;
std::error_code ec;
fs::path dp(dir);
if (!fs::is_directory(dp, ec)) return 1;
int idx = 1;
for (auto& entry : fs::directory_iterator(dp, ec)) {
if (entry.is_directory(ec)) {
lua::pushstring(L, entry.path().string().c_str());
lua::rawseti(L, -2, idx++);
}
}
return 1;
});
lua::setfield(L, -2, "dirs");
// fs.basename(path) -> string
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushstring(L, ""); return 1; }
lua::pushstring(L, fs::path(p).filename().string().c_str());
return 1;
});
lua::setfield(L, -2, "basename");
// fs.dirname(path) -> string
lua::pushcfunction(L, [](lua::State* L) -> int {
const char* p = lua::tostring(L, 1);
if (!p) { lua::pushstring(L, ""); return 1; }
lua::pushstring(L, fs::path(p).parent_path().string().c_str());
return 1;
});
lua::setfield(L, -2, "dirname");
// Store into _LIBXPKG_MODULES["fs"]
lua::getglobal(L, "_LIBXPKG_MODULES");
lua::insert(L, -2); // stack: [modules, fs_table]
lua::setfield(L, -2, "fs"); // modules["fs"] = fs_table
lua::pop(L, 1); // pop modules
}
// Load all xim.libxpkg.* modules into _LIBXPKG_MODULES table, then run prelude
bool load_stdlib(lua::State* L, std::string& err_out) {
// Create empty _LIBXPKG_MODULES table
lua::newtable(L);
lua::setglobal(L, "_LIBXPKG_MODULES");
// Each module script returns a table; store it into _LIBXPKG_MODULES[name]
struct ModEntry { const char* name; std::string_view src; };
const ModEntry mods[] = {
{ "log", detail::log_lua },
{ "pkginfo", detail::pkginfo_lua },
{ "system", detail::system_lua },
{ "xvm", detail::xvm_lua },
{ "utils", detail::utils_lua },
{ "pkgmanager", detail::pkgmanager_lua },
{ "elfpatch", detail::elfpatch_lua },
{ "json", detail::json_lua },
{ "base64", detail::base64_lua },
};
for (auto& m : mods) {
// Load and compile the module source
if (lua::L_loadstring(L, m.src.data()) != lua::OK) {
err_out = std::string("failed to compile module ") + m.name + ": "
+ lua::tostring(L, -1);
lua::pop(L, 1);
return false;
}
// Execute the chunk, requesting 1 return value (the module table)
if (lua::pcall(L, 0, 1, 0) != lua::OK) {
err_out = std::string("failed to run module ") + m.name + ": "
+ lua::tostring(L, -1);
lua::pop(L, 1);
return false;
}
// Stack: [module_table]
// Store into _LIBXPKG_MODULES[name]
lua::getglobal(L, "_LIBXPKG_MODULES"); // stack: [module_table, modules]
lua::insert(L, -2); // stack: [modules, module_table]
lua::setfield(L, -2, m.name); // modules[name] = module_table; stack: [modules]
lua::pop(L, 1); // stack: []
}
// Load prelude: defines import(), os.*, path.*, etc.
if (lua::L_loadstring(L, detail::prelude_lua.data()) != lua::OK) {
err_out = "failed to load prelude: " + std::string(lua::tostring(L, -1));
lua::pop(L, 1);
return false;
}
if (lua::pcall(L, 0, 0, 0) != lua::OK) {
err_out = "failed to run prelude: " + std::string(lua::tostring(L, -1));
lua::pop(L, 1);
return false;
}
// Override shell-based os.* with C++ std::filesystem implementations
register_os_funcs(L);
// Register C++-backed fs module (symlink, entries, etc.)
register_fs_module(L);
return true;
}
// Inject ExecutionContext into Lua as _RUNTIME global table
void inject_context(lua::State* L, const mcpplibs::xpkg::ExecutionContext& ctx) {
lua::newtable(L);
set_string_field(L, "pkg_name", ctx.pkg_name);
set_string_field(L, "version", ctx.version);
set_string_field(L, "platform", ctx.platform);
set_string_field(L, "arch", ctx.arch);
set_string_field(L, "install_file", ctx.install_file.string());
set_string_field(L, "install_dir", ctx.install_dir.string());
set_string_field(L, "run_dir", ctx.run_dir.string());
set_string_field(L, "xpkg_dir", ctx.xpkg_dir.string());
set_string_field(L, "bin_dir", ctx.bin_dir.string());
set_string_field(L, "project_data_dir", ctx.project_data_dir.string());
set_string_field(L, "subos_sysrootdir", ctx.subos_sysrootdir);
set_string_field(L, "pkgindex_dir", ctx.pkgindex_dir);
auto push_string_array = [&](const std::vector<std::string>& v, const char* field) {
lua::newtable(L);
for (int i = 0; i < (int)v.size(); ++i) {
lua::pushstring(L, v[i].c_str());
lua::rawseti(L, -2, i + 1);
}
lua::setfield(L, -2, field);
};
push_string_array(ctx.deps_list, "deps_list");
push_string_array(ctx.runtime_deps_list, "runtime_deps_list");
push_string_array(ctx.build_deps_list, "build_deps_list");
// deps_exports: { [dep_spec] = { loader, libdirs, abi }, ... }
// Only deps that declared exports show up here.
lua::newtable(L);
for (auto& [dep_spec, e] : ctx.deps_exports) {
lua::newtable(L);
set_string_field(L, "loader", e.loader);
set_string_field(L, "abi", e.abi);
push_string_array(e.libdirs, "libdirs");
lua::setfield(L, -2, dep_spec.c_str());
}
lua::setfield(L, -2, "deps_exports");
// self_exports: same shape as a single deps_exports entry. Empty
// strings/arrays when the current package didn't declare exports.
lua::newtable(L);
set_string_field(L, "loader", ctx.self_exports.loader);
set_string_field(L, "abi", ctx.self_exports.abi);
push_string_array(ctx.self_exports.libdirs, "libdirs");
lua::setfield(L, -2, "self_exports");
// args as array table
lua::newtable(L);
for (int i = 0; i < (int)ctx.args.size(); ++i) {
lua::pushstring(L, ctx.args[i].c_str());
lua::rawseti(L, -2, i + 1);
}
lua::setfield(L, -2, "args");
lua::setglobal(L, "_RUNTIME");
}
} // namespace mcpplibs::xpkg::detail
// ---- PackageExecutor ----
export namespace mcpplibs::xpkg {
class PackageExecutor {
lua::State* L_ = nullptr;
fs::path pkg_ ;
public:
explicit PackageExecutor(lua::State* L, fs::path pkg)
: L_(L), pkg_(std::move(pkg)) {}
~PackageExecutor() {
if (L_) { lua::close(L_); L_ = nullptr; }
}
PackageExecutor(const PackageExecutor&) = delete;
PackageExecutor& operator=(const PackageExecutor&) = delete;
PackageExecutor(PackageExecutor&& o) noexcept
: L_(std::exchange(o.L_, nullptr)), pkg_(std::move(o.pkg_)) {}
PackageExecutor& operator=(PackageExecutor&& o) noexcept {
if (this != &o) {
if (L_) lua::close(L_);
L_ = std::exchange(o.L_, nullptr);
pkg_ = std::move(o.pkg_);
}
return *this;
}
bool has_hook(HookType hook) const {
auto name = detail::hook_name(hook);
lua::getglobal(L_, std::string(name).c_str());
bool found = (lua::type(L_, -1) == lua::TFUNCTION);
lua::pop(L_, 1);
return found;
}
HookResult run_hook(HookType hook, const ExecutionContext& ctx) {
// Inject context before each hook call
detail::inject_context(L_, ctx);
auto name = detail::hook_name(hook);
lua::getglobal(L_, std::string(name).c_str());
if (lua::type(L_, -1) != lua::TFUNCTION) {
lua::pop(L_, 1);
return HookResult{ .success = false,
.error = "hook not found: " + std::string(name) };
}
HookResult result;
if (lua::pcall(L_, 0, 1, 0) == lua::OK) {
int t = lua::type(L_, -1);
if (t == lua::TBOOLEAN) {
result.success = lua::toboolean(L_, -1);
} else if (t == lua::TSTRING) {
result.version = lua::tostring(L_, -1);
result.success = !result.version.empty();
} else {
// nil or anything else: treat as success (hook ran without error)
result.success = true;
}
lua::pop(L_, 1);
} else {
result.success = false;
result.error = lua::tostring(L_, -1);
lua::pop(L_, 1);
}
return result;
}
// Auto-stamp wrapper packages (linux-headers etc.) whose install hook
// returns success but leaves install_dir empty because the real
// payload lives elsewhere (subos sysroot via config(), or a
// sub-dependency). Without something in install_dir, xlings's catalog
// probe (`is_directory && !is_empty`) flags the package as not
// installed on every dependent install, re-running this hook + the
// expensive config hook every time. Drop a tiny `.xim-installed`
// stamp so install_dir is non-empty post-install. Authors no longer
// need to remember to write this themselves.
//
// CRITICAL: Call this AFTER all install paths complete (run_hook +
// any consumer-side stage_extracted_payload / default_install
// fallback). If invoked from inside run_hook, the stamp is written
// before the consumer's "is install_dir empty?" check, which would
// suppress the extracted-payload fallback used by packages whose
// install hook silently fails (e.g. tarballs without a top-level
// dir, where the hook's `os.mv(extracted_dir, install_dir)` no-ops
// because extracted_dir doesn't exist).
//
// Policy: only writes when (a) install_dir exists or can be created,
// (b) install_dir is empty. If anything else has populated it, we
// don't touch it.
void apply_install_stamp_if_empty(const ExecutionContext& ctx) {
if (ctx.install_dir.empty()) return;
std::error_code ec;
fs::create_directories(ctx.install_dir, ec);
ec.clear();
bool dir_exists = fs::exists(ctx.install_dir, ec)
&& fs::is_directory(ctx.install_dir, ec);
ec.clear();
if (!dir_exists || !fs::is_empty(ctx.install_dir, ec)) return;
auto stamp_path = ctx.install_dir / ".xim-installed";
std::ofstream out(stamp_path);
if (!out.is_open()) return;
// Key=value INI for human-readable + grep-friendly access.
// schema=1 reserves room to evolve the format later.
out << "schema = 1\n"
<< "name = " << ctx.pkg_name << "\n"
<< "version = " << ctx.version << "\n"
<< "platform = " << ctx.platform << "\n";
}
HookResult check_installed(const ExecutionContext& ctx) {
return run_hook(HookType::Installed, ctx);
}
// Run elfpatch.apply_auto() if the install hook set elfpatch_auto flag.
// Returns {scanned, patched, failed} counts. Safe to call unconditionally.
HookResult apply_elfpatch_auto() {
constexpr const char* script = R"__LUA__(
local ep = _LIBXPKG_MODULES and _LIBXPKG_MODULES["elfpatch"]
if not ep then return "no-ep 0 0 0" end
local r = ep.apply_auto()
return tostring(r.scanned) .. " " .. tostring(r.patched) .. " " .. tostring(r.failed)
)__LUA__";
HookResult result;
if (lua::L_loadstring(L_, script) != lua::OK) {
result.success = false;
result.error = lua::tostring(L_, -1);
lua::pop(L_, 1);
return result;
}
if (lua::pcall(L_, 0, 1, 0) == lua::OK) {
result.success = true;
if (lua::type(L_, -1) == lua::TSTRING)
result.output = lua::tostring(L_, -1);
lua::pop(L_, 1);
} else {
result.success = false;
result.error = lua::tostring(L_, -1);
lua::pop(L_, 1);
}
return result;
}
std::vector<XvmOp> xvm_operations() {
std::vector<XvmOp> ops;
lua::getglobal(L_, "_XVM_OPS");
if (lua::type(L_, -1) != lua::TTABLE) {
lua::pop(L_, 1);
return ops;
}
int len = (int)lua::rawlen(L_, -1);
for (int i = 1; i <= len; ++i) {
lua::rawgeti(L_, -1, i);
if (lua::type(L_, -1) == lua::TTABLE) {
XvmOp op;
auto read_field = [&](const char* key) -> std::string {
lua::getfield(L_, -1, key);
std::string val;
if (lua::type(L_, -1) == lua::TSTRING)
val = lua::tostring(L_, -1);
lua::pop(L_, 1);
return val;
};
op.op = read_field("op");
op.name = read_field("name");
op.version = read_field("version");
op.bindir = read_field("bindir");
op.alias = read_field("alias");
op.type = read_field("type");
op.filename = read_field("filename");
op.binding = read_field("binding");
op.includedir = read_field("includedir");
// Read envs table (key-value pairs)
lua::getfield(L_, -1, "envs");
if (lua::type(L_, -1) == lua::TTABLE) {
lua::pushnil(L_);
while (lua::next(L_, -2)) {
if (lua::type(L_, -2) == lua::TSTRING &&
lua::type(L_, -1) == lua::TSTRING) {
op.envs.emplace_back(
lua::tostring(L_, -2),
lua::tostring(L_, -1));
}
lua::pop(L_, 1);
}
}
lua::pop(L_, 1);
ops.push_back(std::move(op));
}
lua::pop(L_, 1);
}
lua::pop(L_, 1);
return ops;
}
// Run the script's xpkg_main() function with arguments.
HookResult run_script(const ExecutionContext& ctx) {
detail::inject_context(L_, ctx);
lua::newtable(L_);
lua::setglobal(L_, "_XVM_OPS");
lua::newtable(L_);
lua::setglobal(L_, "_INSTALL_REQUESTS");
lua::getglobal(L_, "xpkg_main");
if (lua::type(L_, -1) != lua::TFUNCTION) {
lua::pop(L_, 1);
return HookResult{ .success = false,
.error = "xpkg_main not found in script" };
}
int nargs = static_cast<int>(ctx.args.size());
for (auto& arg : ctx.args) {
lua::pushstring(L_, arg.c_str());
}
HookResult result;
if (lua::pcall(L_, nargs, 0, 0) == lua::OK) {
result.success = true;
} else {
result.success = false;
result.error = lua::tostring(L_, -1);
lua::pop(L_, 1);
}
return result;
}
// Set log level for Lua scripts: "debug", "info", "warn", "error", "silent"
void set_log_level(std::string_view level) {
std::string script = std::string("local log = _LIBXPKG_MODULES and _LIBXPKG_MODULES['log']; ")
+ "if log and log.set_level then log.set_level('" + std::string(level) + "') end";
if (lua::L_loadstring(L_, script.c_str()) == lua::OK) {
lua::pcall(L_, 0, 0, 0);
} else {
lua::pop(L_, 1);
}
}
std::vector<InstallRequest> install_requests() {
std::vector<InstallRequest> reqs;
lua::getglobal(L_, "_INSTALL_REQUESTS");
if (lua::type(L_, -1) != lua::TTABLE) {
lua::pop(L_, 1);
return reqs;
}
int len = (int)lua::rawlen(L_, -1);
for (int i = 1; i <= len; ++i) {
lua::rawgeti(L_, -1, i);
if (lua::type(L_, -1) == lua::TTABLE) {
InstallRequest req;
lua::getfield(L_, -1, "op");
if (lua::type(L_, -1) == lua::TSTRING) req.op = lua::tostring(L_, -1);
lua::pop(L_, 1);
lua::getfield(L_, -1, "target");
if (lua::type(L_, -1) == lua::TSTRING) req.target = lua::tostring(L_, -1);
lua::pop(L_, 1);
reqs.push_back(std::move(req));
}
lua::pop(L_, 1);
}
lua::pop(L_, 1);
return reqs;
}
};
// Factory
std::expected<PackageExecutor, std::string>
create_executor(const fs::path& pkg_path) {
if (!fs::exists(pkg_path)) {
return std::unexpected("package file not found: " + pkg_path.string());
}
lua::State* L = lua::L_newstate();
if (!L) return std::unexpected("failed to create lua state");
lua::L_openlibs(L);
std::string err;
if (!detail::load_stdlib(L, err)) {
lua::close(L);
return std::unexpected(err);
}
// Derive pkgindex root from pkg_path for top-level import("xim.pkgindex.*").
// Package files live at <pkgindex>/pkgs/<letter>/<name>.lua — 3 levels up.
{
auto pkgindex = pkg_path.parent_path().parent_path().parent_path();
std::error_code ec;
if (fs::is_directory(pkgindex / "libs", ec)) {
lua::pushstring(L, pkgindex.string().c_str());
lua::setglobal(L, "_PKGINDEX_DIR");
}
}
if (lua::L_dofile(L, pkg_path.string().c_str()) != lua::OK) {
err = lua::tostring(L, -1);
lua::close(L);
return std::unexpected("failed to load package: " + err);
}
return PackageExecutor(L, pkg_path);
}
} // export namespace mcpplibs::xpkg