载入中...
搜索中...
未找到
Package.cpp
浏览该文件的文档.
1#include <CLI11.hpp>
2#include <iostream>
3#include "cmdline.h"
4
5#if !defined(__EMSCRIPTEN__)
6#include <Poco/PipeStream.h>
7#include <Poco/Process.h>
8#include <Poco/UnicodeConverter.h>
9#include <algorithm>
10#include <chrono>
11#include <cwchar>
12#include <filesystem>
13#include <fstream>
14#include <map>
15#include <rang.hpp>
16#include <set>
17#include <sstream>
18#include <thread>
19#include "Sha256.h"
20#include "common/Runtime.h"
22#include "common/ScriptModule.h"
23#include "common/config.h"
24#include "zip_writer.h"
25
26#if defined(EVENGINE_WINDOWS) || defined(_WIN32)
27#include <restartmanager.h>
28#include <windows.h>
29#else
30#include <unistd.h>
31#endif
32
33using namespace std::filesystem;
34#endif
35
36using namespace std;
37
38namespace eve::cmd
39{
40
41#if !defined(__EMSCRIPTEN__)
42namespace {
43
44#if defined(EVENGINE_WINDOWS) || defined(_WIN32)
45struct PackageLockOwners {
46 DWORD status = ERROR_GEN_FAILURE;
47 vector<DWORD> processes;
48};
49PackageLockOwners diagnosePackageLocks(const path& candidate, bool verbose = true) {
50 // Read-only query: never shut down a locker. Dynamically load the OS API to keep it off the normal
51 // packaging path and avoid adding a shipped DLL dependency.
52 struct RestartManager {
53 HMODULE library = LoadLibraryExW(L"Rstrtmgr.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
54 ~RestartManager() {
55 if (library) FreeLibrary(library);
56 }
57 } api;
58 if (!api.library) {
59 cerr << "Package lock diagnostics unavailable: " << GetLastError() << '\n';
60 return {};
61 }
62 auto start = reinterpret_cast<decltype(&RmStartSession)>(GetProcAddress(api.library, "RmStartSession"));
63 auto end = reinterpret_cast<decltype(&RmEndSession)>(GetProcAddress(api.library, "RmEndSession"));
64 auto resources =
65 reinterpret_cast<decltype(&RmRegisterResources)>(GetProcAddress(api.library, "RmRegisterResources"));
66 auto list = reinterpret_cast<decltype(&RmGetList)>(GetProcAddress(api.library, "RmGetList"));
67 if (!start || !end || !resources || !list) {
68 cerr << "Package lock diagnostics API unavailable\n";
69 return {};
70 }
71 DWORD session = 0;
72 WCHAR key[CCH_RM_SESSION_KEY + 1]{};
73 DWORD status = start(&session, 0, key);
74 if (status != ERROR_SUCCESS) {
75 cerr << "Package lock diagnostics start failed: " << status << '\n';
76 return {};
77 }
78 struct Session {
79 DWORD handle;
80 decltype(&RmEndSession) close;
81 ~Session() {
82 const DWORD result = close(handle);
83 if (result != ERROR_SUCCESS) cerr << "Package lock diagnostics end failed: " << result << '\n';
84 }
85 } cleanup{session, end};
86 vector<wstring> names;
87 error_code scanError;
88 for (recursive_directory_iterator it(candidate, scanError), last; !scanError && it != last;
89 it.increment(scanError)) {
90 if (it->is_regular_file(scanError)) names.push_back(absolute(it->path()).wstring());
91 }
92 if (scanError || names.empty()) {
93 cerr << "Package lock diagnostics enumeration failed or empty: " << scanError.message() << '\n';
94 return {};
95 }
96 vector<LPCWSTR> files;
97 for (const auto& name : names) files.push_back(name.c_str());
98 status = resources(session, static_cast<UINT>(files.size()), files.data(), 0, nullptr, 0, nullptr);
99 UINT needed = 0, count = 0;
100 DWORD reasons = 0;
101 if (status == ERROR_SUCCESS) status = list(session, &needed, &count, nullptr, &reasons);
102 vector<RM_PROCESS_INFO> processes;
103 if (status == ERROR_MORE_DATA) {
104 processes.resize(needed);
105 count = needed;
106 status = list(session, &needed, &count, processes.data(), &reasons);
107 }
108 if (verbose) cerr << "Package lock diagnostics: status=" << status << " process_count=" << count << '\n';
109 if (status != ERROR_SUCCESS) return {};
110 PackageLockOwners owners{ERROR_SUCCESS, {}};
111 for (UINT i = 0; i < count; ++i) {
112 owners.processes.push_back(processes[i].Process.dwProcessId);
113 string name;
114 Poco::UnicodeConverter::toUTF8(wstring(processes[i].strAppName), name);
115 if (verbose)
116 cerr << "Package locker pid=" << processes[i].Process.dwProcessId << " application=" << name << '\n';
117 }
118 return owners;
119}
120
121enum class PackageLockRelease { NotExternal, Released, TimedOut, Unavailable };
122PackageLockRelease waitForExternalPackageLocks(const path& candidate, DWORD runtimePid, PackageLockOwners owners) {
123 const auto deadline = chrono::steady_clock::now() + chrono::seconds(5);
124 const auto publisherPid = GetCurrentProcessId();
125 if (owners.status != ERROR_SUCCESS) return PackageLockRelease::Unavailable;
126 // The borrow can end between the failed rename and this snapshot. An empty
127 // successful query must permit the same verified retry as a later release.
128 if (owners.processes.empty()) return PackageLockRelease::Released;
129 for (;;) {
130 if (find(owners.processes.begin(), owners.processes.end(), publisherPid) != owners.processes.end() ||
131 find(owners.processes.begin(), owners.processes.end(), runtimePid) != owners.processes.end())
132 return PackageLockRelease::NotExternal;
133 if (chrono::steady_clock::now() >= deadline) return PackageLockRelease::TimedOut;
134 this_thread::sleep_for(chrono::milliseconds(100));
135 owners = diagnosePackageLocks(candidate, false);
136 if (owners.status != ERROR_SUCCESS) return PackageLockRelease::Unavailable;
137 if (owners.processes.empty()) return PackageLockRelease::Released;
138 }
139}
140
141#endif
142
143// Runtime binary name inside the *target* SDK's bin/. The packaged game runs on
144// the SDK's platform, which is not necessarily the host running `eve package`
145// (e.g. a Linux host can produce a Windows game folder for the win32 SDK).
146std::string targetRuntimeName(const std::string& sdkRoot) {
147 std::ifstream in(std::filesystem::path(sdkRoot) / "share" / "eve" / "TARGET_PLATFORM");
148 std::string plat;
149 std::getline(in, plat);
150 while (!plat.empty() && (plat.back() == '\r' || plat.back() == '\n' || plat.back() == ' '))
151 plat.pop_back();
152 return plat == "win32" ? "eve.exe" : "eve";
153}
154
155bool copyFileIf(const path& src, const path& dst) {
156 error_code ec;
157 if (!exists(src, ec)) return false;
158 create_directories(dst.parent_path(), ec);
159 copy_file(src, dst, copy_options::overwrite_existing, ec);
160 return !ec;
161}
162
163// Best-effort copy of a DLL from any of the candidate source directories.
164bool copyFirst(const std::string& dll, const std::vector<path>& candidates, const path& dstDir) {
165 for (const auto& dir : candidates) {
166 path p = dir / dll;
167 if (copyFileIf(p, dstDir / dll)) return true;
168 }
169 return false;
170}
171
172struct ScriptPackageManifest {
173 std::map<std::string, std::vector<std::string>> graph;
174 std::string error;
175
176 std::string serialize() const {
177 std::ostringstream out;
178 out << "version=1\n";
179 for (const auto& [module, dependencies] : graph) {
180 out << module;
181 for (const std::string& dependency : dependencies) out << '\t' << dependency;
182 out << '\n';
183 }
184 return out.str();
185 }
186};
187
188bool canonicalGameModule(std::string_view importer, std::string_view specifier, std::string& result,
189 std::string& error) {
190 script::ScriptModuleRequest request{std::string(importer), std::string(specifier)};
192 if (result.rfind("game:/", 0) != 0) {
193 error = "package cannot statically resolve non-game script module: " + result;
194 return false;
195 }
196 return true;
197}
198
199// Compilation imports must use the same snapshot as the archive, never the
200// process's current directory or an already-mounted game's filesystem service.
201class PackageScriptProvider final : public script::IScriptModuleProvider {
202public:
203 explicit PackageScriptProvider(path root) : root_(std::move(root)) {}
204 script::ScriptModuleStatus resolve(const script::ScriptModuleRequest& request, std::string& uri,
205 std::string& error) override {
206 return canonicalGameModule(request.importerUri, request.specifier, uri, error)
209 }
210 script::ScriptModuleStatus load(std::string_view uri, script::ScriptModuleSource& source,
211 std::string& error) override {
212 if (uri.rfind("game:/", 0) != 0) {
213 error = "non-game package module";
215 }
216 const path file = root_ / std::string(uri.substr(6));
217 ifstream input(file, ios::binary);
218 if (!input) {
219 error = "Cannot read package module: " + file.string();
221 }
222 source.canonicalUri = std::string(uri);
223 source.utf8Source.assign(std::istreambuf_iterator<char>(input), {});
224 source.debugOrigin = file.string();
225 sdk::detail::Sha256 hash;
226 hash.update(source.utf8Source.data(), source.utf8Source.size());
227 source.contentHash = hash.finish();
229 }
230
231private:
232 path root_;
233};
234
235ScriptPackageManifest scanScriptPackage(const path& gameDir) {
236 ScriptPackageManifest manifest;
237 std::error_code ec;
238 for (recursive_directory_iterator it(gameDir, directory_options::none, ec), end; it != end; it.increment(ec)) {
239 if (ec) {
240 manifest.error = "cannot enumerate scripts: " + ec.message();
241 return manifest;
242 }
243 if (!it->is_regular_file() || it->path().extension() != ".nut") continue;
244 std::ifstream input(it->path(), std::ios::binary);
245 if (!input) {
246 manifest.error = "cannot read script during package scan: " + it->path().string();
247 return manifest;
248 }
249 const std::string source(std::istreambuf_iterator<char>(input), {});
250 const std::string relative = std::filesystem::relative(it->path(), gameDir, ec).generic_string();
251 if (ec) {
252 manifest.error = "cannot canonicalize packaged script: " + it->path().string();
253 return manifest;
254 }
255 const std::string canonical = "game:/" + relative;
256 auto& edges = manifest.graph[canonical];
257 for (const std::string& specifier : script::ScriptCompiler::analyze(source, canonical).imports) {
258 std::string dependency;
259 if (!canonicalGameModule(canonical, specifier, dependency, manifest.error)) return manifest;
260 edges.push_back(std::move(dependency));
261 }
262 std::sort(edges.begin(), edges.end());
263 edges.erase(std::unique(edges.begin(), edges.end()), edges.end());
264 }
265
266 if (ec) {
267 manifest.error = "cannot enumerate scripts: " + ec.message();
268 return manifest;
269 }
270
271 for (const auto& [module, dependencies] : manifest.graph) {
272 for (const std::string& dependency : dependencies) {
273 if (manifest.graph.find(dependency) == manifest.graph.end()) {
274 manifest.error = "script module imported by " + module + " is missing from package: " + dependency;
275 return manifest;
276 }
277 }
278 }
279
280 enum class Visit { Visiting, Ready };
281 std::map<std::string, Visit> visits;
282 std::vector<std::string> stack;
283 const auto visit = [&](const auto& self, const std::string& module) -> bool {
284 if (const auto found = visits.find(module); found != visits.end()) {
285 if (found->second == Visit::Ready) return true;
286 manifest.error = "cyclic script import in package";
287 for (const std::string& entry : stack) manifest.error += " -> " + entry;
288 manifest.error += " -> " + module;
289 return false;
290 }
291 visits[module] = Visit::Visiting;
292 stack.push_back(module);
293 for (const std::string& dependency : manifest.graph[module]) {
294 if (!self(self, dependency)) return false;
295 }
296 stack.pop_back();
297 visits[module] = Visit::Ready;
298 return true;
299 };
300 for (const auto& [module, _] : manifest.graph) {
301 if (!visit(visit, module)) return manifest;
302 }
303 Runtime compiler(512, ssq::Libs::ALL);
304 if (compiler.scriptModules().registerProvider(std::make_shared<PackageScriptProvider>(gameDir), 100) == 0)
305 throw runtime_error("Cannot register package snapshot provider");
306 for (const auto& [module, _] : manifest.graph) {
307 ifstream input(gameDir / module.substr(6), ios::binary);
308 if (!input) throw runtime_error("Cannot read package script: " + module);
309 const string source(std::istreambuf_iterator<char>(input), {});
310 if (input.bad()) throw runtime_error("Cannot read complete package script: " + module);
311 try {
312 compiler.compileSource(source, module);
313 } catch (const std::exception& error) {
314 manifest.error = module + ": " + error.what();
315 return manifest;
316 }
317 }
318 return manifest;
319}
320
321// Locate the target SDK root: --sdk, EVENGINE_SDK, or next to the running binary.
322std::string resolveSdkRoot(const std::string& sdkArg) {
323 if (!sdkArg.empty() && is_directory(sdkArg)) return sdkArg;
324
325 const char* env = getenv("EVENGINE_SDK");
326 if (env && is_directory(env)) return env;
327
328 // Running from <sdk>/bin/<runtime> -> root is two directories up.
329 path exe;
330#if defined(EVENGINE_WINDOWS) || defined(_WIN32)
331 wchar_t buf[MAX_PATH + 1] = {0};
332 if (GetModuleFileNameW(nullptr, buf, MAX_PATH) != 0) exe = path(buf);
333#else
334 char buf[4096] = {0};
335 const ssize_t n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
336 if (n > 0) exe = path(std::string(buf, static_cast<size_t>(n)));
337#endif
338 if (!exe.empty()) {
339 path root = exe.parent_path().parent_path();
340 if (exists(root / "share" / "eve" / "TARGET_PLATFORM")) return root.string();
341 }
342 return "";
343}
344
345} // namespace
346#endif
347
350 void setup(CLI::App& app, std::shared_ptr<CLI::Formatter>) override {
351 auto subcmd = app.add_subcommand("package", "Package a game into a runnable game folder.");
352 subcmd->allow_extras();
353 subcmd->add_option("-o,--output", outputPath, "output folder path");
354 subcmd->add_option("--sdk", sdkPath, "target SDK root (default: auto-detect / $EVENGINE_SDK)");
355 }
356
357 int parse(CLI::App& app, Cmdline& cmd) override {
358 auto subcmd = app.get_subcommand("package");
359 if (subcmd->parsed()) {
360 string game = cmd.get_remaining(subcmd, ".");
361 int res = cmd.Package(game, outputPath, sdkPath);
362 return res;
363 }
364 return -1; // not handle
365 }
366};
367
369
370#if defined(__EMSCRIPTEN__)
371int Cmdline::Package(std::string, std::string, std::string) {
372 cerr << "eve package requires a native host that can run the target SDK runtime; "
373 "desktop packaging is unavailable in the browser.\n";
374 return 8;
375}
376#else
377int Cmdline::Package(std::string gamePath, std::string output, std::string sdk) try {
378 error_code ec;
379 if (!is_directory(gamePath, ec)) {
380 cerr << rang::fg::red << "Not a directory: " << rang::fg::reset << gamePath << endl;
381 return 1;
382 }
383
384 std::string sdkRoot = resolveSdkRoot(sdk);
385 if (sdkRoot.empty()) {
386 cerr << rang::fg::red
387 << "Cannot locate the target SDK. Pass --sdk <dir>, set $EVENGINE_SDK, "
388 "or run from <sdk>/bin/<runtime>."
389 << rang::fg::reset << endl;
390 return 2;
391 }
392
393 gamePath = canonical(gamePath).string();
394 if (!is_regular_file(path(gamePath) / "main.nut")) {
395 cerr << "Package requires main.nut\n";
396 return 5;
397 }
398 // Game folder name, trailing separators stripped.
399 std::string gameName = gamePath;
400 while (!gameName.empty() && (gameName.back() == '/' || gameName.back() == '\\'))
401 gameName.pop_back();
402 if (gameName.find_first_of("/\\") != string::npos)
403 gameName = std::filesystem::path(gameName).filename().string();
404 if (gameName.empty()) gameName = "game";
405
406 const path destination = weakly_canonical(output.empty() ? path(gameName + "-package") : path(output));
407 const auto relativeOutput = destination.lexically_relative(gamePath);
408 const auto relativeGame = path(gamePath).lexically_relative(destination);
409 if (destination == path(gamePath) || (!relativeOutput.empty() && *relativeOutput.begin() != "..") ||
410 (!relativeGame.empty() && *relativeGame.begin() != "..")) {
411 cerr << "Package output and source must not contain one another\n";
412 return 6;
413 }
414 create_directories(destination.parent_path());
415 const path lock = destination.string() + ".package-lock";
416 if (!create_directory(lock)) {
417 cerr << "Package destination is locked: " << lock << '\n';
418 return 6;
419 }
420 struct Cleanup {
422 ~Cleanup() {
423 error_code ignored;
424 remove_all(directory, ignored);
425 }
426 } cleanup{lock};
427 path outDir = lock / "candidate";
428 create_directory(outDir);
429 const path snapshot = lock / "source";
430 copy(gamePath, snapshot, copy_options::recursive);
431 const ScriptPackageManifest scripts = scanScriptPackage(snapshot);
432 if (!scripts.error.empty()) {
433 cerr << rang::fg::red << "Script dependency scan failed: " << scripts.error << rang::fg::reset << endl;
434 return 5;
435 }
436
437
438 path sdkBin = path(sdkRoot) / "bin";
439 path sdkLib = path(sdkRoot) / "lib";
440 path sdkPlat = path(sdkRoot) / "platform";
441
442 const std::string runtimeName = targetRuntimeName(sdkRoot);
443
444 // 1. Runtime executable.
445 path runtimeSrc = sdkBin / runtimeName;
446 path runtimeDst = outDir / runtimeName;
447 if (!copyFileIf(runtimeSrc, runtimeDst)) {
448 cerr << rang::fg::red << "SDK missing " << runtimeSrc.string() << rang::fg::reset << endl;
449 return 3;
450 }
451
452 // 2. Windows runtime DLLs the packaged game needs (vulkan loader + VC CRT).
453 // win32 SDKs bundle them in bin/ so ANY host can produce a self-contained
454 // package; on a Windows host we also fall back to the local VS redist for
455 // older SDKs that predate bundling.
456 if (runtimeName == "eve.exe") {
457 std::vector<path> crtCandidates;
458 if (exists(sdkBin)) crtCandidates.push_back(sdkBin);
459 if (exists(sdkLib)) crtCandidates.push_back(sdkLib);
460#if defined(EVENGINE_WINDOWS) || defined(_WIN32)
461 // VC redist (version-independent glob): both release CRT and debug CRT.
462 for (const auto& msroot : {"C:/Program Files/Microsoft Visual Studio"}) {
463 path base = path(msroot);
464 if (exists(base / "18")) base = base / "18";
465 for (const auto& entry : directory_iterator(base, ec)) {
466 if (!entry.is_directory()) continue;
467 path redist = entry.path() / "Community" / "VC" / "Redist" / "MSVC";
468 if (!exists(redist)) continue;
469 for (const auto& ver : directory_iterator(redist, ec)) {
470 for (const auto& crtDir : {"x64", "debug_nonredist/x64"}) {
471 path crt = ver.path() / crtDir;
472 if (!exists(crt)) continue;
473 for (const auto& sub : directory_iterator(crt, ec)) {
474 if (!sub.is_directory()) continue;
475 const std::string n = sub.path().filename().string();
476 if (n.find("Microsoft.VC") == 0 &&
477 (n.find(".CRT") != string::npos ||
478 n.find("DebugCRT") != string::npos))
479 crtCandidates.push_back(sub.path());
480 }
481 }
482 }
483 }
484 }
485 if (exists(path("C:/Windows/System32")))
486 crtCandidates.push_back(path("C:/Windows/System32"));
487#endif
488
489 // eve.exe links the VC runtime dynamically; bundle both release and
490 // debug sets so the package is self-contained regardless of build type.
491 for (const auto& dll : {"vulkan-1.dll", "msvcp140.dll", "msvcp140_1.dll",
492 "msvcp140_2.dll", "vcruntime140.dll",
493 "vcruntime140_1.dll", "concrt140.dll",
494 "msvcp140d.dll", "vcruntime140d.dll",
495 "vcruntime140_1d.dll", "ucrtbased.dll",
496 "concrt140d.dll"}) {
497 if (!copyFirst(dll, crtCandidates, outDir))
498 cerr << rang::fg::yellow
499 << "note: runtime DLL not found (may be system-installed): "
500 << dll << rang::fg::reset << endl;
501 }
502 }
503
504#ifdef EVENGINE_MACOSX
505 // 2b. macOS: copy the SDK's lib/ tree (Vulkan loader + MoltenVK + ICD
506 // manifest + zlib/PNG dylibs) into <out>/lib. eve carries INSTALL_RPATH
507 // "@loader_path/../lib", and platform/macosx bootstrapBundledVulkan points
508 // SDL at <out>/lib/libvulkan.1.dylib + <out>/lib/MoltenVK_icd.json, so the
509 // packaged game is self-contained next to the eve binary. Copying the tree
510 // (not just *.dylib) keeps the ICD manifest and any subdirectories.
511 if (exists(sdkLib)) {
512 std::ifstream platIn(std::filesystem::path(sdkRoot) / "share" / "eve" / "TARGET_PLATFORM");
513 std::string plat;
514 std::getline(platIn, plat);
515 while (!plat.empty() && (plat.back() == '\r' || plat.back() == '\n' || plat.back() == ' '))
516 plat.pop_back();
517 // Only macOS-target packages get the dylib tree; cross-packaged
518 // win32/linux games must stay clean.
519 if (plat == "macosx")
520 copy(sdkLib, outDir / "lib",
521 copy_options::recursive | copy_options::overwrite_existing, ec);
522 if (ec) throw filesystem_error("copy SDK libraries", sdkLib, ec);
523 }
524#endif // EVENGINE_MACOSX
525
526 // 3. Platform packaging template (win32/linux README etc).
527 if (exists(sdkPlat)) {
528 for (const auto& entry : directory_iterator(sdkPlat, ec)) {
529 copy(entry.path(), outDir / entry.path().filename(),
530 copy_options::recursive | copy_options::overwrite_existing, ec);
531 if (ec) throw filesystem_error("copy platform template", entry.path(), ec);
532 }
533 }
534
535 // 4. Compress the game directory into game.eve inside the package.
536 path archive = outDir / "game.eve";
537 if (!cmdline::createGameArchive(snapshot, archive, {{".eve/script-modules.manifest", scripts.serialize()}})) {
538 cerr << rang::fg::red << "Failed to package game archive." << rang::fg::reset << endl;
539 return 4;
540 }
541
542 const auto hashFile = [](const path& file) {
543 ifstream input(file, ios::binary);
544 if (!input) throw runtime_error("Cannot hash " + file.string());
546 char buffer[65536];
547 while (input.read(buffer, sizeof(buffer)) || input.gcount())
548 hash.update(buffer, static_cast<size_t>(input.gcount()));
549 if (!input.eof()) throw runtime_error("Cannot read " + file.string());
550 return hash.finish();
551 };
552 const string archiveHash = hashFile(archive);
553 const string runtimeHash = hashFile(runtimeDst);
554 // Run the exact archive and runtime that will be published, with a bounded
555 // acceptance mode. Cross-target runtimes must be executable on this host.
556 Poco::Process::Env childEnvironment;
557#if defined(EVENGINE_WINDOWS) || defined(_WIN32)
558 // Unlike POSIX Poco, CreateProcess replaces the entire environment when a
559 // nonempty map is supplied. Preserve PATH, system directories and drivers.
560 struct EnvironmentBlock {
561 LPWCH value = GetEnvironmentStringsW();
562 ~EnvironmentBlock() {
563 if (value) FreeEnvironmentStringsW(value);
564 }
565 } environment;
566 if (!environment.value) throw runtime_error("Cannot read child process environment");
567 for (const wchar_t* entry = environment.value; *entry; entry += std::wcslen(entry) + 1) {
568 string utf8;
569 Poco::UnicodeConverter::toUTF8(std::wstring(entry), utf8);
570 const auto separator = utf8.find('=', 1);
571 if (separator != string::npos) childEnvironment.emplace(utf8.substr(0, separator), utf8.substr(separator + 1));
572 }
573#endif
574 childEnvironment["EVE_PACKAGE_CHECK"] = "1";
575 Poco::Pipe pipe;
576 auto process = Poco::Process::launch(absolute(runtimeDst).string(), {"run"}, absolute(outDir).string(), nullptr,
577 &pipe, &pipe, childEnvironment);
578 std::string log;
579 struct ChildCleanup {
580 Poco::ProcessHandle child;
581 std::thread reader;
582 ~ChildCleanup() {
583 try {
584 if (child.tryWait() == -1) {
585 Poco::Process::kill(child.id());
586 child.wait();
587 }
588 } catch (...) {
589 }
590 if (reader.joinable()) reader.join();
591 }
592 } child{process, {}};
593 child.reader = std::thread([&] {
594 Poco::PipeInputStream input(pipe);
595 char buffer[4096];
596 while (input.read(buffer, sizeof(buffer)) || input.gcount()) {
597 // Keep draining after the cap so a noisy candidate cannot block.
598 if (log.size() < 8 * 1024 * 1024) log.append(buffer, static_cast<size_t>(input.gcount()));
599 }
600 });
601 int exit = -1;
602 const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60);
603 while ((exit = process.tryWait()) == -1 && std::chrono::steady_clock::now() < deadline)
604 std::this_thread::sleep_for(std::chrono::milliseconds(20));
605 if (exit == -1) {
606 Poco::Process::kill(process.id());
607 exit = process.wait();
608 }
609#if defined(EVENGINE_WINDOWS) || defined(_WIN32)
610 // On Windows tryWait reads the exit code before the process object is
611 // signaled. Wait for teardown to release the candidate's directory handles.
612 exit = process.wait();
613#endif
614 child.reader.join();
615 if (exit != 0 || log.find("[package-check] passed: 30 frames") == std::string::npos) {
616 cerr << "Package runtime acceptance failed (exit " << exit << ")\n" << log;
617 return 7;
618 }
619 if (hashFile(archive) != archiveHash || hashFile(runtimeDst) != runtimeHash)
620 throw runtime_error("Candidate changed during runtime acceptance");
621 sdk::detail::Sha256 buildIdentity;
622 const string identityInput = "eve.package-build/1\n" + archiveHash + "\n" + runtimeHash;
623 buildIdentity.update(identityInput.data(), identityInput.size());
624 ofstream record(outDir / "build-identity.manifest", ios::binary);
625 record << "schema=eve.package-build\nversion=1\n"
626 << "build_id=" << buildIdentity.finish() << "\n"
627 << "archive_sha256=" << archiveHash << "\n"
628 << "runtime_sha256=" << runtimeHash << "\n"
629 << "built_at_unix_ms="
630 << chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now().time_since_epoch()).count()
631 << "\n"
632 << "compiled_scripts=" << scripts.graph.size() << "\n"
633 << "acceptance=passed\nframes=30\n";
634 record.close();
635 if (!record) throw runtime_error("Cannot write build identity");
636 ofstream acceptance(outDir / "acceptance.log", ios::binary);
637 acceptance << log;
638 acceptance.close();
639 if (!acceptance) throw runtime_error("Cannot write acceptance log");
640
641 const path previous = lock / "previous";
642 const bool hadPrevious = exists(destination);
643 if (hadPrevious) rename(destination, previous);
644 rename(outDir, destination, ec);
645 if (ec) {
646 cerr << "Package publish failed: code=" << ec.value() << " category=" << ec.category().name()
647 << " candidate=" << outDir << " destination=" << destination << '\n';
648#if defined(EVENGINE_WINDOWS) || defined(_WIN32)
649 cerr << "Package publisher pid=" << GetCurrentProcessId() << " accepted runtime pid=" << process.id() << '\n';
650 try {
651 auto owners = diagnosePackageLocks(outDir);
652 if (ec.category() == system_category() &&
653 (ec.value() == ERROR_ACCESS_DENIED || ec.value() == ERROR_SHARING_VIOLATION) &&
654 waitForExternalPackageLocks(outDir, process.id(), std::move(owners)) == PackageLockRelease::Released) {
655 // External monitoring can borrow the accepted executable without
656 // delete-sharing. Revalidate acceptance inputs after that borrow ends.
657 if (hashFile(archive) != archiveHash || hashFile(runtimeDst) != runtimeHash)
658 throw runtime_error("Candidate changed while waiting for external package locks");
659 cerr << "No package lockers reported; retrying verified candidate\n";
660 rename(outDir, destination, ec);
661 }
662 } catch (const std::exception& diagnosticError) {
663 cerr << "Package lock diagnostics failed: " << diagnosticError.what() << '\n';
664 }
665#endif
666 }
667 if (ec) {
668 if (hadPrevious) {
669 error_code restoreError;
670 rename(previous, destination, restoreError);
671 if (restoreError) {
672 // Retain recovery evidence if rollback itself fails.
673 cleanup.directory.clear();
674 cerr << "Previous package retained at " << previous << '\n';
675 }
676 }
677 throw filesystem_error("publish package", destination, ec);
678 }
679 cout << "Built verified game package -> " << destination.string() << '\n';
680 cout << " run: " << (destination / runtimeName).string() << '\n';
681 return 0;
682} catch (const std::exception& error) {
683 cerr << "Package failed: " << error.what() << '\n';
684 return 8;
685}
686
687#endif
688
689} // namespace eve::cmd
Duration start
int root
Definition AnimSmr.cpp:119
Vec3 relative
Definition AnimSmr.cpp:164
std::string output
std::filesystem::path directory
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
ScriptComponentRecord record
Definition ECS.cpp:228
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
const GltfImportRequest & request
wgpu::PopErrorScopeStatus status
glm::vec3 n
Definition Grass.cpp:63
std::vector< Edge > edges
std::chrono::steady_clock::time_point deadline
Poco::JSON::Object::Ptr result
Snapshot snapshot
bool exists
std::shared_ptr< const OceanSprayFrame > previous
std::vector< std::weak_ptr< DeviceBytes > > resources
Definition OnnxGpgpu.cpp:55
onnx_detail::CompilerQueue compiler
Definition OnnxGpgpu.cpp:45
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::string error
Definition Package.cpp:174
std::map< std::string, std::vector< std::string > > graph
Definition Package.cpp:173
std::string script
Definition PlayHost.cpp:117
std::string path
Definition PlayHost.cpp:111
std::string uri
PrimitiveHandle handle
std::string file
Object::Ptr value
std::string hash
bool found
ScriptStructure out
std::string_view source
size_t end
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
int count
std::optional< InteractionSession > session
Definition Tactics.cpp:39
V3 dir
Definition TreeMesh.cpp:151
命令行模块(eve.cmd):run / build / package / test / zip / dev-server 等子命令入口。
Definition cmdline.h:34
static std::string get_remaining(CLI::App *sub, std::string default_path=".")
子命令剩余位置参数。
Definition cmdline.cpp:80
int Package(std::string path, std::string output, std::string sdk)
把游戏打包为单个可执行文件 / APK。
Definition Package.cpp:377
Sha256 public API.
Definition Sha256.h:11
std::string finish()
Finish.
Definition Sha256.cpp:88
void update(const char *data, std::size_t size)
Updates .
Definition Sha256.cpp:73
static bool canonicalize(const ScriptModuleRequest &request, std::string &output, std::string &error)
Normalizes a logical module URI and rejects root traversal.
#define CMD_REG(name)
Definition cmdline.h:102
bool createGameArchive(const std::filesystem::path &gameDir, const std::filesystem::path &outArchive, const std::vector< std::pair< std::string, std::string > > &generatedEntries={})
Creates game archive.
Definition zip_writer.h:220
ScriptModuleStatus
Result of asking a provider to resolve or load a script module.
WidgetDesc list(std::string listId, const std::vector< std::string > &items, const std::function< WidgetDesc(const std::string &, int)> &itemFn)
Expand a string list into a Group of item widgets. itemFn(label, index) builds each row; keys default...
Definition Widget.cpp:906
One eve <subcommand> handler: CLI setup + argument parsing.
Definition cmdline.h:24
int parse(CLI::App &app, Cmdline &cmd) override
Parses arguments and runs the command; returns the exit code.
Definition Package.cpp:357
void setup(CLI::App &app, std::shared_ptr< CLI::Formatter >) override
Registers options on the CLI11 sub-app.
Definition Package.cpp:350