// 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 { // A JSON value: what clang-scan-deps writes of a source, and what Build() // keeps of that. The members of an object are its `items`, each with // its `key`. struct Json { enum class Kind { Null, Boolean, Number, String, Array, Object }; Kind kind = Kind::Null; bool boolean = false; // A string's value, or a number as it is written. std::string text; std::vector items; std::string key; // The member of an object named `name`; nullptr when the object has // none, and for a value that is no object. const Json* Member(std::string_view name) const { if (kind != Kind::Object) return nullptr; for (const Json& item : items) { if (item.key == name) return &item; } return nullptr; } }; // Reads the one JSON value (RFC 8259) a text holds. There is no JSON // library in the tree, and what clang-scan-deps writes is JSON. class JsonReader { public: explicit JsonReader(std::string_view text) : text(text) {} // The value, with nothing after it but white space; nullopt for a // text that holds anything else. std::optional Read() { Json value; if (!Value(value, 0)) return std::nullopt; SkipSpace(); if (at != text.size()) return std::nullopt; return value; } private: // Deeper than anything clang-scan-deps writes, and shallow enough // that a text which is not its output cannot exhaust the stack. static constexpr std::size_t MaxDepth = 64; bool Value(Json& value, std::size_t depth) { SkipSpace(); if (at == text.size() || depth > MaxDepth) return false; if (text[at] == '{') return Object(value, depth); if (text[at] == '[') return Array(value, depth); if (text[at] == '"') { value.kind = Json::Kind::String; return String(value.text); } if (Word("true")) { value.kind = Json::Kind::Boolean; value.boolean = true; return true; } if (Word("false")) { value.kind = Json::Kind::Boolean; return true; } if (Word("null")) return true; return Number(value); } bool Object(Json& value, std::size_t depth) { value.kind = Json::Kind::Object; ++at; SkipSpace(); if (Take('}')) return true; do { SkipSpace(); Json member; if (!String(member.key)) return false; SkipSpace(); if (!Take(':') || !Value(member, depth + 1)) return false; value.items.push_back(std::move(member)); SkipSpace(); } while (Take(',')); return Take('}'); } bool Array(Json& value, std::size_t depth) { value.kind = Json::Kind::Array; ++at; SkipSpace(); if (Take(']')) return true; do { Json element; if (!Value(element, depth + 1)) return false; value.items.push_back(std::move(element)); SkipSpace(); } while (Take(',')); return Take(']'); } // The string that starts at the cursor, its escapes undone, into // `out`. bool String(std::string& out) { if (!Take('"')) return false; while (at < text.size()) { const char c = text[at++]; if (c == '"') return true; // A control character is only ever escaped. if (static_cast(c) < 0x20) return false; if (c != '\\') { out.push_back(c); continue; } if (at == text.size()) return false; switch (text[at++]) { case '"': out.push_back('"'); break; case '\\': out.push_back('\\'); break; case '/': out.push_back('/'); break; case 'b': out.push_back('\b'); break; case 'f': out.push_back('\f'); break; case 'n': out.push_back('\n'); break; case 'r': out.push_back('\r'); break; case 't': out.push_back('\t'); break; case 'u': { std::uint32_t code = 0; if (!Hex(code)) return false; // A character past the first 65,536 is written as // two escapes, a high surrogate and then a low one. if (code >= 0xD800 && code <= 0xDBFF) { std::uint32_t low = 0; if (!Take('\\') || !Take('u') || !Hex(low) || low < 0xDC00 || low > 0xDFFF) return false; code = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00); } else if (code >= 0xDC00 && code <= 0xDFFF) { return false; } AppendUtf8(out, code); break; } default: return false; } } return false; } // The four hexadecimal digits at the cursor, as the number they // spell, into `code`. bool Hex(std::uint32_t& code) { if (text.size() - at < 4) return false; for (const std::size_t end = at + 4; at < end; ++at) { const char c = text[at]; std::uint32_t digit = 0; if (c >= '0' && c <= '9') { digit = static_cast(c - '0'); } else if (c >= 'a' && c <= 'f') { digit = static_cast(c - 'a' + 10); } else if (c >= 'A' && c <= 'F') { digit = static_cast(c - 'A' + 10); } else { return false; } code = code * 16 + digit; } return true; } static void AppendUtf8(std::string& out, std::uint32_t code) { if (code < 0x80) { out.push_back(static_cast(code)); } else if (code < 0x800) { out.push_back(static_cast(0xC0 | (code >> 6))); out.push_back(static_cast(0x80 | (code & 0x3F))); } else if (code < 0x10000) { out.push_back(static_cast(0xE0 | (code >> 12))); out.push_back(static_cast(0x80 | ((code >> 6) & 0x3F))); out.push_back(static_cast(0x80 | (code & 0x3F))); } else { out.push_back(static_cast(0xF0 | (code >> 18))); out.push_back(static_cast(0x80 | ((code >> 12) & 0x3F))); out.push_back(static_cast(0x80 | ((code >> 6) & 0x3F))); out.push_back(static_cast(0x80 | (code & 0x3F))); } } // The number at the cursor, kept as it is written: no number that // clang-scan-deps writes is read. bool Number(Json& value) { const std::size_t start = at; Take('-'); if (!Digits()) return false; if (Take('.') && !Digits()) return false; if (Take('e') || Take('E')) { if (!Take('+')) Take('-'); if (!Digits()) return false; } value.kind = Json::Kind::Number; value.text = std::string(text.substr(start, at - start)); return true; } bool Digits() { const std::size_t start = at; while (at < text.size() && text[at] >= '0' && text[at] <= '9') ++at; return at > start; } bool Word(std::string_view word) { if (!text.substr(at).starts_with(word)) return false; at += word.size(); return true; } bool Take(char c) { if (at == text.size() || text[at] != c) return false; ++at; return true; } void SkipSpace() { while (at < text.size() && (text[at] == ' ' || text[at] == '\t' || text[at] == '\n' || text[at] == '\r')) ++at; } std::string_view text; std::size_t at = 0; }; // What one source declares and imports, as clang-scan-deps read it. struct ScannedUnit { // The unit of a module it is by its declaration: `X` for the primary // interface of module X, `X:P` for X's partition P. Empty for a // source that is neither, as an implementation unit of X written // `module X;` is, which imports X instead. std::string provides; // The modules and partitions it imports, each by its whole name: an // `import :P;` in a unit of X is `X:P`. std::vector imports; }; // The unit `document` describes, as clang-scan-deps describes a single // source in its P1689 format; nullopt for a document of any other shape. std::optional ReadP1689(const Json& document) { const Json* rules = document.Member("rules"); if (rules == nullptr || rules->kind != Json::Kind::Array || rules->items.size() != 1) return std::nullopt; const Json& rule = rules->items.front(); // The logical name of each entry of the rule's array `name`, which // need not be there; false when it is there and is not such an // array. const auto names = [&rule](std::string_view name, std::vector& out) { const Json* entries = rule.Member(name); if (entries == nullptr) return true; if (entries->kind != Json::Kind::Array) return false; for (const Json& entry : entries->items) { const Json* logical = entry.Member("logical-name"); if (logical == nullptr || logical->kind != Json::Kind::String) return false; out.push_back(logical->text); } return true; }; std::vector provided; ScannedUnit unit; if (!names("provides", provided) || provided.size() > 1 || !names("requires", unit.imports)) return std::nullopt; if (!provided.empty()) unit.provides = std::move(provided.front()); return unit; } std::optional ReadWholeFile(const fs::path& file) { std::ifstream in(file, std::ios::binary); if (!in) return std::nullopt; std::stringstream buffer; buffer << in.rdbuf(); return std::move(buffer).str(); } // The dependency file of the scan Build() keeps at `scan`, beside it: the // source and every file it included, as a rule for `scan`. fs::path ScanDepfile(const fs::path& scan) { return fs::path(scan) += ".d"; } // The scan of a source that Build() keeps at `scan`, when it holds for // `command`: it was taken with that command, after the source and every // file the source included were last written (NewestPrerequisite of // its dependency file). nullopt when it does not, and when it cannot be // read; the source is then scanned again. std::optional CurrentScan(const fs::path& scan, std::string_view command) { std::error_code ec; const fs::file_time_type written = fs::last_write_time(scan, ec); if (ec || NewestPrerequisite(ScanDepfile(scan)) >= written) return std::nullopt; const std::optional text = ReadWholeFile(scan); if (!text) return std::nullopt; const std::optional kept = JsonReader(*text).Read(); if (!kept) return std::nullopt; const Json* scannedWith = kept->Member("command"); const Json* p1689 = kept->Member("p1689"); if (scannedWith == nullptr || scannedWith->kind != Json::Kind::String || scannedWith->text != command || p1689 == nullptr) return std::nullopt; return ReadP1689(*p1689); } // A unit's name split at its colon: {"X", ""} for the module X, // {"X", "P"} for X's partition P. std::pair SplitUnitName(std::string_view name) { const std::size_t colon = name.find(':'); if (colon == std::string_view::npos) return {name, {}}; return {name.substr(0, colon), name.substr(colon + 1)}; } Module* FindModule(std::span> modules, std::string_view name) { for (const std::unique_ptr& candidate : modules) { if (candidate->name == name) return candidate.get(); } return nullptr; } // The configuration whose build the pass ran for the directory a // dependency is built into, and so the one that holds the modules of // that build (BuildResult::built): the dependency itself, or another // configuration of its directory. using BuiltConfiguration = std::function; // Adds the staleness edge of an import of the module `name` by a unit of // a configuration whose own modules are `local` and which is built on // `dependencies`: to the module among `local`, else to the first found // among the modules of the dependencies and of what they are built on, // each as `builtIn` gives it, with the BMI that one's build writes, // unless the unit has that edge already. A module none of them has, // `std` or one from outside the build, gets no edge. The dependencies // have been built when this is called, and so have read their sources: // their modules are known. void AddImport(std::span> local, std::span dependencies, const BuiltConfiguration& builtIn, std::string_view name, std::vector& localDeps, std::vector>& externalDeps) { if (Module* own = FindModule(local, name)) { if (!std::ranges::contains(localDeps, own)) localDeps.push_back(own); return; } std::unordered_set seen; std::function walk = [&](const Configuration& listed) -> bool { const Configuration& depCfg = builtIn(listed); if (!seen.insert(&depCfg).second) return false; if (Module* found = FindModule(depCfg.interfaces, name)) { if (!std::ranges::contains(externalDeps, found, &std::pair::first)) { externalDeps.emplace_back(found, std::format("{}.pcm", (depCfg.PcmDir() / found->path.filename()).string())); } return true; } for (const Configuration* sub : depCfg.dependencies) { if (walk(*sub)) return true; } return false; }; for (const Configuration* depCfg : dependencies) { if (walk(*depCfg)) return; } } // The modules and units of a configuration as the scans of its sources // describe them, before Build() gives them to the configuration. struct ModuleGraph { std::vector> interfaces; std::vector implementations; }; // Makes the modules and units of `config` from `interfaceScans` and // `implementationScans`, the scans of its interfaceSources and of its // implementationSources in the order they are listed in, with its // dependencies as `builtIn` gives them. Returns why it could not, empty // when it could. std::string MakeModuleGraph(const Configuration& config, std::span interfaceScans, std::span implementationScans, const BuiltConfiguration& builtIn, ModuleGraph& graph) { // A unit is named by its source without the extension. const auto stem = [](const fs::path& source) { fs::path stemmed = source; stemmed.replace_extension(); return stemmed; }; // The unit each interface source is: its module, and for a // partition the partition as well. std::vector moduleOf(interfaceScans.size(), nullptr); std::vector partitionOf(interfaceScans.size(), nullptr); // The primary interfaces first, so that a partition finds its module // in whatever order the two are listed. for (std::size_t i = 0; i < interfaceScans.size(); ++i) { const auto [moduleName, partitionName] = SplitUnitName(interfaceScans[i].provides); if (moduleName.empty()) return std::format("No module declaration found in {}", config.interfaceSources[i].string()); if (!partitionName.empty()) continue; graph.interfaces.push_back(std::make_unique(std::string(moduleName), stem(config.interfaceSources[i]))); moduleOf[i] = graph.interfaces.back().get(); } for (std::size_t i = 0; i < interfaceScans.size(); ++i) { const auto [moduleName, partitionName] = SplitUnitName(interfaceScans[i].provides); if (partitionName.empty()) continue; Module* owner = FindModule(graph.interfaces, moduleName); if (owner == nullptr) return std::format("Module {} not found, referenced in {}", moduleName, config.interfaceSources[i].string()); owner->partitions.push_back(std::make_unique(std::string(partitionName), stem(config.interfaceSources[i]))); moduleOf[i] = owner; partitionOf[i] = owner->partitions.back().get(); } // The partition an import of `X:P` names: a partition of the module // X among this configuration's interface sources. X is the importing // unit's own module, since only its partitions can be imported. // nullptr when there is none. const auto partitionNamed = [&graph](std::string_view moduleName, std::string_view partitionName) -> ModulePartition* { const Module* owner = FindModule(graph.interfaces, moduleName); if (owner == nullptr) return nullptr; for (const std::unique_ptr& partition : owner->partitions) { if (partition->name == partitionName) return partition.get(); } return nullptr; }; for (std::size_t i = 0; i < interfaceScans.size(); ++i) { ModulePartition* partition = partitionOf[i]; for (const std::string& name : interfaceScans[i].imports) { const auto [moduleName, partitionName] = SplitUnitName(name); if (partitionName.empty()) { if (partition != nullptr) { AddImport(graph.interfaces, config.dependencies, builtIn, name, partition->moduleDependencies, partition->externalModuleDependencies); } else { AddImport(graph.interfaces, config.dependencies, builtIn, name, moduleOf[i]->moduleDependencies, moduleOf[i]->externalModuleDependencies); } continue; } ModulePartition* imported = partitionNamed(moduleName, partitionName); if (imported == nullptr) return std::format("imported partition {}:{} not found, referenced in {}", moduleName, partitionName, config.interfaceSources[i].string()); // A primary interface needs no edge to its own partitions: it // is checked and built after every one of them (Module::Check, // Module::Schedule). if (partition != nullptr && !std::ranges::contains(partition->partitionDependencies, imported)) partition->partitionDependencies.push_back(imported); } } for (std::size_t i = 0; i < implementationScans.size(); ++i) { const fs::path& source = config.implementationSources[i]; Implementation& implementation = graph.implementations.emplace_back(stem(source)); // A source that is a unit of a module by its declaration, as an // implementation partition (`module X:P;`) is, belongs to a // module of this configuration. if (const std::string_view moduleName = SplitUnitName(implementationScans[i].provides).first; !moduleName.empty() && FindModule(graph.interfaces, moduleName) == nullptr) { return std::format("Module {} not found, referenced in {}", moduleName, source.string()); } for (const std::string& name : implementationScans[i].imports) { const auto [moduleName, partitionName] = SplitUnitName(name); if (partitionName.empty()) { AddImport(graph.interfaces, config.dependencies, builtIn, name, implementation.moduleDependencies, implementation.externalModuleDependencies); continue; } ModulePartition* imported = partitionNamed(moduleName, partitionName); if (imported == nullptr) return std::format("imported partition {}:{} not found, referenced in {}", moduleName, partitionName, source.string()); if (!std::ranges::contains(implementation.partitionDependencies, imported)) implementation.partitionDependencies.push_back(imported); } } return ""; } } void Configuration::GetInterfacesAndImplementations(std::span interfaces, std::span implementations) { // Absolute now, so that a path stays the same file when the working // directory changes, as it does around the load of a GitProject. for (const fs::path& listed : interfaces) { fs::path source = fs::absolute(path / listed).lexically_normal(); source += ".cppm"; interfaceSources.push_back(std::move(source)); } for (const fs::path& listed : implementations) { fs::path source = fs::absolute(path / listed).lexically_normal(); source += ".cpp"; implementationSources.push_back(std::move(source)); } } std::string Crafter::StdPcmFlags(const Configuration& config, const Toolchain& toolchain) { 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 sysroot = config.ResolvedSysroot(toolchain); const std::string sysrootFlag = sysroot.empty() ? std::string() : std::format(" --sysroot={}", 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 && !sysroot.empty()) { archFlags += std::format(" -nostdinc++ -isystem {}/usr/include/c++/v1", 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, toolchain); // 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); } namespace { // `path` resolved against the working directory, with no `.` or `..` in // it and no separator at its end. fs::path WithoutSeparator(fs::path path) { path = fs::absolute(path).lexically_normal(); return path.has_filename() ? path : path.parent_path(); } // What the name of a source's object ends in, by the source's // extension: one ending for each kind of source, so a .c beside a .cu // of its name has an object of its own. Empty for an extension Build() // compiles no source of. std::string_view ObjectSuffix(std::string_view extension) { if (extension == ".cpp") return "_impl.o"; if (extension == ".c") return "_source.o"; if (extension == ".cu") return "_cuda.o"; return ""; } // ObjectPath's rule for the sources of one configuration, with what it // takes from the configuration worked out once for all of them, and the // same rule for where Build() keeps the scan of each interface and // implementation source. class SourceLayout { public: SourceLayout(const fs::path& directory, const fs::path& buildDir) : directory(WithoutSeparator(directory)), inside(buildDir / "objects"), outside(buildDir / "objects-outside"), scansInside(buildDir / "scans"), scansOutside(buildDir / "scans-outside") {} // The object of the source a configuration lists as `listed`, which // is its path without its extension, `extension`. fs::path Object(const fs::path& listed, std::string_view extension) const { fs::path object = fs::absolute(listed).lexically_normal(); object += ObjectSuffix(extension); const fs::path within = Within(object); return within.empty() ? outside / object.relative_path() : inside / within; } // Where the scan of `source`, given with its extension, is kept: // named as Object() names an object, under scans/ and // scans-outside/, by the source's own name with .json after it, as // in scans/a/Thing.cppm.json, so that a .cppm and a .cpp of one // name have one each. fs::path Scan(const fs::path& source) const { fs::path scan = fs::absolute(source).lexically_normal(); scan += ".json"; const fs::path within = Within(scan); return within.empty() ? scansOutside / scan.relative_path() : scansInside / within; } // That source as the progress line of its compile names it: by its // path from the configuration's directory, or by its whole path // when it lies outside that directory. std::string Shown(const fs::path& listed, std::string_view extension) const { fs::path source = fs::absolute(listed).lexically_normal(); source += extension; return Shown(source); } // The same for a source given with its extension. std::string Shown(const fs::path& source) const { const fs::path resolved = fs::absolute(source).lexically_normal(); const fs::path within = Within(resolved); return within.empty() ? resolved.string() : within.string(); } private: // The path of `resolved` from the configuration's directory; empty // when it does not lie in that directory. fs::path Within(const fs::path& resolved) const { const fs::path relative = resolved.lexically_relative(directory); if (relative.empty() || relative == "." || *relative.begin() == "..") return {}; return relative; } fs::path directory; fs::path inside; fs::path outside; fs::path scansInside; fs::path scansOutside; }; } fs::path Crafter::ObjectPath(const Configuration& config, const fs::path& source) { const std::string extension = source.extension().string(); if (ObjectSuffix(extension).empty()) throw std::invalid_argument(std::format("{} is not a .cpp, .c or .cu source", source.string())); fs::path listed = source; listed.replace_extension(); return SourceLayout(config.path, config.BuildDir()).Object(listed, extension); } 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 (const std::string sysroot = config.ResolvedSysroot(GetToolchain()); !sysroot.empty()) { out.command += std::format(" --sysroot={}", 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", 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 { // Two of `configurations` that would be built into one directory, as // the error that names them; empty when no two would. Built side by // side they are two builds writing the same files, and a pass that has // built one of them hands it to whatever is built on the other. std::string SameDirectoryError(std::span configurations) { std::unordered_map builtInto; for (const Configuration* cfg : configurations) { const auto [known, added] = builtInto.try_emplace(fs::absolute(cfg->PcmDir()).lexically_normal(), cfg); if (!added && known->second != cfg) { return std::format("two configurations named {} would both be built into {}: give each a name of its own", cfg->name, known->first.string()); } } return ""; } // 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. Asked once Build() has read // the sources of `config`: the modules of a configuration are what the // build that read its sources found (Configuration::interfaces), and // those of each dependency are known once it is built. A dependency is // taken as `builtIn` gives it, so two configurations that the pass // builds into one directory are one build of their modules, not two. std::string DuplicateModuleError(const Configuration& config, const BuiltConfiguration& builtIn) { 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& listed, const std::string& chain) { const Configuration& c = &listed == &config ? config : builtIn(listed); 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. 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.", 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.ResolvedSysroot(GetToolchain()); 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); } // The name a file is written under before MoveIntoPlace gives it its // own: beside its place, so that the move is a rename, and no other // write's, in this process or in another. A build writes files that a // step of another crafter-build may be reading at that moment: a // project loaded with GitProject is built in its clone in the cache, // which every project that names the same source shares, and nothing // keeps two crafter-builds from building it at once. The name is made // of random bits and not of the process's id: a crafter-build that // runs as a Flatpak has the process ids of its own sandbox, and two of // them the same ones. fs::path WrittenBeside(const fs::path& file) { std::random_device random; return fs::path(file) += std::format(".{:08x}{:08x}.tmp", random(), random()); } // Moves `written` to `file`. The rename puts it there in one step: what // opens `file` finds the file of before or this one, never none and // never part of one, and what has the file of before open goes on // reading that one. Returns what went wrong, with `written` removed; // empty when nothing did. std::string MoveIntoPlace(const fs::path& written, const fs::path& file) { std::error_code ec; fs::rename(written, file, ec); if (!ec) return ""; std::string failed = std::format("cannot move {} to {}: {}", written.string(), file.string(), ec.message()); fs::remove(written, ec); return failed; } // `argument` as one argument in a response file, the file of further // arguments a command names with @. clang and llvm-ar split such a file // at whitespace, keep what stands in quotes together, and take a // backslash to quote the character after it, inside quotes as well. // That last is why this is not ShellQuote: the shell keeps a backslash // in single quotes as it is. std::string ResponseFileArgument(std::string_view argument) { std::string quoted = "\""; for (const char c : argument) { if (c == '"' || c == '\\') quoted.push_back('\\'); quoted.push_back(c); } quoted.push_back('"'); return quoted; } // Has `scanner`, clang-scan-deps, read `source` as `command` compiles it, // and keeps what it found at `scan` for CurrentScan: a JSON object of the // command and of the P1689 description the scanner wrote, with the // dependency file of what the source included beside it. Both are // written beside their places and moved into them (WrittenBeside), as // another crafter-build may be reading them. Returns what went wrong, // empty when nothing did, and then leaves what it found in `found`. std::string ScanSource(const fs::path& scanner, std::string_view command, const fs::path& source, const fs::path& scan, ScannedUnit& found) { std::error_code ec; fs::create_directories(scan.parent_path()); const fs::path description = WrittenBeside(scan); const fs::path depfile = WrittenBeside(ScanDepfile(scan)); // -w: what the preprocessor warns of, the compile of the source // reports. The command's own output is named `scan`, so that the // dependency file is the rule for the scan. const std::string failed = RunBuildCommand(std::format("{} -format=p1689 -o {} -- {} -w {} -c -MD -MF {} -o {}", ShellQuote(scanner.string()), ShellQuote(description.string()), command, ShellQuote(source.string()), ShellQuote(depfile.string()), ShellQuote(scan.string()))); const std::optional written = ReadWholeFile(description); fs::remove(description, ec); if (!failed.empty()) { fs::remove(depfile, ec); return failed; } const std::optional document = written ? JsonReader(*written).Read() : std::nullopt; std::optional unit = document ? ReadP1689(*document) : std::nullopt; if (!unit) { fs::remove(depfile, ec); return std::format("clang-scan-deps wrote no description of {} that crafter-build can read: {}", source.string(), written.value_or("")); } const fs::path kept = WrittenBeside(scan); std::ofstream out(kept, std::ios::binary | std::ios::trunc); out << std::format("{{\"command\": {}, \"p1689\": {}}}\n", JsonQuote(command), *written); out.close(); if (out.fail()) { fs::remove(kept, ec); fs::remove(depfile, ec); return std::format("cannot write {}, the scan of {}", kept.string(), source.string()); } // The dependency file first. Should the second move fail, the scan // of before is left beside the dependency file of now, which lists // what the source includes now; the other way round, the scan of // now would be left beside the dependency file of before, which may // miss a header the source includes now, and an edit of that header // would not have the source scanned again. if (std::string moved = MoveIntoPlace(depfile, ScanDepfile(scan)); !moved.empty()) { fs::remove(kept, ec); return moved; } if (std::string moved = MoveIntoPlace(kept, scan); !moved.empty()) return moved; found = std::move(*unit); return ""; } // Reads what each interface and implementation source of `config` // declares and imports, with `command`, the command they are compiled // with, and gives the configuration the modules and units that makes. A // source whose scan is current (CurrentScan) is not read again; the // others are scanned at once, each a job on the workers of the process. // Returns why it could not, empty when it could; the configuration then // keeps the modules and units it had. Its dependencies are taken as // `builtIn` gives them. std::string ReadSources(Configuration& config, std::string_view command, const SourceLayout& layout, const BuiltConfiguration& builtIn) { std::vector sources = config.interfaceSources; sources.insert(sources.end(), config.implementationSources.begin(), config.implementationSources.end()); std::vector scans(sources.size()); { JobGroup scanning; for (std::size_t i = 0; i < sources.size(); ++i) { fs::path scan = layout.Scan(sources[i]); if (std::optional current = CurrentScan(scan, command)) { scans[i] = std::move(*current); continue; } scanning.Add(std::format("Scanning {}", layout.Shown(sources[i])), [&scans, i, scanner = GetToolchain().clangScanDeps, command = std::string(command), source = sources[i], scan = std::move(scan)] { return ScanSource(scanner, command, source, scan, scans[i]); }); } if (std::string failed = scanning.Wait(); !failed.empty()) return failed; } const std::span scanned(scans); ModuleGraph graph; if (std::string error = MakeModuleGraph(config, scanned.first(config.interfaceSources.size()), scanned.subspan(config.interfaceSources.size()), builtIn, graph); !error.empty()) return error; config.interfaces = std::move(graph.interfaces); config.implementations = std::move(graph.implementations); return ""; } } 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 anything is spawned as well, so a refused build leaves no // directory behind and starts no thread. 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(); // Where the object of each .cpp, .c and .cu of this configuration goes, // what its compile is called (ObjectPath), and where the scan of each // .cppm and .cpp is kept. const SourceLayout layout(config.path, 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 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"); // The objects this configuration is linked or archived from, in the // order that step is given them. std::vector objects; 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 (const std::string resolved = config.ResolvedSysroot(GetToolchain()); !resolved.empty()) { cArchFlags += std::format(" --sysroot={}", resolved); } 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) { const fs::path object = layout.Object(cFile, ".c"); objects.push_back(object); const std::string objPath = object.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)) { // The job makes the directory of its object, which is one for // the source's own directory: the compiler makes none. // // The source, the dependency file and the object are quoted // for the shell, as the CUDA compile below quotes its own. The // object of a source outside the configuration's directory is // named by that source's whole path, and so holds directories // this command did not name while an object lay in the build // directory itself: the working directory's, where the source // is listed relative to it. A build from a directory with a // space in its name would have stopped here. jobs.Add(std::format("Compiling {}", layout.Shown(cFile, ".c")), [directory = object.parent_path(), command = std::format("{8} {0} --target={1}{2} -O3{3} -c{4}{5}{6} -MD -MF {7} -o {9}", ShellQuote(srcPath), config.target, cArchFlags, ltoCompileFlags, includeFlags, defineFlags, userFlags, ShellQuote(std::format("{}.d", objPath)), GetToolchain().clang.string(), ShellQuote(objPath))] { fs::create_directories(directory); return RunBuildCommand(command); }); } } for (const fs::path& cFile : config.cuda) { const fs::path object = layout.Object(cFile, ".cu"); objects.push_back(object); const std::string objPath = object.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 {}: {}", layout.Shown(cFile, ".cu"), toolchain.nvccError)); break; } jobs.Add(std::format("Compiling {}", layout.Shown(cFile, ".cu")), [directory = object.parent_path(), 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))] { fs::create_directories(directory); 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; } // What the interface and implementation sources declare and import, read // only now: clang-scan-deps preprocesses each with the command it is // compiled with, which is complete from here on, with the include paths // of the dependencies and external dependencies just built, whose // headers a source may include. Their modules, which the imports are // looked up among, are known by now too, as each dependency's Build() // has read its own sources. A Build() makes the modules and units of its // own configuration alone: those of a dependency are its own Build()'s // to make, and the builds of other configurations built on it may be // reading them at this moment. // // A dependency's modules are those of the build the pass ran for its // directory, which need not have been the dependency's own: OncePerPass // builds a directory once, for whichever configuration of it asked // first, and a configuration it did not build has no modules (see // BuildResult::built). Every dependency has its result in the pass by // now. const BuiltConfiguration builtIn = [&depResults, &depMutex](const Configuration& dependency) -> const Configuration& { std::shared_future built; { std::lock_guard lock(depMutex); if (const auto found = depResults.find(dependency.PcmDir()); found != depResults.end()) built = found->second; } if (built.valid() && built.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { // A build that threw has failed this one already, before it got // here, and is taken as the dependency's own. try { if (const Configuration* ran = built.get().built) return *ran; } catch (...) { } } return dependency; }; if (std::string error = ReadSources(config, command, layout, builtIn); !error.empty()) { jobs.Fail(std::move(error)); return {jobs.Wait(), false, {}}; } buildResult.built = &config; // Both before any .cppm or .cpp of the configuration is compiled, and // only now that its modules are known. Its C and CUDA sources, whose // compiles started beside the dependencies' builds, may have been. if (std::string duplicate = DuplicateModuleError(config, builtIn); !duplicate.empty()) { jobs.Fail(std::move(duplicate)); return {jobs.Wait(), false, {}}; } if (std::string cycle = ImportCycleError(config); !cycle.empty()) { jobs.Fail(std::move(cycle)); return {jobs.Wait(), false, {}}; } // 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; } objects.push_back(buildDir / std::format("{}.o", interface->path.filename().string())); for(std::unique_ptr& part : interface->partitions) { objects.push_back(buildDir / std::format("{}.o", 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) { const fs::path object = layout.Object(implementation.path, ".cpp"); if(implementation.Check(object, pcmDir, externalFloor)) { buildResult.repack = true; implementation.Schedule(jobs, command, pcmDir, buildDir, object, layout.Shown(implementation.path, ".cpp")); } objects.push_back(object); } 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.ResolvedSysroot(GetToolchain()).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. // // Every object of the step is looked at, by the name the step // itself is given. 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) { for (const fs::path& object : objects) { std::error_code ec; const fs::file_time_type written = fs::last_write_time(object, ec); if (!ec && written > consumerMtime) { buildResult.repack = true; break; } } } } } // The step reads its objects from a file the command names with @, one // to a line: a response file, which clang and llvm-ar both take // arguments from. Written into the command itself, the objects' paths // made it longer with every source, and the command is one argument to // the shell that runs it, which Linux holds to 32 pages, 131,072 bytes // where a page is 4 KiB. With objects whose paths came to more, no // shell started and the build ended with "popen() failed!". const fs::path objectList = buildDir / std::format("{}.objects", config.outputName); std::string listed; for (const fs::path& object : objects) listed += std::format("{}\n", ResponseFileArgument(object.string())); const std::string files = std::format(" {}", ShellQuote(std::format("@{}", objectList.string()))); // The archive step of a static library, as it writes the archive to // `archive`. 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. const auto archiveCommand = [&](const fs::path& archive) { return std::format("{} rcs {} {}", GetToolchain().llvmAr.string(), archive.string(), files); }; // The command the link step runs, or the archive step with the archive // itself for the name it is written under (see where the step runs), // kept beside the objects once the step 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) { linkCommand = archiveCommand(ExpectedOutput(config)); } 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); // Kept with the command, under it: the objects it reads, which the // command itself only names the file of. Taking a source out of the // configuration can leave the command the one of the build before, // with no object newer than the output: that list is then all that // says the step has to run again. const std::string linked = std::format("{}\n{}", linkCommand, listed); if (!buildResult.repack) { std::ifstream recorded(linkRecord, std::ios::binary); const std::string previous((std::istreambuf_iterator(recorded)), std::istreambuf_iterator()); if (previous != linked) 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, {}}; } } } { // Written for every run of the step, and a list that cannot be // written is the build's error: the list of an earlier build // would be left in its place, and the step would read that one. // Written beside its place and moved there, not over the list // that is there: a step of another crafter-build that reads the // list at that moment (WrittenBeside) would read none of it, or // part, and archive or link that. With the move it reads the // list it opened, whole, or this one. const fs::path written = WrittenBeside(objectList); std::ofstream list(written, std::ios::binary | std::ios::trunc); list << listed; list.close(); if (list.fail()) { std::error_code ec; fs::remove(written, ec); return {std::format("cannot write {}, the list of objects {} is made from", written.string(), ExpectedOutput(config).filename().string()), false, {}}; } if (std::string failed = MoveIntoPlace(written, objectList); !failed.empty()) return {std::move(failed), false, {}}; } if (config.type == ConfigurationType::LibraryStatic) { // llvm-ar's `r` adds to an archive that is there: it replaces // the members it is given and keeps every other one, so the // object of a source that had left the configuration stayed in // the library, ahead of whatever was added after it. The link // takes a symbol from the first member that defines it: once a // source had been renamed, everything built on the library went // on linking the object of the file under its old name. So the // step writes its archive where there is none, and that one // holds what the command lists and nothing else. // // Not in the archive's own place with what is there removed // first: the library would be missing from there until llvm-ar // had written the new one, and the link of another // crafter-build that is built on the library at that moment // (WrittenBeside) would not find it. llvm-ar put a new archive // in the place of the old one in one step, and so does the // move. const fs::path archive = ExpectedOutput(config); const fs::path written = WrittenBeside(archive); buildResult.result = RunBuildCommand(archiveCommand(written)); if (buildResult.result.empty()) { buildResult.result = MoveIntoPlace(written, archive); } else { // The archive of the build before stays, as it did when // llvm-ar failed on it. std::error_code ec; fs::remove(written, ec); } } else { buildResult.result = RunBuildCommand(linkCommand); } if (buildResult.result.empty()) { std::ofstream(linkRecord, std::ios::binary | std::ios::trunc) << linked; } } 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.