// SPDX-License-Identifier: LGPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® module; #include #include #include export module Crafter.Build:Clang_impl; import std; import :Clang; import :Platform; import :Toolchain; import :Test; import :Lint; import :Script; import :Agents; import :Progress; import :Asset; import :Flatpak; import :Jobs; namespace fs = std::filesystem; using namespace Crafter; namespace { // Map one `import X;` name onto either a module this Configuration owns or // one exported by a Configuration reachable through its dependency DAG, // appending the matching staleness edge. False means nothing in reach // provides X — either it's supplied from outside the graph (`std`) or the // dependency isn't wired up *yet*, which is why callers remember the name. bool ResolveImportName(Configuration& cfg, const std::string& importName, std::vector& localDeps, std::vector>& externalDeps) { for(const std::unique_ptr& interface : cfg.interfaces) { if(interface->name == importName) { localDeps.push_back(interface.get()); return true; } } std::unordered_set seen; std::function walk = [&](Configuration* depCfg) -> bool { if (!seen.insert(depCfg).second) return false; for(const std::unique_ptr& depInterface : depCfg->interfaces) { if(depInterface->name == importName) { fs::path depPcmPath = std::format("{}.pcm", (depCfg->PcmDir() / depInterface->path.filename()).string()); externalDeps.emplace_back(depInterface.get(), std::move(depPcmPath)); return true; } } for(Configuration* sub : depCfg->dependencies) { if (walk(sub)) return true; } return false; }; for(Configuration* depCfg : cfg.dependencies) { if (walk(depCfg)) return true; } return false; } } void Configuration::ResolvePendingImports() { // Same resolution the scan used, and against both dependency kinds — a // second GetInterfacesAndImplementations call can add interfaces that an // earlier batch's import was looking for, so a pending name may land on a // local module and not just an external one. auto sweep = [this](std::vector& pending, std::vector& localDeps, std::vector>& externalDeps) { std::erase_if(pending, [&](const std::string& name) { return ResolveImportName(*this, name, localDeps, externalDeps); }); }; for(const std::unique_ptr& interface : interfaces) { sweep(interface->pendingImports, interface->moduleDependencies, interface->externalModuleDependencies); for(const std::unique_ptr& partition : interface->partitions) { sweep(partition->pendingImports, partition->moduleDependencies, partition->externalModuleDependencies); } } for(Implementation& implementation : implementations) { sweep(implementation.pendingImports, implementation.moduleDependencies, implementation.externalModuleDependencies); } } void Configuration::GetInterfacesAndImplementations(std::span interfaces, std::span implementations) { auto resolveImport = [this](const std::string& importName, std::vector& localDeps, std::vector>& externalDeps, std::vector& pending) { if (!ResolveImportName(*this, importName, localDeps, externalDeps)) { pending.push_back(importName); } }; std::vector> tempModulePaths = std::vector>(interfaces.size()); for(std::uint16_t i = 0; i < interfaces.size(); i++){ // Resolve to absolute now so the stored path survives cwd changes // (matters for GitProject deps loaded from a different working dir). fs::path file = fs::absolute(path / interfaces[i]).lexically_normal(); file += ".cppm"; std::ifstream t(file); std::stringstream buffer; buffer << t.rdbuf(); std::string fileContent = buffer.str(); fileContent = std::regex_replace(fileContent, std::regex(R"(//[^\n]*)"), ""); fileContent = std::regex_replace(fileContent, std::regex(R"(/\*.*?\*/)"), ""); tempModulePaths[i] = {file, fileContent, nullptr, nullptr}; } // Primary interface units first, so the partition pass below can find their // parent Module. They stay in tempModulePaths — a primary unit's own // `import X;` lines are layout dependencies exactly like a partition's, and // dropping the entry here is what left them unrecorded (issue #26). Marked // by a null partition slot with the Module slot filled in. for(std::tuple& file : tempModulePaths) { std::smatch match; if (std::regex_search(std::get<1>(file), match, std::regex(R"(export module ([a-zA-Z0-9_\.\-]+);)"))) { fs::path pthCpy = std::get<0>(file); pthCpy.replace_extension(""); this->interfaces.push_back(std::make_unique(std::move(match[1].str()), std::move(pthCpy))); std::get<3>(file) = this->interfaces.back().get(); } } for(std::uint16_t i = 0; i < tempModulePaths.size(); i++) { std::smatch match; if (std::get<3>(tempModulePaths[i]) != nullptr) { continue; } if (std::regex_search(std::get<1>(tempModulePaths[i]), match, std::regex(R"(export module ([a-zA-Z_0-9\.\-]+):([a-zA-Z_0-9\.\-]+);)"))) { for(const std::unique_ptr& modulee : this->interfaces) { if(modulee->name == match[1]) { std::string name = match[2].str(); fs::path pthCpy = std::get<0>(tempModulePaths[i]); pthCpy.replace_extension(""); std::unique_ptr partition = std::make_unique(std::move(name), std::move(pthCpy)); std::get<2>(tempModulePaths[i]) = partition.get(); modulee->partitions.push_back(std::move(partition)); std::get<3>(tempModulePaths[i]) = modulee.get(); goto next; } } throw std::runtime_error(std::format("Module {} not found, referenced in {}", match[1].str(), std::get<0>(tempModulePaths[i]).string())); } else { throw std::runtime_error(std::format("No module declaration found in {}", std::get<0>(tempModulePaths[i]).string())); } next:; } for(std::tuple& file : tempModulePaths) { ModulePartition* partition = std::get<2>(file); Module* parentModule = std::get<3>(file); const std::string& fileContent = std::get<1>(file); // Primary interface unit: record only its module imports. Its // `[export] import :Part;` lines need no edge — Module::Check walks // every partition it owns and Module::Schedule puts the primary // interface after all of them, so partitions are covered wholesale. if (partition == nullptr) { std::regex primaryPattern(R"(import ([a-zA-Z_0-9\.\-]+);)"); std::sregex_iterator primaryCurrent(fileContent.begin(), fileContent.end(), primaryPattern); std::sregex_iterator primaryLast; while (primaryCurrent != primaryLast) { std::smatch match = *primaryCurrent; resolveImport(match[1].str(), parentModule->moduleDependencies, parentModule->externalModuleDependencies, parentModule->pendingImports); ++primaryCurrent; } continue; } std::regex partitionPattern(R"(import :([a-zA-Z_\-0-9\.]+);)"); std::sregex_iterator currentMatch(fileContent.begin(), fileContent.end(), partitionPattern); std::sregex_iterator lastMatch; while (currentMatch != lastMatch) { std::smatch match = *currentMatch; for(std::unique_ptr& sibling : parentModule->partitions) { if(sibling->name == match[1]) { partition->partitionDependencies.push_back(sibling.get()); goto next2; } } throw std::runtime_error(std::format("imported partition {}:{} not found, referenced in {}", parentModule->name, match[1].str(), std::get<0>(file).string())); next2: ++currentMatch; } std::regex modulePattern(R"(import ([a-zA-Z_0-9\.\-]+);)"); std::sregex_iterator modCurrent(fileContent.begin(), fileContent.end(), modulePattern); while (modCurrent != lastMatch) { std::smatch match = *modCurrent; resolveImport(match[1].str(), partition->moduleDependencies, partition->externalModuleDependencies, partition->pendingImports); ++modCurrent; } } for(const fs::path& tempFile : implementations) { fs::path file = fs::absolute(path / tempFile).lexically_normal(); file += ".cpp"; std::ifstream t(file); std::stringstream buffer; buffer << t.rdbuf(); std::string fileContent = buffer.str(); fileContent = std::regex_replace(fileContent, std::regex(R"(//[^\n]*)"), ""); fileContent = std::regex_replace(fileContent, std::regex(R"(/\*.*?\*/)"), ""); std::smatch match; fs::path fileCopy = file; fileCopy.replace_extension(""); Implementation& implementation = this->implementations.emplace_back(std::move(fileCopy)); if (std::regex_search(fileContent, match, std::regex(R"(module ([a-zA-Z0-9_\.\-]+)(:[a-zA-Z0-9_\.\-]+)?\s*;)"))) { const bool isPartitionImpl = match[2].length() > 0; for(const std::unique_ptr& interface : this->interfaces) { if(interface->name == match[1]) { if (!isPartitionImpl) { implementation.moduleDependencies.push_back(interface.get()); } std::regex partitionPattern(R"(import :([a-zA-Z_\-0-9\.]+);)"); std::sregex_iterator currentMatch(fileContent.begin(), fileContent.end(), partitionPattern); std::sregex_iterator lastMatch; while (currentMatch != lastMatch) { std::smatch match2 = *currentMatch; for(const std::unique_ptr& partition : interface->partitions) { if(partition->name == match2[1]) { implementation.partitionDependencies.push_back(partition.get()); goto next3; } } throw std::runtime_error(std::format("imported partition {}:{} not found, referenced in {}", match[1].str(), match2[1].str(), file.string())); next3: ++currentMatch; } std::regex modulePattern(R"(import ([a-zA-Z_0-9\.\-]+);)"); std::sregex_iterator modCurrent(fileContent.begin(), fileContent.end(), modulePattern); while (modCurrent != lastMatch) { std::smatch match2 = *modCurrent; if (match2[1] != match[1]) { resolveImport(match2[1].str(), implementation.moduleDependencies, implementation.externalModuleDependencies, implementation.pendingImports); } ++modCurrent; } goto next4; } } throw std::runtime_error(std::format("Module {} not found not found, referenced in {}", match[1].str(), file.string())); next4:; } else { std::regex pattern(R"(import ([a-zA-Z_\-0-9\.]+);)"); std::sregex_iterator currentMatch(fileContent.begin(), fileContent.end(), pattern); std::sregex_iterator lastMatch; while (currentMatch != lastMatch) { std::smatch match2 = *currentMatch; resolveImport(match2[1].str(), implementation.moduleDependencies, implementation.externalModuleDependencies, implementation.pendingImports); ++currentMatch; } } } } std::string Crafter::StdPcmFlags(const Configuration& config) { if (config.target == "x86_64-w64-mingw32") { // -femulated-tls keeps PCM TLS access matching libstdc++'s emutls // definitions; a mismatch surfaces as undefined std::__once_callable. return std::format(" --target={} -march={} -mtune={} -femulated-tls -O3 -std=c++26 -Wno-reserved-identifier -Wno-reserved-module-identifier", config.target, config.march, config.mtune); } const bool isWasm = config.target.starts_with("wasm32"); const std::string sysrootFlag = config.sysroot.empty() ? std::string() : std::format(" --sysroot={}", config.sysroot); // wasm32 rejects -march, and the std module has to be compiled the way // the units importing it are, a variant pass's flags (e.g. // -mrelaxed-simd) included, or the BMI is not feature-compatible. std::string archFlags = isWasm ? WasmCompileFlags(config) : std::format(" -march={} -mtune={}", config.march, config.mtune); // non-wasm cross builds: the driver ranks the host toolchain's own // libc++ headers (/../include/c++/v1) above --sysroot, so the // PCM would mix host libc++ with the foreign libc. Force the sysroot's // copy. if (!isWasm && !config.sysroot.empty()) { archFlags += std::format(" -nostdinc++ -isystem {}/usr/include/c++/v1", config.sysroot); } return std::format(" --target={} -std=c++26{}{} -O3 -Wno-reserved-identifier -Wno-reserved-module-identifier", config.target, sysrootFlag, archFlags); } std::string Crafter::StdPcmKey(const Configuration& config, const Toolchain& toolchain) { // A PCM is only valid for the clang that wrote it and the flags it was // written with, so a compiler bump starts a cold directory instead of // handing the new clang a PCM it will crash on, and so does any flag. // With only some of them in the name, configurations that differed in // the rest took turns rebuilding one std PCM in place: -mtune=generic // against project.cpp's -mtune=native on every run, two sysroots, or two // releases sharing a cache, as the Flatpak's branches do, each time under // the PCMs built against the previous one, which clang crashes on rather // than rejecting. std::string compiled = StdPcmFlags(config); // The base command's part: the toolchain's key covers the compiler and // libc++, and for the mingw target what clang finds mingw-w64 through is // the prefix, given whole or through a view (MingwSysroot), named here by // the prefix rather than by the view's own path. if (config.target == "x86_64-w64-mingw32" && !toolchain.mingwPrefix.empty()) { compiled += std::format("|mingw:{}|{}", toolchain.mingwPrefix.string(), toolchain.mingwPrefixIsSystem ? "view" : "whole"); } return std::format("{}-{}-{}-{:08x}", config.target, config.march, toolchain.Key(), static_cast(std::hash{}(compiled))); } fs::path Crafter::StdPcmDir(const Configuration& config) { return GetCacheDir() / StdPcmKey(config, GetToolchain()); } std::string Crafter::WasmCompileFlags(const Configuration& config) { std::string flags = std::format(" {}", WasmBaselineFlags); for (const std::string& f : config.wasmVariantFlags) flags += std::format(" {}", f); return flags; } fs::path Crafter::ExpectedOutput(const Configuration& config) { const fs::path dir = config.ProgramDir(); const bool mingwTarget = config.target == "x86_64-w64-mingw32"; if (config.type == ConfigurationType::Executable) { if (config.target.starts_with("wasm32")) return dir / std::format("{}.wasm", config.outputName); return mingwTarget ? dir / std::format("{}.exe", config.outputName) : dir / config.outputName; } if (config.type == ConfigurationType::LibraryStatic) { // The archive step writes lib.a for every target, mingw included: // llvm-ar does not care about the object format. return dir / std::format("lib{}.a", config.outputName); } // LibraryDynamic — the .dll on the mingw target so an mtime check sees the // freshly linked library; on Unix the .so is that file. return mingwTarget ? dir / std::format("{}.dll", config.outputName) : dir / std::format("lib{}.so", config.outputName); } CompileCommand Crafter::GetCompileCommand(const Configuration& config) { CompileCommand out; out.stdPcmDir = StdPcmDir(config); out.pcmDir = config.PcmDir(); std::string editedTarget = config.target; std::replace(editedTarget.begin(), editedTarget.end(), '-', '_'); // wasm32 targets reject -march and silently ignore -mtune (clang errors on // the former). Skip both for any wasm32-* triple. const bool isWasm = config.target.starts_with("wasm32"); std::string archFlags = isWasm ? std::string() : std::format(" -march={} -mtune={}", config.march, config.mtune); out.command = std::format("{} --target={}{} -std=c++26 -D CRAFTER_BUILD_CONFIGURATION_TARGET=\\\"{}\\\" -D CRAFTER_BUILD_CONFIGURATION_TARGET_{} -fprebuilt-module-path={} -fprebuilt-module-path={}", GetBaseCommand(config), config.target, archFlags, editedTarget, editedTarget, out.stdPcmDir.string(), out.pcmDir.string()); if (!config.sysroot.empty()) { out.command += std::format(" --sysroot={}", config.sysroot); // Same reason as in BuildStdPcm: the driver ranks the host // toolchain's own libc++ headers (/../include/c++/v1) above // --sysroot. A unit that only does `import std;` never notices, but // one that includes a standard header textually (vendored C++ such as // Crafter.Asset's gdeflate) would get host libc++ configured for the // host libc, which fails on a musl sysroot with "unknown rune table // for this platform". Force the sysroot's copy. -nostdinc++ leaves // -stdlib=libc++ unused on every compile ("argument unused during // compilation"), hence the silencer; the price is that it also hides // that diagnostic for a user's own misplaced flag (a -l or -Wl, // option in compileFlags) on sysroot builds. Not for mingw, which // uses libstdc++ and has no libc++ in its sysroot. if (!isWasm && config.target != "x86_64-w64-mingw32") { out.command += std::format(" -nostdinc++ -isystem {}/usr/include/c++/v1 -Wno-unused-command-line-argument", config.sysroot); } } if (isWasm) { // -mllvm is consumed by codegen but not the link driver, which is the // same command line; quiet the unused-flag warning rather than split // compile and link commands. An active variant pass (see the variant // driver at the end of Build) adds its codegen flags (e.g. // -mrelaxed-simd) to every TU; they are part of VariantId, so those // objects/PCMs land in their own dir. out.command += std::format("{} -Wno-unused-command-line-argument", WasmCompileFlags(config)); } if (config.target == "x86_64-w64-mingw32") { // mingw libstdc++ defines TLS via __emutls_v.* (emulated TLS); without // -femulated-tls clang generates native-TLS references that don't // match. Symptom: undefined std::__once_callable / __once_call at // link time. Also -Wno-unused… because -femulated-tls is a codegen // flag the link driver doesn't consume. out.command += " -femulated-tls -Wno-unused-command-line-argument"; } if(config.type == ConfigurationType::LibraryDynamic) { out.command += " -fPIC -D CRAFTER_BUILD_CONFIGURATION_TYPE_SHARED_LIBRARY"; } else if(config.type == ConfigurationType::Executable) { out.command += " -D CRAFTER_BUILD_CONFIGURATION_TYPE_EXECUTABLE"; } else { out.command += " -D CRAFTER_BUILD_CONFIGURATION_TYPE_LIBRARY"; } // -I propagation that's valid for both C and C++ compiles. Module-only // bits (-fprebuilt-module-path) stay on `command` only. { // bin/ and build/ hold what builds write for the configuration whose // path holds them: crafter-build's own outputs (BinDir(), BuildDir()) // and whatever else a build leaves there, a CMake build tree or a // flatpak-builder /app tree among it, whose include/ holds another // library's or toolchain's headers and never the dependency's own. // The walk leaves out every directory of those names, not only the // graph's: a dependency's tree holds the outputs of configurations // outside the graph too, a program in a directory below it or a // project of its own beside it, as Crafter.Graphics' examples are. // Walked, they would have every compile built on the dependency take // those headers before the system's, and what compiled depend on // which builds had run. std::unordered_set seen; std::function addFlags = [&](Configuration* dep) { if (!seen.insert(dep).second) return; for (auto it = fs::recursive_directory_iterator(dep->path); it != fs::recursive_directory_iterator(); ++it) { if (!it->is_directory()) continue; const fs::path name = it->path().filename(); if (name == "bin" || name == "build") { it.disable_recursion_pending(); } else if (name == "include") { out.includeFlags += std::format(" -I{}", it->path().string()); } } out.includeFlags += std::format(" -I{}", dep->path.string()); out.command += std::format(" -fprebuilt-module-path={}", dep->PcmDir().string()); for (Configuration* sub : dep->dependencies) { addFlags(sub); } }; for (Configuration* dep : config.dependencies) { addFlags(dep); } } out.command += out.includeFlags; // External dependency includes, gathered transitively. Kept off `command` // so it stays exactly what it was before this was extracted. { std::unordered_set seen; std::function addExternal = [&](const Configuration* cfg) { if (!seen.insert(cfg).second) return; for (const ExternalDependency& dep : cfg->externalDependencies) { for (const std::string& flag : ExternalIncludeFlags(dep, cfg->target)) { out.externalIncludeFlags += std::format(" {}", flag); } } for (const Configuration* sub : cfg->dependencies) addExternal(sub); }; addExternal(&config); } // Defines belong on both C and C++ compiles so vendored C dependencies // can see configuration-level macros consistently with module sources. for(const Define& define : config.defines) { if(define.value.empty()) { out.defineFlags += std::format(" -D {}", define.name); } else { out.defineFlags += std::format(" -D {}={}", define.name, define.value); } } out.command += out.defineFlags; // Track caller-provided compileFlags separately so the .c compile can // pick them up too (vendored C deps usually need -I from this set). for(const std::string& flag : config.compileFlags) { out.userFlags += std::format(" {}", flag); } out.command += out.userFlags; // Behaviour-neutral release performance for the binaries we emit: ThinLTO // (cross-TU inlining) plus dead-section GC and safe identical-code folding. // Default-on in Release, never Debug (keeps builds fast and debuggable). // Excluded for wasm32 — its -mllvm/sjlj codegen flags don't compose with // LTO here, and wasi-sdk lists exceptions under LTO as broken // (WebAssembly/wasi-sdk#629) — and for nvcc .cu objects below (they can't // emit LLVM bitcode, so they link in as ordinary objects alongside the // bitcode ones). ThinLTO rather than monolithic -flto so link time and // memory scale with arbitrary user project sizes. Compile-side flags // (-flto, -ffunction/-fdata-sections) ride on `command`, which is reused // as the link base; the link-only -Wl flags go on linkExtras so they // don't warn on each -c compile. out.useLto = !config.debug && !isWasm; out.ltoCompileFlags = out.useLto ? " -flto=thin -ffunction-sections -fdata-sections" : ""; out.ltoLinkFlags = out.useLto ? " -flto=thin -Wl,--gc-sections -Wl,--icf=safe" : ""; if(config.debug) { out.command += " -g -D CRAFTER_BUILD_CONFIGURATION_DEBUG"; } else { out.command += " -O3"; } out.command += out.ltoCompileFlags; return out; } namespace { // The outcome of `work` for `key` in this build pass. The first caller // runs it; every other caller, whether at the same time or later, waits // for that run and gets its result or its exception. The keys are the // directories the work writes, a configuration's PcmDir and an external // dependency's ExternalBuildDir, so the two kinds never collide. std::shared_future OncePerPass(std::unordered_map>& depResults, std::mutex& depMutex, const fs::path& key, const std::function& work) { std::promise promise; std::shared_future outcome = promise.get_future().share(); { std::lock_guard lock(depMutex); if (auto [it, inserted] = depResults.try_emplace(key, outcome); !inserted) return it->second; } try { promise.set_value(work()); } catch (...) { promise.set_exception(std::current_exception()); } return outcome; } // Two configurations among `config` and its transitive dependencies that // export a module of the same name: the same project loaded along two // paths with different args, say, or from a checkout on one path and a // clone on the other. A program can hold one module of each name. Built // anyway, both PCM dirs went onto the consumer's -fprebuilt-module-path, // clang resolved the module by name to the first for every import, the // ones inside the other build's consumers included, and nothing checked // that it was the build they had been compiled against. The program then // linked code compiled against two layouts of the same types, and ran // (issue #41). Empty when the dependencies agree, otherwise the error, // naming the path to each of the two builds. std::string DuplicateModuleError(const Configuration& config) { struct Owner { const Configuration* cfg; std::string chain; }; const auto describe = [](const Owner& owner) { return std::format("{} ({}, {}, project args {})", owner.chain, owner.cfg->path.string(), owner.cfg->VariantId(), owner.cfg->projectArgs); }; std::unordered_map owners; std::unordered_set visited; std::string error; std::function walk = [&](const Configuration& c, const std::string& chain) { if (!error.empty() || !visited.insert(&c).second) return; for (const std::unique_ptr& iface : c.interfaces) { const auto [it, inserted] = owners.emplace(iface->name, Owner{ &c, chain }); if (inserted || it->second.cfg == &c) continue; error = std::format("module {} is built twice for {}:\n {}\n {}\nA program can hold one build of each module: load {} with the same args, and from the same place, along every path.", iface->name, config.name, describe(it->second), describe(Owner{ &c, chain }), c.name); return; } for (const Configuration* dep : c.dependencies) walk(*dep, std::format("{} -> {}", chain, dep->name)); }; walk(config, config.name); return error; } // Interface units of `config` that are each built after the next, round // to the first again: partitions that import each other, a partition that // imports its own module, sibling modules that import each other. Empty // when there are none, otherwise the error naming the round. No order // builds such units. Schedule() works the order out before it adds a // unit's jobs, by following the imports, and would follow a round of // them without end. When each unit had a thread that waited for the // units it imports, such a build hung with no compiler running. // // The imports are the scanner's, which reads one in a string literal, in // a comment that spans lines or under `#if 0` as it reads any other // (issue #45): the units named are where to look for one of those as // well, and the error says so, since the compiler sees no round there. std::string ImportCycleError(const Configuration& config) { struct Unit { std::string name; std::vector builtAfter; bool entered = false; bool left = false; }; // By address: a module and a partition are different types, and a // unit's imports name either. Walked in the order the units were // declared, so the same project gets the same message every time. std::unordered_map units; std::vector declared; for (const std::unique_ptr& module : config.interfaces) { declared.push_back(module.get()); Unit& primary = units[module.get()]; primary.name = module->name; for (const Module* imported : module->moduleDependencies) primary.builtAfter.push_back(imported); for (const std::unique_ptr& partition : module->partitions) { // The primary interface is built after every partition of // its module, whether it imports that one or not. primary.builtAfter.push_back(partition.get()); declared.push_back(partition.get()); Unit& unit = units[partition.get()]; unit.name = std::format("{}:{}", module->name, partition->name); for (const ModulePartition* imported : partition->partitionDependencies) unit.builtAfter.push_back(imported); for (const Module* imported : partition->moduleDependencies) unit.builtAfter.push_back(imported); } } std::vector chain; std::string round; std::function visit = [&](Unit& unit) { if (!round.empty() || unit.left) return; if (unit.entered) { // Back at a unit this walk is still inside of: the round is // the chain from where it was entered. for (auto it = std::ranges::find(chain, &unit); it != chain.end(); ++it) round += std::format("{} -> ", (*it)->name); round += unit.name; return; } unit.entered = true; chain.push_back(&unit); for (const void* before : unit.builtAfter) { if (const auto found = units.find(before); found != units.end()) visit(found->second); } chain.pop_back(); unit.left = true; }; for (const void* unit : declared) visit(units.at(unit)); if (round.empty()) return ""; return std::format("{}: these interface units are each built after the next, so none can be built first: {}. A unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions. The imports are read from the source text without compiling it: one in a string literal, in a comment that spans lines or under #if 0 counts too.", config.name, round); } // What a wasm32 configuration cannot be built with now that every unit // has C++ exceptions, and what its sysroot has to have for that; empty // for any other target and when nothing is wrong. Each would otherwise // fail at the first compile or link with a message that does not say // why, or not fail at all. std::string WasmBuildError(const Configuration& config) { if (!config.target.starts_with("wasm32")) return ""; for (const std::vector* flags : { &config.compileFlags, &config.linkFlags }) { for (const std::string& flag : *flags) { // The compile has the backend options that keep exception // handling; LTO code generation at the link does not, so it // drops every landing pad and the build succeeds with throws // that escape their catch blocks (WebAssembly/wasi-sdk#629). if (flag.starts_with("-flto")) { return std::format("{}: {} is not supported on wasm32: LTO code generation drops C++ exception handling (WebAssembly/wasi-sdk#629), so every throw would escape its catch", config.name, flag); } // The std module is built with exceptions, and a unit built // without them cannot import it. if (flag == "-fno-exceptions" || flag == "-fno-cxx-exceptions") { return std::format("{}: {} is not supported on wasm32: wasm builds have C++ exceptions, the std module included, and a unit compiled without them cannot import std", config.name, flag); } } } // wasi-sdk's exception support does not cover shared libraries: the // libc++ under lib//eh is static archives built without -fPIC. if (config.type == ConfigurationType::LibraryDynamic) { return std::format("{}: wasm32 shared libraries are not supported: the exception-enabled libc++ they would link has static archives only", config.name); } const fs::path sysroot = config.sysroot; if (!fs::is_directory(sysroot)) { return std::format("no WASI sysroot at {}: the Flatpak bundles one, and CRAFTER_BUILD_WASI_SYSROOT selects another", sysroot.string()); } const fs::path libDir = sysroot / "lib" / NormalizeTarget(config.target); if (!fs::is_directory(libDir)) { return std::format("the WASI sysroot at {} has nothing for {} (no {})", sysroot.string(), config.target, libDir.string()); } // Only a link takes the exception-enabled libraries: a static // library's objects compile against the headers alone. The driver // looks in eh/ first and then in the triple's own directory, where a // sysroot built with exceptions only (WASI_SDK_EXCEPTIONS=ON) has them. // Without them the first link fails with "unable to find library // -lunwind", which says nothing about why it was asked for. if (config.type == ConfigurationType::Executable && !fs::exists(libDir / "eh" / "libunwind.a") && !fs::exists(libDir / "libunwind.a")) { return std::format("the WASI sysroot at {} has no C++ exception support (no {}): wasm builds use WebAssembly exception handling and need the exception-enabled libc++ and libunwind that wasi-sdk 33 and later ship. The Flatpak bundles such a sysroot; CRAFTER_BUILD_WASI_SYSROOT selects another", sysroot.string(), (libDir / "eh" / "libunwind.a").string()); } return ""; } // Why `config` cannot be the Flatpak it asks for; empty when it can be, // or does not ask. Checked before anything is built, like WasmBuildError: // each of these would otherwise surface as an app that does not start // once installed, or not at all on the machine it was meant for. std::string FlatpakBuildError(const Configuration& config) { if (config.ResolvedPackaging() != Packaging::Flatpak) return ""; if (config.target == "x86_64-w64-mingw32") return std::format("{}: a Windows executable is not packaged as a Flatpak; it stays an .exe", config.name); if (config.target.starts_with("wasm32")) return std::format("{}: a wasm build is not packaged as a Flatpak; it stays a .wasm", config.name); const Toolchain& tc = GetToolchain(); if (tc.flatpakBranch.empty()) { return std::format("{}: only the Flatpak crafter-build packages a Flatpak: a native one links the program against the host's glibc and libc++, which no Flatpak runtime matches", config.name); } if (!config.sysroot.empty()) { return std::format("{}: a build against a sysroot ({}) links that sysroot's libraries, its C library among them, and not those of the runtime the app runs on", config.name, config.sysroot); } if (NormalizeTarget(config.target) != std::format("{}-linux-gnu", tc.flatpakArch)) { if (config.target.ends_with("-linux-musl")) return std::format("{}: {} links musl, which no Flatpak runtime provides", config.name, config.target); return std::format("{}: {} is not packaged as a Flatpak: the runtime crafter-build runs on, and the libc++ it would bundle, are {}", config.name, config.target, tc.flatpakArch); } // The libc++ a Flatpak carries is the toolchain's own, built against // the runtime's glibc. One from CRAFTER_BUILD_LIBCXX_DIR is what the // program would be compiled and linked against instead, and nothing // says which glibc it needs: bundled, it may not load on the // runtime; not bundled, the program loads a libc++ it was not built // against. if (!tc.libcxxDir.empty()) { return std::format("{}: a build against CRAFTER_BUILD_LIBCXX_DIR ({}) links that libc++, and a Flatpak carries the toolchain's own, built against the runtime's glibc: unset it to package a Flatpak", config.name, tc.libcxxDir.string()); } return ""; } // What an asset is compressed to, by the extension Crafter.Asset reads: // the formats stb_image loads (behind TextureAsset::LoadPNG) to .ctex, // .obj to .cmesh; nullopt for anything else. The one rule for an // executable's own assets and the ones its dependencies forward to it. std::optional CompressedAssetName(const fs::path& src) { std::string ext = src.extension().string(); for (char& c : ext) c = static_cast(std::tolower(static_cast(c))); if (ext == ".png" || ext == ".tga" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp") { return fs::path(src.filename()).replace_extension(".ctex"); } if (ext == ".obj") return fs::path(src.filename()).replace_extension(".cmesh"); return std::nullopt; } std::string AppIdOf(const Configuration& config) { return config.flatpak.appId.empty() ? DefaultFlatpakAppId(config.outputName) : config.flatpak.appId; } // The sandbox's permissions as the executable gets them: a dependency's // dependencies before it, each once, and the executable's own last, so // it has the last word. std::vector PermissionsOf(const Configuration& config) { std::vector permissions; std::unordered_set seen; std::function walk = [&](const Configuration* c) { if (!seen.insert(c).second) return; for (const Configuration* dep : c->dependencies) walk(dep); for (const std::string& permission : c->flatpak.permissions) permissions.push_back({permission, c->name}); }; for (const Configuration* dep : config.dependencies) walk(dep); for (const std::string& permission : config.flatpak.permissions) permissions.push_back({permission, config.name}); return permissions; } // The writer's record: one per bin dir, as there is one bin dir per // BuildDir(). VariantId() does not hold outputName, and under a name of // its own the record of a program renamed in place was not found, so // the old program stayed in files/bin as one it wrote. fs::path FlatpakRecordPath(const Configuration& config) { return config.BuildDir() / "flatpak-record"; } // Gathers what WriteFlatpakFiles needs from `config`, the link that just // ran and the top-level names Build()'s copies placed in files/bin, and // has it lay out files/. std::string WriteFlatpak(const Configuration& config, const BuildResult& linked, const std::set& placed) { const Toolchain& tc = GetToolchain(); FlatpakFiles d; d.root = config.BinDir(); d.record = FlatpakRecordPath(config); d.appId = AppIdOf(config); d.command = ExpectedOutput(config).filename().string(); d.desktopFile = config.flatpak.desktopFile; d.metainfo = config.flatpak.metainfo; d.icons = config.flatpak.icons; d.share = config.flatpak.share; d.appDir = FlatpakAppDir(config); d.clangxx = tc.clangxx; d.readelf = tc.llvmReadelf; for (const std::string& dir : linked.runPaths) d.libraryDirs.emplace_back(dir); // Last, the toolchain's own lib dir, which the link searches as well // (LibcxxSearchFlags): a library it takes from there, libclang or // libedit of crafter-build's /app/lib, is no runtime's. -r would not // show it missing, since crafter-build's sandbox has /app/lib on the // loader's path, but the installed app would not start. if (const fs::path toolchainLib = tc.LibcxxLibDir(); !toolchainLib.empty()) d.libraryDirs.push_back(toolchainLib); d.programEntries = placed; return WriteFlatpakFiles(d); } } BuildResult Crafter::Build(Configuration& config, std::unordered_map>& depResults, std::mutex& depMutex) { // Before anything is spawned: one message naming the missing compiler // beats a clang++-not-found per translation unit. if (const Toolchain& tc = GetToolchain(); !tc.error.empty()) { return {tc.error, false, {}}; } // Before any directory is made or dependency built, so a refused graph // leaves nothing behind. if (std::string duplicate = DuplicateModuleError(config); !duplicate.empty()) { return {std::move(duplicate), false, {}}; } // Reset per-build cached state on every Module/ModulePartition so that // successive Build() calls on the same Configuration re-evaluate mtimes // (incremental-rebuild test scenarios). // // Reset ONLY this configuration's own modules — never recurse into // dependencies. Configuration objects are shared across the dependency DAG // (diamond deps point at the same Configuration*), and every config in the // tree gets its own Build() call: the per-PcmDir builder registered in // depResults resets its own state here, at the top of its own Build(), // sequenced before that config's units are checked and scheduled. // Recursing into dependencies from here would clear a shared dependency's // state from a parent/sibling thread *while that dependency's own Build() // is using it*: a unit whose `scheduled` is cleared between two of that // build's Schedule() calls is scheduled a second time, and two compilers // write one BMI. When every unit had a thread of its own that waited on a // `compiled` flag of each unit it imports, the reset cleared that flag // under a waiter, which then blocked forever on a flag nothing // re-signalled: the build froze mid-compile, idle, with no compiler // process alive (issue #16). Cross-config module state is consulted only via // PCM file mtimes and the depResults futures, never via this state, so the // narrower reset is correct. for (auto& iface : config.interfaces) { iface->checked = false; iface->scheduled = false; iface->precompileJob.reset(); for (auto& part : iface->partitions) { part->checked = false; part->scheduled = false; part->precompileJob.reset(); } } // Sources were scanned when they were declared, which for most callers is // before `dependencies` exists — AddTest resolves tests//main.cpp and // only then hands back a builder whose .Dependencies() supplies the library. // Any `import ;` in such a TU resolved to nothing and so carried // no staleness edge, which meant a member added to a dependency's interface // rebuilt the library, relinked the consumer, and silently kept the // consumer's object compiled against the *old* class layout (issue #27). // Re-resolving here — the last point before mtimes are compared, with the // DAG fully wired — closes that window for every caller rather than for the // ones that remember to declare in the right order. config.ResolvePendingImports(); // With every import placed, and before this configuration makes a // directory or builds a dependency. A configuration built on this one // has started its own build by then: the imports just placed are this // Build()'s to read, so no other configuration's can check them for it. if (std::string cycle = ImportCycleError(config); !cycle.empty()) { return {std::move(cycle), false, {}}; } // Auto-detect the WASI sysroot before any compile step runs so BuildStdPcm // and the main compile command see the same value. Covers all wasm32-* // triples (wasi, wasip1, wasip2, ...); the sysroot's per-triple subdirs // handle the differences. if (config.sysroot.empty() && config.target.starts_with("wasm32")) { config.sysroot = GetToolchain().wasiSysroot.string(); } // As early as the duplicate-module check, so a refused build leaves no // directory behind and starts no thread, but after the sysroot is known. // A Flatpak asked of a target that cannot be one says so before anything // the target itself would refuse: that is the request to change. if (std::string refused = FlatpakBuildError(config); !refused.empty()) { return {std::move(refused), false, {}}; } if (std::string refused = WasmBuildError(config); !refused.empty()) { return {std::move(refused), false, {}}; } fs::path buildDir = config.BuildDir(); // Everything this configuration produces lands here: a library's archive // and module PCMs, an executable and the files it reads at run time. fs::path outputDir = config.ProgramDir(); // The top-level names this build places in outputDir, which a Flatpak's // writer keeps in files/bin and an earlier build's it removes. Each copy // below records its own destination as it decides it: the name that // follows outputDir in it, or, for a directory copied into outputDir // itself ("data/", "data/."), the names of what that directory holds. std::set placed = {ExpectedOutput(config).filename().string()}; const auto withoutSeparator = [](fs::path path) { path = fs::absolute(path).lexically_normal(); return path.has_filename() ? path : path.parent_path(); }; const fs::path outputRoot = withoutSeparator(outputDir); const auto place = [&](const fs::path& destination, const fs::path& source) { const fs::path normal = withoutSeparator(destination); if (normal != outputRoot) { placed.insert(normal.lexically_relative(outputRoot).begin()->string()); return; } std::error_code ec; for (const fs::directory_entry& child : fs::directory_iterator(source, ec)) placed.insert(child.path().filename().string()); }; // A build that fails has copied into files/bin all the same, so what it // placed joins the writer's record on every way out of Build(): the next // write removes what no build places any more, rather than take it for // a file the program wrote. After a write, the record holds these names // already. struct PlacedOnExit { const Configuration& config; const std::set& names; ~PlacedOnExit() { if (config.ResolvedPackaging() == Packaging::Flatpak) RecordFlatpakPlaced(FlatpakRecordPath(config), names); } }; const PlacedOnExit placedOnExit{config, placed}; if (!fs::exists(buildDir)) { fs::create_directories(buildDir); } if (!fs::exists(outputDir)) { fs::create_directories(outputDir); } BuildResult buildResult{}; // glslang #include search paths for every shader compiled in this // configuration: each transitive (incl. self) buildFiles entry's parent // dir, or the entry itself if it points at a directory. Collected once // up front so the per-shader jobs can capture the resulting span by // reference. No file copy involved — glslang reads the includes in // place from the dep's source tree. std::vector shaderIncludeDirs; { std::unordered_set seenDirs; std::unordered_set seenCfg; std::function collect = [&](const Configuration* c) { if (!seenCfg.insert(c).second) return; for (const fs::path& bf : c->buildFiles) { fs::path dir = fs::is_directory(bf) ? bf : bf.parent_path(); if (seenDirs.insert(dir.string()).second) { shaderIncludeDirs.push_back(std::move(dir)); } } for (const Configuration* sub : c->dependencies) collect(sub); }; collect(&config); } // A stale shader, asset to compress, C, CUDA or C++ unit is a job of this // group; each used to get a thread of its own the moment it was found // stale. The copies of cfg.files and of the other files of an asset // directory are jobs as well. The jobs run on the workers every build of // the process shares, so no more of them run at once than the machine // has hardware threads. // // The group also holds the first error among its jobs and what this // build reports to it (Fail), the dependency and external builds below // among it, and none of its jobs starts after one. What goes wrong once // the jobs are done, at the link, is not the group's. // // Declared after everything its jobs use by reference: leaving Build() // waits for them before any of that is destroyed. A job gets a copy of // whatever it uses that is declared below here. JobGroup jobs; // Two entries with the same output name would compile in parallel into // one file: whichever finished last won, the build reported success, and // Check() then called both up to date. The usual way in is one source // registered twice with different defines and no variant; a.vert next to // a.frag is another. { std::unordered_map outputs; for (const Shader& shader : config.shaders) { const auto [existing, inserted] = outputs.emplace(shader.OutputName().string(), &shader); if (inserted) continue; jobs.Fail(std::format("shaders {} and {} both compile to {}: give one of them a distinct Shader::variant", existing->second->path.string(), shader.path.string(), existing->first)); break; } } for (const Shader& shader : config.shaders) { if (jobs.Failed()) break; place(outputDir / shader.OutputName(), {}); if (shader.Check(outputDir, buildDir, shaderIncludeDirs)) continue; // A source registered more than once shows up once per variant; // name the variant so the lines can be told apart. jobs.Add(shader.variant.empty() ? std::format("Compiling shader {}", shader.path.filename().string()) : std::format("Compiling shader {} ({})", shader.path.filename().string(), shader.variant), [&shader, &outputDir, &buildDir, &shaderIncludeDirs] { return shader.Compile(outputDir, buildDir, shaderIncludeDirs); }); } // Asset compilation: each cfg.assets entry is either a single .png/.obj // file (flat output: outputDir/.ctex/cmesh — preserves the // original behavior) or a directory (recursed, with the relative tree // mirrored under outputDir//; .png/.obj are compressed, every // other file is copied through unchanged). Directory mode lets mod/map // trees keep their nested layout so mod.json paths like // "cannon/base.cmesh" resolve correctly at runtime. // Skipped per-file if the output is newer than the source. Each // compress is a job of its own; passthrough copies are bundled into // a single job to match the cfg.files pattern. auto submitCompress = [&](fs::path sourcePath, fs::path outRelative) { place(outputDir / outRelative, {}); fs::path out = outputDir / outRelative; if (fs::exists(out) && fs::exists(sourcePath) && fs::last_write_time(sourcePath) <= fs::last_write_time(out)) return; // Named before the job takes the path: the arguments of one call // are evaluated in no particular order. std::string label = std::format("Compressing asset {}", sourcePath.filename().string()); jobs.Add(std::move(label), [sourcePath = std::move(sourcePath), out = std::move(out)] { std::error_code ec; fs::create_directories(out.parent_path(), ec); return CompressAsset(sourcePath, out); }); }; std::vector> assetPassthroughs; for (const fs::path& asset : config.assets) { if (fs::is_directory(asset)) { fs::path topName = asset.filename(); for (const auto& entry : fs::recursive_directory_iterator(asset)) { if (!entry.is_regular_file()) continue; fs::path rel = fs::relative(entry.path(), asset); if (std::optional compName = CompressedAssetName(entry.path())) { submitCompress(entry.path(), topName / rel.parent_path() / *compName); } else { place(outputDir / topName / rel, {}); assetPassthroughs.emplace_back(entry.path(), topName / rel); } } } else { std::optional outName = CompressedAssetName(asset); if (!outName) { jobs.Fail(std::format("{}: unsupported asset extension (expected .png/.tga/.jpg/.bmp/.obj, or a directory)", asset.string())); break; } submitCompress(asset, *outName); } } if (!assetPassthroughs.empty()) { // What a copy throws is the job's error (JobGroup::Add), here and // for cfg.files below. jobs.Add("Copying asset passthrough files", [passthroughs = std::move(assetPassthroughs), &outputDir]() -> std::string { for (const auto& [src, rel] : passthroughs) { fs::path dst = outputDir / rel; fs::create_directories(dst.parent_path()); if (!fs::exists(dst)) { fs::copy_file(src, dst); } else if (fs::last_write_time(src) > fs::last_write_time(dst)) { fs::copy_file(src, dst, fs::copy_options::overwrite_existing); } } return {}; }); } for (const fs::path& additionalFile : config.files) place(outputDir / additionalFile.filename(), additionalFile); jobs.Add(std::format("Copying files for {}", config.name), [&config, &outputDir]() -> std::string { for (const fs::path& additionalFile : config.files) { fs::path destination = outputDir / additionalFile.filename(); if (fs::is_directory(additionalFile)) { for (const auto& entry : fs::recursive_directory_iterator(additionalFile)) { const fs::path& sourcePath = entry.path(); fs::path relativePath = fs::relative(sourcePath, additionalFile); fs::path destPath = destination / relativePath; if (entry.is_directory()) { if (!fs::exists(destPath)) fs::create_directories(destPath); } else if (entry.is_regular_file()) { fs::create_directories(destPath.parent_path()); if (!fs::exists(destPath)) { fs::copy_file(sourcePath, destPath); } else if (fs::last_write_time(sourcePath) > fs::last_write_time(destPath)) { fs::copy_file(sourcePath, destPath, fs::copy_options::overwrite_existing); } } } } else { if (!fs::exists(destination)) { fs::copy_file(additionalFile, destination); } else if (fs::last_write_time(additionalFile) > fs::last_write_time(destination)) { fs::copy_file(additionalFile, destination, fs::copy_options::overwrite_existing); } } } return {}; }); std::vector externalResults(config.externalDependencies.size()); std::vector externalThreads; externalThreads.reserve(config.externalDependencies.size()); for (std::size_t i = 0; i < config.externalDependencies.size(); ++i) { externalThreads.emplace_back([&, i]() { const ExternalDependency& dep = config.externalDependencies[i]; Progress::Task task(std::format("Building external dep {}", dep.name)); if (jobs.Failed()) return; std::string error; try { // Every configuration of the pass that declares this // dependency shares one fetch and build of it. A project's // tests often each copy its externalDependencies, and RunTests // builds them side by side: each of them pulling the clone // cost a network round trip per test, and before the clone had // a lock, the simultaneous pulls broke its FETCH_HEAD and // failed every test (issue #34). const std::shared_future built = OncePerPass(depResults, depMutex, ExternalBuildDir(dep, config.target), [&] { return BuildResult{BuildExternal(dep, config.target), false, {}}; }); error = built.get().result; if (error.empty()) externalResults[i] = ExternalOutputs(dep, config.target); } catch (const std::exception& e) { error = std::format("external dep {} threw: {}", dep.name, e.what()); } if (!error.empty()) jobs.Fail(std::move(error)); }); } fs::path stdPcmDir = StdPcmDir(config); if (!fs::exists(stdPcmDir)) { fs::create_directories(stdPcmDir); } std::string stdPcmResult; { Progress::Task task(std::format("Building std PCM ({}-{})", config.target, config.march)); // The external threads are running: an exception leaving here would // destroy them joinable, which terminates the process. try { stdPcmResult = BuildStdPcm(config, stdPcmDir/"std.pcm"); } catch (const std::exception& e) { stdPcmResult = std::format("building the std module for {}: {}", config.target, e.what()); } } if(!stdPcmResult.empty()) { jobs.Fail(stdPcmResult); for(std::thread& thread : externalThreads) thread.join(); jobs.Wait(); return {stdPcmResult, false, {}}; } fs::path pcmDir = config.PcmDir(); fs::copy_file(stdPcmDir/"std.pcm", pcmDir/"std.pcm", fs::copy_options::update_existing); // Everything about the compile command that is a pure function of the // Configuration is assembled by GetCompileCommand, so that anything which // needs to PARSE these sources with the same flags — the linter's AST // layer — cannot drift from what actually built the PCMs. Build appends // only what depends on work having happened: dependency public flags and // external dependency flags, further down. CompileCommand compile = GetCompileCommand(config); std::string command = compile.command; const std::string& includeFlags = compile.includeFlags; const std::string& defineFlags = compile.defineFlags; const std::string& userFlags = compile.userFlags; const std::string& ltoCompileFlags = compile.ltoCompileFlags; const std::string& ltoLinkFlags = compile.ltoLinkFlags; const bool isWasm = config.target.starts_with("wasm32"); std::string files; std::set libSet; std::set runtimeSet; std::set publicFlagSet; std::set runPathSet; std::mutex fileMutex; std::vector depThreads; depThreads.reserve(config.dependencies.size()); std::atomic repack(false); for(Configuration* dep : config.dependencies) { depThreads.emplace_back([&, dep](){ try { if (jobs.Failed()) return; const std::shared_future built = OncePerPass(depResults, depMutex, dep->PcmDir(), [&] { return Build(*dep, depResults, depMutex); }); const BuildResult& result = built.get(); fileMutex.lock(); for (const std::string& lib : result.libs) libSet.insert(lib); for (const std::string& lib : result.runtimeLibs) runtimeSet.insert(lib); for (const std::string& f : result.publicCompileFlags) publicFlagSet.insert(f); for (const std::string& dir : result.runPaths) runPathSet.insert(dir); fileMutex.unlock(); if (!result.result.empty()) jobs.Fail(result.result); if (result.repack) { repack = true; } } catch (const std::exception& e) { jobs.Fail(std::format("dep build for {} threw: {}", dep->path.string(), e.what())); } }); } // Only the CMake build type is still derived here; the compile flags it // used to sit alongside now come from GetCompileCommand. const std::string cmakeBuildType = config.debug ? "Debug" : "Release"; // Same target-aware setup as the C++ compile path (line 459-): wasm32 // rejects -march, silently ignores -mtune, and needs --sysroot to find // wasi-libc headers. Build the prefix once so all C compiles share it. std::string cArchFlags = isWasm ? std::string() : std::format(" -march={} -mtune={}", config.march, config.mtune); if (!config.sysroot.empty()) { cArchFlags += std::format(" --sysroot={}", config.sysroot); } else if (config.target == "x86_64-w64-mingw32") { // The C++ side gets it through GetBaseCommand. if (const fs::path& sysroot = MingwSysroot(); !sysroot.empty()) cArchFlags += std::format(" --sysroot={}", sysroot.string()); } if (isWasm) { // The C++ path's wasm flags, all of them, a variant pass's included. // With only the signal.h define, wasi-libc's setjmp.h refused to // compile in C, and a C object given -wasm-enable-sjlj through // compileFlags used LLVM's legacy exception encoding next to C++ // objects in the standard one, a mix engines refuse to load. cArchFlags += WasmCompileFlags(config); } for (const fs::path& cFile : config.cFiles) { files += std::format(" {}_source.o ", (buildDir / cFile.filename()).string()); const std::string objPath = std::format("{}_source.o", (buildDir / cFile.filename()).string()); const std::string srcPath = std::format("{}.c", cFile.string()); // C sources carry their dependencies entirely in #includes, so the // depfile the compile below writes is the whole record of what this // object was built from beyond the .c itself. if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) { jobs.Add(std::format("Compiling {}.c", cFile.filename().string()), [command = std::format("{8} {0}.c --target={1}{2} -O3{3} -c{4}{5}{6} -MD -MF {7}_source.o.d -o {7}_source.o", cFile.string(), config.target, cArchFlags, ltoCompileFlags, includeFlags, defineFlags, userFlags, (buildDir / cFile.filename()).string(), GetToolchain().clang.string())] { return RunBuildCommand(command); }); } } for (const fs::path& cFile : config.cuda) { files += std::format(" {}_source.o ", (buildDir / cFile.filename()).string()); const std::string objPath = std::format("{}_source.o", (buildDir / cFile.filename()).string()); const std::string srcPath = std::format("{}.cu", cFile.string()); // nvcc writes the depfile clang writes for a C source (-MD -MF): the // .cu and every header it read, the toolkit's and the system's among // them, as a Make rule NewestPrerequisite reads as it reads clang's, // although nvcc puts a space before the colon. Without it, a .cu // whose header changed kept its old object. cfg.cudaArch needs no // check: it is part of VariantId, so another one builds in another // directory. if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) { const Toolchain& toolchain = GetToolchain(); if (toolchain.nvcc.empty()) { jobs.Fail(std::format("cannot compile {}.cu: {}", cFile.filename().string(), toolchain.nvccError)); break; } jobs.Add(std::format("Compiling {}.cu", cFile.filename().string()), [command = std::format("{} {} -c -MD -MF {} -o {} -O3 -arch={}", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(std::format("{}.d", objPath)), ShellQuote(objPath), ShellQuote(config.cudaArch))] { return RunBuildCommand(command); }); } } for(std::thread& thread : depThreads) { thread.join(); } for(std::thread& thread : externalThreads) { thread.join(); } if (jobs.Failed()) { return {jobs.Wait(), false, {}}; } // Ship runtime artifacts from transitive deps' bin dirs alongside the // executable: compiled .spv files (cfg.shaders) and asset files/dirs // (cfg.files). The lib already mirrored these into its own bin dir // during its build, but a consumer exe loads them from its own dir at // runtime. Only an exe is a deployment unit; intermediate libs don't // need to forward since the exe walks all transitive deps. Runs outside // the repack gate because the relink mtime check above only watches // .so/.dll/.a, so a shader/file-only change in a dep wouldn't trigger // repack but still needs the new artifact copied across. // (cfg.buildFiles use a different mechanism — they're exposed to shader // compiles as #include search paths in place, no copy.) if (config.type == ConfigurationType::Executable) { try { auto copyTree = [](const fs::path& src, const fs::path& dest) { if (fs::is_directory(src)) { for (const auto& entry : fs::recursive_directory_iterator(src)) { fs::path rel = fs::relative(entry.path(), src); fs::path destPath = dest / rel; if (entry.is_directory()) { if (!fs::exists(destPath)) fs::create_directories(destPath); } else if (entry.is_regular_file()) { fs::create_directories(destPath.parent_path()); if (!fs::exists(destPath)) { fs::copy_file(entry.path(), destPath); } else if (fs::last_write_time(entry.path()) > fs::last_write_time(destPath)) { fs::copy_file(entry.path(), destPath, fs::copy_options::overwrite_existing); } } } } else { if (!fs::exists(dest)) { fs::copy_file(src, dest); } else if (fs::last_write_time(src) > fs::last_write_time(dest)) { fs::copy_file(src, dest, fs::copy_options::overwrite_existing); } } }; std::unordered_set seen; std::function forwardDepArtifacts = [&](Configuration* dep) { if (!seen.insert(dep).second) return; fs::path depBinDir = dep->ProgramDir(); for (const Shader& shader : dep->shaders) { fs::path src = depBinDir / shader.OutputName(); if (!fs::exists(src)) continue; place(outputDir / src.filename(), src); copyTree(src, outputDir / src.filename()); } for (const fs::path& additionalFile : dep->files) { fs::path src = depBinDir / additionalFile.filename(); if (!fs::exists(src)) continue; place(outputDir / additionalFile.filename(), src); copyTree(src, outputDir / additionalFile.filename()); } for (const fs::path& asset : dep->assets) { // Directory entry: the dep already mirrored the // (compressed + passthrough) tree under // depBinDir//. Forward it wholesale // so our bin dir gets the same layout. if (fs::is_directory(asset)) { fs::path src = depBinDir / asset.filename(); if (!fs::exists(src)) continue; place(outputDir / asset.filename(), src); copyTree(src, outputDir / asset.filename()); continue; } const std::optional srcName = CompressedAssetName(asset); if (!srcName) continue; fs::path src = depBinDir / *srcName; if (!fs::exists(src)) continue; place(outputDir / *srcName, src); copyTree(src, outputDir / *srcName); } for (Configuration* sub : dep->dependencies) forwardDepArtifacts(sub); }; for (Configuration* dep : config.dependencies) forwardDepArtifacts(dep); } catch (const fs::filesystem_error& e) { jobs.Fail(e.what()); jobs.Wait(); return {e.what(), false, {}}; } } if(repack.load()) { buildResult.repack = true; } buildResult.libs = std::move(libSet); buildResult.runtimeLibs = std::move(runtimeSet); buildResult.runPaths = std::move(runPathSet); for(const std::string& flag : config.linkFlags) { buildResult.libs.insert(flag); } // CUDA sources link the runtime nvcc's own link takes, the static one, of // the toolkit whose nvcc compiles them: Toolchain::cudaRuntime, with the // -lrt -lpthread -ldl nvcc's link line puts after it. Static, so no run // path into the toolkit, which in the Flatpak lies under /run/host, ends // up in the program; libcuda.so.1, which the runtime loads, comes with the // driver. Named by its path: a -L of the toolkit's lib64 would put its // libraries, such as Arch's libcheckpoint.so, in the way of a project's // own of the same name. A toolkit without one gets nothing linked, as // before, and cfg.linkFlags names the runtime: a -lcudart_static the // linker could not find would fail the link even of a project that names // its own -lcudart. In runtimeLibs, which a configuration hands on as it // does libs and every link puts after them: whatever is built on a library // with CUDA sources links the runtime too, and a -lcudart a project names // itself comes first. Without an nvcc there is no runtime either, and no // object: VariantId keys the nvcc, and the .cu's compile above has already // said where it looked. if (const Toolchain& toolchain = GetToolchain(); !config.cuda.empty() && !toolchain.cudaRuntime.empty()) { buildResult.runtimeLibs.insert(ShellQuote(toolchain.cudaRuntime.string())); for (const std::string_view lib : {"-lrt", "-lpthread", "-ldl"}) buildResult.runtimeLibs.emplace(lib); } // Public compile flags propagated from sub-deps. Add them to this build's // command so config sees the headers its deps expose, and re-publish them // so config's own consumers see them transitively. for (const std::string& flag : publicFlagSet) command += std::format(" {}", flag); buildResult.publicCompileFlags = std::move(publicFlagSet); fs::file_time_type externalFloor = fs::file_time_type::min(); for(const ExternalBuildResult& ext : externalResults) { for(const std::string& flag : ext.compileFlags) { command += std::format(" {}", flag); // Headers a dep links via ExternalDependency are part of its // public surface (its modules can include them in declarations // visible to consumers), so propagate the -I to consumers. buildResult.publicCompileFlags.insert(flag); } for(const std::string& flag : ext.linkFlags) { buildResult.libs.insert(flag); } for (const std::string& dir : ext.runPaths) buildResult.runPaths.insert(dir); if (ext.latestArtifact > externalFloor) externalFloor = ext.latestArtifact; } // Check every interface before scheduling any of them. Schedule() puts a // unit after the stale units it imports and reads their needsRecompiling // for that, which a unit's own Check need not have set: a partition's // returns at the first stale import it finds. for(std::unique_ptr& interface : config.interfaces) { if(interface->Check(pcmDir, externalFloor)) { buildResult.repack = true; } files += std::format(" {}/{}.o", buildDir.string(), interface->path.filename().string()); for(std::unique_ptr& part : interface->partitions) { files += std::format(" {}/{}.o", buildDir.string(), part->path.filename().string()); } } // Every interface, and with each its partitions, not only the stale // ones: a unit whose BMI is up to date can still be without the object // made from it, which Schedule() then adds alone. No repack for that // here: the link below runs again for an object newer than its output. for(std::unique_ptr& interface : config.interfaces) { interface->Schedule(jobs, command, pcmDir, buildDir); } for(Implementation& implementation : config.implementations) { if(implementation.Check(buildDir, pcmDir, externalFloor)) { buildResult.repack = true; implementation.Schedule(jobs, command, pcmDir, buildDir); } files += std::format(" {}/{}_impl.o", buildDir.string(), implementation.path.filename().string()); } if (std::string failed = jobs.Wait(); !failed.empty()) { return {std::move(failed), false, {}}; } std::string linkExtras; for(const std::string& flag : buildResult.libs) { linkExtras += std::format(" {}", flag); } for (const std::string& lib : buildResult.runtimeLibs) linkExtras += std::format(" {}", lib); // The program loads its shared dependencies from where they were built, // the external cache among them. ExternalOutputs leaves the mingw target // without any: PE resolves DLLs another way. A Flatpak has none of those // directories once installed, and nothing outside its own /app and the // runtime: WriteFlatpak copies what the program needs from them into // files/lib, beside files/bin, and that is the one place it looks, under // -r as well as installed. const bool flatpak = config.ResolvedPackaging() == Packaging::Flatpak; if (flatpak) { linkExtras += " -Wl,-rpath,'$ORIGIN/../lib'"; } else { for (const std::string& dir : buildResult.runPaths) linkExtras += RunPathFlags(dir); } // Link-only LTO/section flags (empty in Debug and for wasm). Every exe/lib // link below ends with linkExtras, so this reaches them all; the static-lib // archive path uses ar instead and is handled separately. linkExtras += ltoLinkFlags; // Host links use the toolchain's own libc++. When the toolchain lives // outside /usr (a bundled one) the binary needs an rpath to find // libc++.so.1 at run time; a Flatpak finds the copy in its files/lib // through the run path above instead, as it does anything else this -L // lets the link take from that directory. mingw links libstdc++ and // every sysroot build (wasm included) brings its own libc++. if (config.target != "x86_64-w64-mingw32" && config.sysroot.empty()) { linkExtras += flatpak ? GetToolchain().LibcxxSearchFlags() : GetToolchain().LibcxxLinkFlags(); } // mingw uses libstdc++; C++26 std::print/format extras live in libstdc++exp. // libstdc++ on mingw uses winpthreads for std::atomic_wait / // counting_semaphore / stop_token, so -lpthread is required as soon as // those primitives appear (they do, transitively, in any non-trivial std // import). -static-libstdc++ bundles libstdc++ into the exe so we don't // chase libstdc++-6.dll TLS symbol mismatches across mingw versions and // the resulting binary stands alone. Auto-link so user projects don't // carry boilerplate. if (config.target == "x86_64-w64-mingw32") { // Static-link libstdc++/libgcc/libwinpthread so the resulting .exe // or .dll doesn't depend on a specific runtime DLL being on the // consumer's PATH. The mingw runtime ABI varies subtly between // distributions (Arch UCRT vs msys2 UCRT vs msys2 MSVCRT) and // STATUS_ENTRYPOINT_NOT_FOUND at LoadLibrary time is the symptom // of a mismatch. Static linkage trades binary size for portability. // The -Bstatic/-Bdynamic bracketing forces -lpthread to resolve // against libwinpthread.a rather than the import lib; everything // else (KERNEL32, UCRT) stays dynamic. -lstdc++exp adds C++26 // std::print/format extras. -femulated-tls is already on the // compile so __once_callable et al resolve in static libstdc++. linkExtras += " -lstdc++exp -static-libstdc++ -static-libgcc -Wl,-Bstatic -lpthread -Wl,-Bdynamic"; } // Code built with -fwasm-exceptions calls into libunwind (the // __cpp_exception tag, the landing-pad context, _Unwind_RaiseException), // and -wasm-enable-sjlj turns setjmp and longjmp into calls into // wasi-libc's libsetjmp (__wasm_setjmp, __wasm_longjmp, the __c_longjmp // tag). The driver adds neither to the link the way it adds libc++. A // static archive contributes only what something references, so a // program without setjmp gets nothing from libsetjmp, and every sysroot // that passes WasmBuildError ships both. if (isWasm) { linkExtras += " -lunwind -lsetjmp"; } // Force a relink if the expected output is missing or older than any dep // artifact. Missing covers: previous build produced a different outputName, // or the binary was deleted by hand. Older-than-dep covers: dep's library // was rebuilt by an earlier run (so dep.repack is false this time around) // but the consumer was never relinked against the new dep. { fs::path expected = ExpectedOutput(config); if (!fs::exists(expected)) { buildResult.repack = true; } else { auto consumerMtime = fs::last_write_time(expected); for (Configuration* dep : config.dependencies) { fs::path depArtifact = ExpectedOutput(*dep); if (fs::exists(depArtifact) && fs::last_write_time(depArtifact) > consumerMtime) { buildResult.repack = true; break; } } // Also relink if any .o this archive bundles is newer than the // archive itself. Covers a build that compiled the .o but never // reached the link step (interrupt, crash, or a source touched // after compile but before link): on the next run the .cpp is // already ≤ .o so Implementation/Module Check returns false and // nothing else would notice the archive is stale. if (!buildResult.repack) { auto objNewer = [&](const fs::path& obj) { std::error_code ec; auto t = fs::last_write_time(obj, ec); return !ec && t > consumerMtime; }; for (const std::unique_ptr& iface : config.interfaces) { if (objNewer(buildDir / std::format("{}.o", iface->path.filename().string()))) { buildResult.repack = true; break; } bool partHit = false; for (const std::unique_ptr& part : iface->partitions) { if (objNewer(buildDir / std::format("{}.o", part->path.filename().string()))) { partHit = true; break; } } if (partHit) { buildResult.repack = true; break; } } if (!buildResult.repack) { for (const Implementation& impl : config.implementations) { if (objNewer(buildDir / std::format("{}_impl.o", impl.path.filename().string()))) { buildResult.repack = true; break; } } } // C and CUDA objects are archive members too, and their compile // loop above is the only thing that knows it rebuilt one — it // sets no repack flag, so without this a .c edit recompiled the // object and then linked nothing. if (!buildResult.repack) { auto sourceObjNewer = [&](const std::vector& sources) { for (const fs::path& source : sources) { if (objNewer(buildDir / std::format("{}_source.o", source.filename().string()))) return true; } return false; }; if (sourceObjNewer(config.cFiles) || sourceObjNewer(config.cuda)) { buildResult.repack = true; } } } } } // The exact command the link (or archive) step runs, kept beside the // objects once it has succeeded. A different one relinks even with no // object newer than the output: a link flag changed in project.cpp, or a // dependency's library moved, as an ExternalDependency's does when its // options change and it is built into a new cache directory. std::string linkCommand; if (config.type == ConfigurationType::Executable) { if (config.target.starts_with("wasm32")) { linkCommand = std::format("{}{} -o {}.wasm -fuse-ld=lld{}", command, files, (outputDir/config.outputName).string(), linkExtras); } else { linkCommand = std::format("{}{} -o {} -fuse-ld=lld{}", command, files, (outputDir/config.outputName).string(), linkExtras); } } else if (config.type == ConfigurationType::LibraryStatic) { // ThinLTO emits LLVM bitcode objects; plain `ar` writes an archive // index that omits their symbols, so a consumer's lld link can't // pull the needed members. llvm-ar writes a bitcode-aware index // and handles plain ELF and COFF objects just as well, so every // build uses it. linkCommand = std::format("{} rcs {}.a {}", GetToolchain().llvmAr.string(), (outputDir/fs::path(std::string("lib")+config.outputName)).string(), files); } else if (config.target == "x86_64-w64-mingw32") { // LibraryDynamic. Output names follow each target's convention so // consumers can link via the standard linker search: // mingw: .dll + lib.dll.a (lld --out-implib) // unix: lib.so (rpath $ORIGIN) fs::path dll = outputDir / std::format("{}.dll", config.outputName); fs::path implib = outputDir / std::format("lib{}.dll.a", config.outputName); linkCommand = std::format("{}{} -shared -o {} -Wl,--out-implib,{} -fuse-ld=lld{}", command, files, dll.string(), implib.string(), linkExtras); } else { linkCommand = std::format("{}{} -shared -o {}.so -Wl,-rpath,'$ORIGIN' -fuse-ld=lld{}", command, files, (outputDir/(std::string("lib")+config.outputName)).string(), linkExtras); } const fs::path linkRecord = buildDir / std::format("{}.link", config.outputName); if (!buildResult.repack) { std::ifstream recorded(linkRecord, std::ios::binary); const std::string previous((std::istreambuf_iterator(recorded)), std::istreambuf_iterator()); if (previous != linkCommand) buildResult.repack = true; } if(buildResult.repack) { Progress::Task task(std::format("Linking {}", config.outputName)); // The record goes first, so a link that fails leaves it stale. std::error_code removed; fs::remove(linkRecord, removed); if(config.type == ConfigurationType::Executable) { if(config.target == "x86_64-w64-mingw32") { try { // Copy any LibraryDynamic dependency DLLs alongside // the launcher exe — Windows resolves DLLs from the exe's // own directory at load time, so this is the simplest // equivalent of rpath $ORIGIN. std::unordered_set dllSeen; std::function copyDepDlls = [&](Configuration* dep) { if (!dllSeen.insert(dep).second) return; if (dep->type == ConfigurationType::LibraryDynamic && dep->target == "x86_64-w64-mingw32") { // Only the DLL: Windows resolves it from the exe's // directory at load time. The import lib stays in // the dependency's own bin dir, which is already // on the link line through buildResult.libs. fs::path src = dep->BinDir() / std::format("{}.dll", dep->outputName); if (fs::exists(src)) { fs::path dest = outputDir / src.filename(); if (!fs::exists(dest) || fs::last_write_time(src) > fs::last_write_time(dest)) { fs::copy(src, dest, fs::copy_options::overwrite_existing); } } } for (Configuration* sub : dep->dependencies) copyDepDlls(sub); }; for (Configuration* dep : config.dependencies) copyDepDlls(dep); } catch (const fs::filesystem_error& e) { return {e.what(), false, {}}; } } } buildResult.result = RunBuildCommand(linkCommand); if (buildResult.result.empty()) { std::ofstream(linkRecord, std::ios::binary | std::ios::trunc) << linkCommand; } } if (config.type == ConfigurationType::LibraryStatic || config.type == ConfigurationType::LibraryDynamic) { buildResult.libs.insert(std::format("-L{}", outputDir.string())); buildResult.libs.insert(std::format("-l{}", config.outputName)); } // A program built on a shared library loads it from where it was linked // from: its run path names this directory, or, packaged as a Flatpak, it // carries a copy in files/lib, taken from here. Only for the consumers: // the library's own link is done. On Windows a DLL is found beside the // program instead, where the mingw link copies it. if (config.type == ConfigurationType::LibraryDynamic && config.target != "x86_64-w64-mingw32") { buildResult.runPaths.insert(fs::absolute(outputDir).string()); } // After every build, linked or not: the writer changes only what differs, // and a permission or desktop file can change without a link. if (buildResult.result.empty() && flatpak) { buildResult.result = WriteFlatpak(config, buildResult, placed); } // Browser-wasm feature-detected variants. The baseline outputName.wasm is // now built (above). For each declared variant, recompile the entire build // graph with the variant's extra codegen flags and drop the result next to // the baseline as outputName.