A test that opens a window opened it on the display of whoever ran the suite: every `crafter-build test` of Crafter.Graphics put the windows of its window tests on the desktop, and its other GPU tests connect to the session's compositor too, since Device::Initialize calls wl_display_connect whether a window follows or not. A test that sets the new Test::wayland (TestBuilder::Wayland) now runs with a headless compositor started for it alone. RunSingleTest starts the compositor through sh, with XDG_RUNTIME_DIR naming a directory made for it and without WAYLAND_DISPLAY, WAYLAND_SOCKET or DISPLAY, waits up to 30 s for a wayland-<n> socket in that directory, runs the test with WAYLAND_DISPLAY set to the socket's path and with DISPLAY and WAYLAND_SOCKET unset, then stops the compositor's process group and removes the directory. The test's command is env with those changes, and env's command is sh, which execs the test's words: env takes every word with an '=' in it ahead of its command for an assignment, a binary's path among them. The compositor runs under timeout(1) as long as the test may, the wait and 30 s more, and with no limit for a test that has none, a timeout of 0. It is weston on its headless backend with its GL renderer, unless CRAFTER_BUILD_COMPOSITOR or the new --compositor= names another command; `host` gives the tests the session's own display instead, to watch them. A compositor that ends before it listens, sh not finding it included, or does not listen in time fails the test with what it printed. A test that may run where its compositor is missing declares it in requires_ (tool:weston for the default), the check RunTests makes before the build, so no skip of its own is added, and no probe of the command: the command is any sh command, whose first word need not be the compositor. A test that fails, crashes or times out keeps what its compositor printed (TestResult::compositorLog), which RunTests writes to build/test-logs/<name>.compositor.log, and says when the compositor ended while it ran. One compositor per test rather than one per run: no two tests share one, so tests that run at once cannot cover each other's windows or take each other's focus, for weston's start-up on every test. weston's GL renderer, because it imports the dmabufs that a GPU's Vulkan driver presents, as Mesa's and NVIDIA's do, and the headless backend's default renderer and pixman import none: against pixman, the NVIDIA driver reports no format for a window's surface, and Crafter.Graphics's FrameLoopSync stops at its formatCount > 0 assertion. weston cannot run the test itself, as `weston -- <test>` exits 0 whatever the test returned, so crafter-build runs the compositor beside it. :Platform gains BackgroundCommand, the compositor's process, and PrivateDirectory, its directory. The process is forked with PR_SET_PDEATHSIG and runs under `timeout`, which passes the SIGTERM it gets when crafter-build dies on to the compositor's group, so a crafter-build killed by Ctrl-C leaves no compositor running. The directory is made in $XDG_RUNTIME_DIR, or in /tmp where that is not a directory, rather than in the temp directory, since a socket's path holds 107 bytes, and is flocked while in use; one that a killed crafter-build left is removed when the next is made beside it, once it has not changed for a minute. New members and a parameter with a default, nothing removed: a minor release.
3505 lines
188 KiB
C++
3505 lines
188 KiB
C++
// SPDX-License-Identifier: LGPL-3.0-only
|
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
|
|
|
module;
|
|
#include <sys/socket.h>
|
|
#include <netinet/in.h>
|
|
#include <unistd.h>
|
|
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<Json> 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<Json> 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<std::uint8_t>(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<std::uint32_t>(c - '0');
|
|
} else if (c >= 'a' && c <= 'f') {
|
|
digit = static_cast<std::uint32_t>(c - 'a' + 10);
|
|
} else if (c >= 'A' && c <= 'F') {
|
|
digit = static_cast<std::uint32_t>(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<char>(code));
|
|
} else if (code < 0x800) {
|
|
out.push_back(static_cast<char>(0xC0 | (code >> 6)));
|
|
out.push_back(static_cast<char>(0x80 | (code & 0x3F)));
|
|
} else if (code < 0x10000) {
|
|
out.push_back(static_cast<char>(0xE0 | (code >> 12)));
|
|
out.push_back(static_cast<char>(0x80 | ((code >> 6) & 0x3F)));
|
|
out.push_back(static_cast<char>(0x80 | (code & 0x3F)));
|
|
} else {
|
|
out.push_back(static_cast<char>(0xF0 | (code >> 18)));
|
|
out.push_back(static_cast<char>(0x80 | ((code >> 12) & 0x3F)));
|
|
out.push_back(static_cast<char>(0x80 | ((code >> 6) & 0x3F)));
|
|
out.push_back(static_cast<char>(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<std::string> 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<ScannedUnit> 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<std::string>& 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<std::string> 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<std::string> 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 for that command, which clang-scan-deps was
|
|
// given as ScannedAs makes it, 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<ScannedUnit> 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<std::string> text = ReadWholeFile(scan);
|
|
if (!text) return std::nullopt;
|
|
const std::optional<Json> 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<std::string_view, std::string_view> 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<const std::unique_ptr<Module>> modules, std::string_view name) {
|
|
for (const std::unique_ptr<Module>& 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<const Configuration&(const Configuration&)>;
|
|
|
|
// 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<const std::unique_ptr<Module>> local, std::span<Configuration* const> dependencies, const BuiltConfiguration& builtIn, std::string_view name, std::vector<Module*>& localDeps, std::vector<std::pair<Module*, fs::path>>& externalDeps) {
|
|
if (Module* own = FindModule(local, name)) {
|
|
if (!std::ranges::contains(localDeps, own)) localDeps.push_back(own);
|
|
return;
|
|
}
|
|
std::unordered_set<const Configuration*> seen;
|
|
std::function<bool(const Configuration&)> 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<Module*, fs::path>::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<std::unique_ptr<Module>> interfaces;
|
|
std::vector<Implementation> 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<const ScannedUnit> interfaceScans, std::span<const ScannedUnit> 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<Module*> moduleOf(interfaceScans.size(), nullptr);
|
|
std::vector<ModulePartition*> 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<Module>(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<ModulePartition>(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<ModulePartition>& 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<fs::path> interfaces, std::span<fs::path> 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 (<install>/../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::uint32_t>(std::hash<std::string>{}(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<name>.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 (<install>/../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<Configuration*> seen;
|
|
std::function<void(Configuration*)> 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<const Configuration*> seen;
|
|
std::function<void(const Configuration*)> 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<Configuration* const> configurations) {
|
|
std::unordered_map<fs::path, const Configuration*> 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<BuildResult> OncePerPass(std::unordered_map<fs::path, std::shared_future<BuildResult>>& depResults, std::mutex& depMutex, const fs::path& key, const std::function<BuildResult()>& work) {
|
|
std::promise<BuildResult> promise;
|
|
std::shared_future<BuildResult> 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<std::string, Owner> owners;
|
|
std::unordered_set<const Configuration*> visited;
|
|
std::string error;
|
|
std::function<void(const Configuration&, const std::string&)> 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<Module>& 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<const void*> 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<const void*, Unit> units;
|
|
std::vector<const void*> declared;
|
|
for (const std::unique_ptr<Module>& 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<ModulePartition>& 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<const Unit*> chain;
|
|
std::string round;
|
|
std::function<void(Unit&)> 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<std::string>* 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/<triple>/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<fs::path> CompressedAssetName(const fs::path& src) {
|
|
std::string ext = src.extension().string();
|
|
for (char& c : ext) c = static_cast<char>(std::tolower(static_cast<std::uint8_t>(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<FlatpakPermission> PermissionsOf(const Configuration& config) {
|
|
std::vector<FlatpakPermission> permissions;
|
|
std::unordered_set<const Configuration*> seen;
|
|
std::function<void(const Configuration*)> 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<std::string>& 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;
|
|
}
|
|
|
|
// `command`, a compile command of GetCompileCommand's, with its first
|
|
// word, the toolchain's clangxx, made
|
|
// Toolchain::InstalledClangxx(command), the compiler where clang started
|
|
// with that command takes itself to be. clang-scan-deps runs a clang
|
|
// driver of its own over the command after its --, and that driver looks
|
|
// for clang's own headers, and in a build for the host whose command names
|
|
// no libc++ directory for libc++'s too, from the directory of the
|
|
// command's first word, found on PATH where it is a bare name, without
|
|
// following a link to where the compiler is, whatever the command says of
|
|
// canonical prefixes: with a clangxx reached through a link from another
|
|
// directory, as CRAFTER_BUILD_LLVM_DIR may name one, a source that
|
|
// includes a header of the C++ standard library failed its scan where
|
|
// those headers were not to be found from the link's directory, though its
|
|
// compile, which takes itself to be where the link leads unless the
|
|
// command's last prefix flag is -no-canonical-prefixes, found the header.
|
|
// A command that does not start with clangxx is left as it is.
|
|
std::string ScannedAs(std::string_view command) {
|
|
const Toolchain& tc = GetToolchain();
|
|
const std::string compiler = tc.clangxx.string();
|
|
if (!command.starts_with(compiler)) return std::string(command);
|
|
return std::format("{}{}", ShellQuote(tc.InstalledClangxx(command).string()), command.substr(compiler.size()));
|
|
}
|
|
|
|
// 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()), ScannedAs(command), ShellQuote(source.string()), ShellQuote(depfile.string()), ShellQuote(scan.string())));
|
|
const std::optional<std::string> written = ReadWholeFile(description);
|
|
fs::remove(description, ec);
|
|
if (!failed.empty()) {
|
|
fs::remove(depfile, ec);
|
|
return failed;
|
|
}
|
|
const std::optional<Json> document = written ? JsonReader(*written).Read() : std::nullopt;
|
|
std::optional<ScannedUnit> 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, as `command`, the command they are compiled
|
|
// with, compiles them (ScanSource), 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<fs::path> sources = config.interfaceSources;
|
|
sources.insert(sources.end(), config.implementationSources.begin(), config.implementationSources.end());
|
|
std::vector<ScannedUnit> 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<ScannedUnit> 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<const ScannedUnit> 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<fs::path, std::shared_future<BuildResult>>& 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<std::string> 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<std::string>& 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<fs::path> shaderIncludeDirs;
|
|
{
|
|
std::unordered_set<std::string> seenDirs;
|
|
std::unordered_set<const Configuration*> seenCfg;
|
|
std::function<void(const Configuration*)> 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<std::string, const Shader*> 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/<filename>.ctex/cmesh — preserves the
|
|
// original behavior) or a directory (recursed, with the relative tree
|
|
// mirrored under outputDir/<dirname>/; .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<std::pair<fs::path, fs::path>> 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<fs::path> 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<fs::path> 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<ExternalBuildResult> externalResults(config.externalDependencies.size());
|
|
std::vector<std::thread> 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<BuildResult> 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<fs::path> objects;
|
|
std::set<std::string> libSet;
|
|
std::set<std::string> runtimeSet;
|
|
std::set<std::string> publicFlagSet;
|
|
std::set<std::string> runPathSet;
|
|
std::mutex fileMutex;
|
|
std::vector<std::thread> depThreads;
|
|
depThreads.reserve(config.dependencies.size());
|
|
std::atomic<bool> repack(false);
|
|
|
|
for(Configuration* dep : config.dependencies) {
|
|
depThreads.emplace_back([&, dep](){
|
|
try {
|
|
if (jobs.Failed()) return;
|
|
|
|
const std::shared_future<BuildResult> 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<Configuration*> seen;
|
|
std::function<void(Configuration*)> 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/<asset.filename()>/. 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<fs::path> 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<BuildResult> 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<Module>& 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<ModulePartition>& 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<Module>& 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: <name>.dll + lib<name>.dll.a (lld --out-implib)
|
|
// unix: lib<name>.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<char>(recorded)), std::istreambuf_iterator<char>());
|
|
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<Configuration*> dllSeen;
|
|
std::function<void(Configuration*)> 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.<label>.wasm. Relaxed-SIMD (and friends) is
|
|
// per-translation-unit codegen, not a link switch, so a full rebuild — incl.
|
|
// dep libs and the std PCM — is the only correct way to produce it.
|
|
//
|
|
// Guard: only fires on the top-level config that *declared* wasmVariants
|
|
// (deps leave it empty) and never on a variant pass itself (those carry
|
|
// wasmVariantFlags), so there's no recursion. Skipped on build error.
|
|
if (buildResult.result.empty() && config.target.starts_with("wasm32") && config.type == ConfigurationType::Executable && !config.wasmVariants.empty() && config.wasmVariantFlags.empty()) {
|
|
fs::path baselineBin = config.ProgramDir();
|
|
|
|
// The whole transitive graph, so the variant flags reach every TU.
|
|
std::vector<Configuration*> graph;
|
|
{
|
|
std::unordered_set<Configuration*> graphSeen;
|
|
std::function<void(Configuration*)> collect = [&](Configuration* c) {
|
|
if (!c || !graphSeen.insert(c).second) return;
|
|
graph.push_back(c);
|
|
for (Configuration* dep : c->dependencies) collect(dep);
|
|
};
|
|
collect(&config);
|
|
}
|
|
|
|
for (const WasmVariant& variant : config.wasmVariants) {
|
|
// A labelless or flagless "variant" is just the baseline under
|
|
// another name — nothing extra to compile.
|
|
if (variant.label.empty() || variant.flags.empty()) continue;
|
|
|
|
Progress::Task task(std::format("Building wasm variant {} ({})", variant.label, config.outputName));
|
|
|
|
for (Configuration* c : graph) c->wasmVariantFlags = variant.flags;
|
|
fs::path variantBin = config.ProgramDir();
|
|
|
|
std::unordered_map<fs::path, std::shared_future<BuildResult>> variantDeps;
|
|
std::mutex variantMutex;
|
|
BuildResult vr = Build(config, variantDeps, variantMutex);
|
|
|
|
for (Configuration* c : graph) c->wasmVariantFlags.clear();
|
|
|
|
if (!vr.result.empty()) {
|
|
buildResult.result = std::format("wasm variant '{}' build failed: {}", variant.label, vr.result);
|
|
break;
|
|
}
|
|
|
|
std::error_code ec;
|
|
fs::path src = variantBin / (std::format("{}.wasm", config.outputName));
|
|
fs::path dst = baselineBin / std::format("{}.{}.wasm", config.outputName, variant.label);
|
|
fs::copy_file(src, dst, fs::copy_options::overwrite_existing, ec);
|
|
if (ec) {
|
|
buildResult.result = std::format("copy wasm variant '{}' {} -> {}: {}", variant.label, src.string(), dst.string(), ec.message());
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
return buildResult;
|
|
}
|
|
|
|
namespace {
|
|
// How BuildAll builds the configurations of a list, or why it does not:
|
|
// worked out from the list alone, before anything of it is built.
|
|
struct BuildPlan {
|
|
// Each of them once, however often the list names it.
|
|
std::vector<Configuration*> roots;
|
|
// For each of `roots`, the others it is built after, by their places
|
|
// in `roots`.
|
|
std::vector<std::vector<std::size_t>> waitsFor;
|
|
// The places in `roots`, each after the ones it waits for.
|
|
std::vector<std::size_t> order;
|
|
// Whether a wasm executable that declares variants is among them or
|
|
// among what they are built on, so that they are built one after the
|
|
// other.
|
|
bool rewrites = false;
|
|
// Why the list is not built, as BuildAll returns it; empty when it
|
|
// is.
|
|
std::string refused;
|
|
};
|
|
|
|
BuildPlan PlanBuild(std::span<Configuration* const> configurations) {
|
|
BuildPlan plan;
|
|
for (Configuration* cfg : configurations) {
|
|
if (!std::ranges::contains(plan.roots, cfg)) plan.roots.push_back(cfg);
|
|
}
|
|
const std::span<Configuration* const> roots = plan.roots;
|
|
const std::size_t count = roots.size();
|
|
const auto directory = [](const Configuration& cfg) { return fs::absolute(cfg.PcmDir()).lexically_normal(); };
|
|
|
|
// The directory each of them is built into, and the directories of
|
|
// everything it is built on. A wasm executable that declares
|
|
// variants builds everything it is built on once more for each of
|
|
// them, and says which variant by rewriting those configurations in
|
|
// place (the end of Build()). A library that two of these share
|
|
// would change under whichever is still building its baseline, so
|
|
// with such a configuration anywhere among them they are built one
|
|
// after the other.
|
|
std::vector<fs::path> builtInto(count);
|
|
std::vector<std::unordered_set<fs::path>> builtOn(count);
|
|
for (std::size_t index = 0; index < count; ++index) {
|
|
builtInto[index] = directory(*roots[index]);
|
|
std::unordered_set<const Configuration*> seen = { roots[index] };
|
|
std::vector<const Configuration*> pending = { roots[index] };
|
|
while (!pending.empty()) {
|
|
const Configuration& cfg = *pending.back();
|
|
pending.pop_back();
|
|
if (cfg.type == ConfigurationType::Executable && cfg.target.starts_with("wasm32") && !cfg.wasmVariants.empty()) plan.rewrites = true;
|
|
for (const Configuration* dep : cfg.dependencies) {
|
|
if (!seen.insert(dep).second) continue;
|
|
builtOn[index].insert(directory(*dep));
|
|
pending.push_back(dep);
|
|
}
|
|
}
|
|
}
|
|
|
|
plan.refused = SameDirectoryError(roots);
|
|
if (!plan.refused.empty()) return plan;
|
|
|
|
// One that another is built on, which is to say that something the
|
|
// other is built on is built into its directory, is built before
|
|
// the other starts: the other then finds it built, in the record of
|
|
// the pass, instead of building it a second time beside this build
|
|
// of it.
|
|
plan.waitsFor.resize(count);
|
|
for (std::size_t index = 0; index < count; ++index) {
|
|
for (std::size_t other = 0; other < count; ++other) {
|
|
if (other != index && builtOn[index].contains(builtInto[other])) plan.waitsFor[index].push_back(other);
|
|
}
|
|
}
|
|
// One that is itself built on something of its own directory makes
|
|
// two builds for that directory, its dependency's and its own, and
|
|
// the record of the pass holds one result for a directory: another
|
|
// of them that looks there for what it is built on would be given
|
|
// one of the two, whichever it had asked for. By itself, or with no
|
|
// other of them built on that directory, it builds as it does for
|
|
// Build().
|
|
for (std::size_t index = 0; index < count; ++index) {
|
|
if (!builtOn[index].contains(builtInto[index])) continue;
|
|
for (std::size_t other = 0; other < count; ++other) {
|
|
if (other == index || !builtOn[other].contains(builtInto[index])) continue;
|
|
plan.refused = std::format("{} and a configuration it is built on would both be built into {}, where {} looks for what it is built on: give each a name of its own", roots[index]->name, builtInto[index].string(), roots[other]->name);
|
|
return plan;
|
|
}
|
|
}
|
|
std::vector<bool> ordered(count, false);
|
|
for (bool placed = true; placed;) {
|
|
placed = false;
|
|
for (std::size_t index = 0; index < count; ++index) {
|
|
if (ordered[index] || !std::ranges::all_of(plan.waitsFor[index], [&](std::size_t other) { return ordered[other]; })) continue;
|
|
ordered[index] = true;
|
|
plan.order.push_back(index);
|
|
placed = true;
|
|
}
|
|
}
|
|
if (plan.order.size() != count) {
|
|
std::string names;
|
|
for (std::size_t index = 0; index < count; ++index) {
|
|
if (ordered[index]) continue;
|
|
if (!names.empty()) names += ", ";
|
|
names += roots[index]->name;
|
|
}
|
|
plan.refused = std::format("{}: each of these is built on something that would be built into the directory of another of them, so none of them can be built first", names);
|
|
}
|
|
return plan;
|
|
}
|
|
}
|
|
|
|
std::string Crafter::BuildAll(std::span<Configuration* const> configurations, std::unordered_map<fs::path, std::shared_future<BuildResult>>& depResults, std::mutex& depMutex) {
|
|
const BuildPlan plan = PlanBuild(configurations);
|
|
if (!plan.refused.empty()) return plan.refused;
|
|
const std::size_t count = plan.roots.size();
|
|
|
|
std::vector<std::string> errors(count);
|
|
const auto build = [&](std::size_t index) {
|
|
Configuration& cfg = *plan.roots[index];
|
|
// By Build() itself, as a project's one configuration always was,
|
|
// and only then put into the record of the pass, where a
|
|
// configuration that depends on this one looks for it, with what
|
|
// the build returned or threw. Recorded while it is still being
|
|
// built, it would be handed to a dependency of its own that is
|
|
// built into the same directory, which would wait for the build
|
|
// that is waiting for it. Such a dependency has left its own result
|
|
// under that directory by now, and this one's takes its place: no
|
|
// other of them is built on that directory, or the set was refused.
|
|
std::promise<BuildResult> built;
|
|
try {
|
|
BuildResult result = Build(cfg, depResults, depMutex);
|
|
errors[index] = result.result;
|
|
built.set_value(std::move(result));
|
|
} catch (const std::exception& e) {
|
|
errors[index] = std::format("build of {} threw: {}", cfg.name, e.what());
|
|
built.set_exception(std::current_exception());
|
|
} catch (...) {
|
|
errors[index] = std::format("build of {} threw something that is not a std::exception", cfg.name);
|
|
built.set_exception(std::current_exception());
|
|
}
|
|
const std::lock_guard lock(depMutex);
|
|
depResults.insert_or_assign(cfg.PcmDir(), built.get_future().share());
|
|
};
|
|
|
|
if (plan.rewrites) {
|
|
for (const std::size_t index : plan.order) build(index);
|
|
} else {
|
|
std::vector<std::promise<void>> finishes(count);
|
|
std::vector<std::shared_future<void>> finished;
|
|
finished.reserve(count);
|
|
for (std::promise<void>& finish : finishes) finished.push_back(finish.get_future().share());
|
|
const auto buildInTurn = [&](std::size_t index) {
|
|
for (const std::size_t other : plan.waitsFor[index]) finished[other].wait();
|
|
build(index);
|
|
finishes[index].set_value();
|
|
};
|
|
// The first on this thread, so a project of one configuration is
|
|
// built where it always was.
|
|
std::vector<std::jthread> others;
|
|
others.reserve(count);
|
|
for (std::size_t index = 1; index < count; ++index) others.emplace_back(buildInTurn, index);
|
|
if (count > 0) buildInTurn(0);
|
|
}
|
|
|
|
std::string failed;
|
|
for (auto error = errors.begin(); error != errors.end(); ++error) {
|
|
if (error->empty() || std::ranges::contains(errors.begin(), error, *error)) continue;
|
|
if (!failed.empty()) failed += '\n';
|
|
failed += *error;
|
|
}
|
|
return failed;
|
|
}
|
|
|
|
namespace {
|
|
FlatpakExport ExportOf(const Configuration& config) {
|
|
FlatpakExport app;
|
|
app.files = fs::absolute(config.BinDir() / "files").lexically_normal();
|
|
app.appId = AppIdOf(config);
|
|
app.work = fs::absolute(FlatpakAppDir(config)).lexically_normal();
|
|
app.command = ExpectedOutput(config).filename().string();
|
|
app.runtime = config.flatpak.runtime;
|
|
app.arch = GetToolchain().flatpakArch;
|
|
app.branch = GetToolchain().flatpakBranch;
|
|
app.permissions = PermissionsOf(config);
|
|
for (const fs::path& module : config.flatpak.modules) app.modules.push_back(fs::absolute(module).lexically_normal());
|
|
return app;
|
|
}
|
|
|
|
// Why `verb` cannot export `config`, from the loaded Configuration and
|
|
// the host alone, so that Run() refuses before anything is built; empty
|
|
// when it can.
|
|
std::string ExportRefusal(const Configuration& config, std::string_view verb) {
|
|
if (config.ResolvedPackaging() != Packaging::Flatpak) {
|
|
return std::format("crafter-build {}: {} is not packaged as a Flatpak; set cfg.packaging = Packaging::Flatpak in project.cpp, or, where it calls ApplyStandardArgs, pass --packaging=flatpak", verb, config.name);
|
|
}
|
|
if (const std::string why = HostFlatpakUnavailable(config.path); !why.empty()) return std::format("crafter-build {}: {}", verb, why);
|
|
return "";
|
|
}
|
|
|
|
// ExportRefusal, or a build that is not there to export.
|
|
std::string CannotExport(const Configuration& config, std::string_view verb) {
|
|
if (const std::string refused = ExportRefusal(config, verb); !refused.empty()) return refused;
|
|
if (!fs::exists(ExpectedOutput(config))) return std::format("crafter-build {}: {} is not built yet", verb, config.name);
|
|
return "";
|
|
}
|
|
|
|
// The names of `configurations`, as a message lists them.
|
|
std::string NamesOf(std::span<const Configuration* const> configurations) {
|
|
std::string names;
|
|
for (const Configuration* cfg : configurations) {
|
|
if (!names.empty()) names += ", ";
|
|
names += cfg->name;
|
|
}
|
|
return names;
|
|
}
|
|
|
|
// What install or bundle exports of the configurations a project file
|
|
// returns: the only one, or of several the one packaged as a Flatpak.
|
|
struct ExportChoice {
|
|
// Null when none of several is packaged, or more than one is.
|
|
const Configuration* config = nullptr;
|
|
// Why `config` cannot be exported, or why there is none; empty when
|
|
// it can be.
|
|
std::string refused;
|
|
};
|
|
|
|
ExportChoice ChooseExport(std::span<Configuration* const> configurations, std::string_view verb) {
|
|
std::vector<const Configuration*> packaged;
|
|
for (const Configuration* cfg : configurations) {
|
|
if (cfg->ResolvedPackaging() == Packaging::Flatpak) packaged.push_back(cfg);
|
|
}
|
|
if (packaged.size() > 1) {
|
|
return { nullptr, std::format("crafter-build {0}: {1} are each packaged as a Flatpak, and {0} exports one app", verb, NamesOf(packaged)) };
|
|
}
|
|
if (packaged.empty() && configurations.size() > 1) {
|
|
return { nullptr, std::format("crafter-build {0}: none of {1} is packaged as a Flatpak; set cfg.packaging = Packaging::Flatpak in project.cpp on the one to {0}", verb, NamesOf(configurations)) };
|
|
}
|
|
const Configuration* const config = packaged.empty() ? configurations.front() : packaged.front();
|
|
return { config, ExportRefusal(*config, verb) };
|
|
}
|
|
|
|
// A repo's path as the file:// URL of a remote: percent-encoded, since
|
|
// `remote-modify --url=` stores what it is given as it is.
|
|
std::string FileUrl(const fs::path& path) {
|
|
std::string url = "file://";
|
|
for (const char c : path.string()) {
|
|
const bool plain = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || std::string_view("/-._~").contains(c);
|
|
if (plain) url.push_back(c);
|
|
else url += std::format("%{:02X}", static_cast<std::uint8_t>(c));
|
|
}
|
|
return url;
|
|
}
|
|
|
|
// Every variant of an app exports into its one repo, FlatpakAppDir(), so
|
|
// another crafter-build exporting a variant between an export and the
|
|
// install or bundle made from it would have that install or bundle the
|
|
// other's program. Both hold this lock from the export on.
|
|
FileLock AppDirLock(const fs::path& work) {
|
|
std::error_code ec;
|
|
fs::create_directories(work, ec);
|
|
return FileLock(work / ".lock");
|
|
}
|
|
}
|
|
|
|
std::string Crafter::InstallFlatpakApp(const Configuration& config) {
|
|
if (const std::string refused = CannotExport(config, "install"); !refused.empty()) return refused;
|
|
const FlatpakExport app = ExportOf(config);
|
|
const FileLock lock = AppDirLock(app.work);
|
|
if (const std::string failed = ExportFlatpak(app); !failed.empty()) return failed;
|
|
// A remote of its own, re-pointed at this project's repo each time: the
|
|
// same app-id built in another checkout would otherwise go on updating
|
|
// from that one's, and --if-not-exists would keep it silently.
|
|
const std::string remote = std::format("crafter-build-{}", app.appId);
|
|
const std::string url = ShellQuote(FileUrl(app.work / "repo"));
|
|
// The remote is the installation's, shared by every checkout that builds
|
|
// this app-id, so re-pointing it and installing from it hold a lock of
|
|
// their own: another checkout's install would otherwise re-point it
|
|
// between this one's remote-modify and install. Every crafter-build that
|
|
// installs there has to take the same lock, native or in the Flatpak,
|
|
// with whatever XDG_CACHE_HOME it runs, so the lock follows the
|
|
// installation and not the cache: a private one, FLATPAK_USER_DIR, holds
|
|
// it, one lock for all of them where the sandbox shares that directory
|
|
// with the host, and for the user's own, which flatpak hides from
|
|
// crafter-build's sandbox behind a tmpfs of the sandbox's own, it is in
|
|
// ~/.cache by HOME.
|
|
const fs::path base = [] {
|
|
if (const char* userDir = std::getenv("FLATPAK_USER_DIR"); userDir && *userDir) return fs::path(userDir);
|
|
if (const char* home = std::getenv("HOME"); home && *home) return fs::path(home) / ".cache";
|
|
return fs::path();
|
|
}();
|
|
if (base.empty()) return "crafter-build install: neither FLATPAK_USER_DIR nor HOME is set, and the lock on the user's remote is found by one of them";
|
|
const fs::path locks = base / "crafter.build" / "flatpak-remotes";
|
|
std::error_code ec;
|
|
fs::create_directories(locks, ec);
|
|
const FileLock remoteLock(locks / std::format("{}.lock", remote));
|
|
if (RunHostFlatpak(std::format("remote-add --user --if-not-exists --no-gpg-verify {} {}", ShellQuote(remote), url)) != 0) return std::format("crafter-build install: adding the remote {} failed", remote);
|
|
if (RunHostFlatpak(std::format("remote-modify --user --url={} {}", url, ShellQuote(remote))) != 0) return std::format("crafter-build install: pointing the remote {} at the repo failed", remote);
|
|
if (RunHostFlatpak(std::format("install --user --noninteractive --or-update {} {}", ShellQuote(remote), ShellQuote(app.appId))) != 0) return std::format("crafter-build install: installing {} failed", app.appId);
|
|
if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) {
|
|
std::println("\nInstalled {0}: `flatpak run {0}` starts it.\nThe remote {1} points into build/, which `crafter-build clean` deletes; remove both with\n flatpak uninstall --user {0}\n flatpak remote-delete --user {1}", app.appId, remote);
|
|
}
|
|
return "";
|
|
}
|
|
|
|
namespace {
|
|
// CUDA sources compiled for native, code for the GPUs of the machine
|
|
// that builds and no PTX, in `config`'s program: its own, and those of
|
|
// every library Build hands its link, which it does through an
|
|
// executable dependency too. That executable's own objects are run by
|
|
// path and stay out of the bundle; `linked` is false for them alone,
|
|
// and it follows from a configuration's type, so `seen` holds either
|
|
// way.
|
|
bool HasNativeCuda(const Configuration& config, std::unordered_set<const Configuration*>& seen, bool linked = true) {
|
|
if (!seen.insert(&config).second) return false;
|
|
if (linked && !config.cuda.empty() && config.cudaArch == "native") return true;
|
|
return std::ranges::any_of(config.dependencies, [&seen](const Configuration* dep) { return HasNativeCuda(*dep, seen, dep->type != ConfigurationType::Executable); });
|
|
}
|
|
}
|
|
|
|
std::string Crafter::BundleFlatpakApp(const Configuration& config) {
|
|
if (const std::string refused = CannotExport(config, "bundle"); !refused.empty()) return refused;
|
|
const FlatpakExport app = ExportOf(config);
|
|
const FileLock lock = AppDirLock(app.work);
|
|
if (const std::string failed = ExportFlatpak(app); !failed.empty()) return failed;
|
|
const fs::path bundle = fs::absolute(FlatpakBundlePath(config)).lexically_normal();
|
|
// The runtime's repository goes into the bundle, so a machine without
|
|
// the Platform fetches it from Flathub on install instead of refusing.
|
|
if (RunHostFlatpak(std::format("build-bundle --runtime-repo=https://dl.flathub.org/repo/flathub.flatpakrepo {} {} {}", ShellQuote((app.work / "repo").string()), ShellQuote(bundle.string()), ShellQuote(app.appId))) != 0) {
|
|
return std::format("crafter-build bundle: flatpak build-bundle failed for {}", app.appId);
|
|
}
|
|
if (config.march == "native") {
|
|
Progress::Diagnostic(std::format("{} is built with -march=native, so it may stop with SIGILL on a CPU older than this one; for others, build with --march=x86-64-v3", bundle.string()));
|
|
}
|
|
if (std::unordered_set<const Configuration*> seen; HasNativeCuda(config, seen)) {
|
|
Progress::Diagnostic(std::format("{} holds CUDA code built with --cuda-arch=native, for this machine's GPUs and with no PTX, so it may not run on another machine's GPU; for others, build with --cuda-arch=all-major", bundle.string()));
|
|
}
|
|
if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) std::println("\nBundled {} as {}: `flatpak install --user {}` installs it.", app.appId, bundle.string(), bundle.filename().string());
|
|
return "";
|
|
}
|
|
|
|
fs::path Crafter::FlatpakBundlePath(const Configuration& config) {
|
|
return config.BinDir().parent_path() / std::format("{}.flatpak", config.VariantId());
|
|
}
|
|
|
|
fs::path Crafter::FlatpakAppDir(const Configuration& config) {
|
|
return config.BuildDir().parent_path() / "flatpak-apps" / AppIdOf(config);
|
|
}
|
|
|
|
std::string Crafter::FlatpakManifest(const Configuration& config) {
|
|
return FlatpakManifestText(ExportOf(config));
|
|
}
|
|
|
|
void Crafter::EnableWasiBrowserRuntime(Configuration& cfg) {
|
|
fs::path runtimeDir = GetCrafterBuildHome() / "wasi-runtime";
|
|
fs::path runtimeJs = runtimeDir / "runtime.js";
|
|
fs::path htmlTemplate = runtimeDir / "index.html.in";
|
|
if (!fs::exists(runtimeJs) || !fs::exists(htmlTemplate)) {
|
|
throw std::runtime_error(std::format("wasi-runtime assets missing under {} (set CRAFTER_BUILD_HOME or reinstall)", runtimeDir.string()));
|
|
}
|
|
|
|
fs::path htmlOutDir = cfg.path / "build" / "wasi-runtime" / cfg.name;
|
|
fs::create_directories(htmlOutDir);
|
|
fs::path htmlPath = htmlOutDir / "index.html";
|
|
|
|
// Walk the dep graph for env-style JS bridges that need to load BEFORE
|
|
// runtime.js so they can populate `window.crafter_webbuild_env`. Any
|
|
// `*.js` entry in a (transitive) dep's `cfg.files` qualifies — the
|
|
// file is already going to be copied into the consumer's bin dir, we
|
|
// just need its basename for a `<script src=...>` tag.
|
|
std::vector<std::string> envScripts;
|
|
std::unordered_set<Configuration*> seen;
|
|
std::function<void(Configuration*)> walk = [&](Configuration* c) {
|
|
if (!c || !seen.insert(c).second) return;
|
|
for (const fs::path& f : c->files) {
|
|
if (f.extension() == ".js" && f.filename() != "runtime.js") {
|
|
std::string name = f.filename().string();
|
|
if (std::find(envScripts.begin(), envScripts.end(), name) == envScripts.end()) {
|
|
envScripts.push_back(std::move(name));
|
|
}
|
|
}
|
|
}
|
|
for (Configuration* dep : c->dependencies) walk(dep);
|
|
};
|
|
walk(&cfg);
|
|
|
|
// Per-build cache-busting token. Stamped onto every script src + the
|
|
// wasm URL so a regular browser reload sees fresh files even though
|
|
// the dev server (python -m http.server) sends no Cache-Control
|
|
// headers. Using ms-since-epoch is enough to be unique per build
|
|
// without invoking any version-control machinery.
|
|
const std::string buildId = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count());
|
|
|
|
std::string envScriptTags;
|
|
for (const std::string& name : envScripts) {
|
|
envScriptTags += std::format(" <script src=\"{}?v={}\" type=\"module\"></script>\n", name, buildId);
|
|
}
|
|
|
|
// Walk the dep graph again for non-JS assets — these get pre-loaded by
|
|
// runtime.js into an in-memory VFS so the wasm's std::ifstream et al.
|
|
// can actually read them (the wasi-runtime in this repo otherwise
|
|
// stubs every fd syscall to zero).
|
|
//
|
|
// The manifest lists *relative paths* (e.g. "assets/Inter.ttf") so
|
|
// runtime.js's fetch() resolves against the bin-dir layout the asset
|
|
// copy step actually emits. The VFS is keyed by basename — path_open
|
|
// strips to basename on lookup, so subdir layouts collapse on the
|
|
// wasm side. Basename collisions across subdirs aren't supported on
|
|
// the wasi runtime today; if two assets share a basename, the last
|
|
// one preloaded wins. Avoid collisions in the source tree.
|
|
// The name Build() writes an asset under, by the rule its own copy uses,
|
|
// so the manifest cannot list a file the build never wrote.
|
|
auto compressedRel = [](const fs::path& rel) -> fs::path {
|
|
if (const std::optional<fs::path> name = CompressedAssetName(rel)) return rel.parent_path() / *name;
|
|
return rel;
|
|
};
|
|
std::vector<std::string> assetFiles;
|
|
auto pushUnique = [&](std::string name) {
|
|
if (name.empty()) return;
|
|
if (std::find(assetFiles.begin(), assetFiles.end(), name) == assetFiles.end()) {
|
|
assetFiles.push_back(std::move(name));
|
|
}
|
|
};
|
|
seen.clear();
|
|
std::function<void(Configuration*)> walkAssets = [&](Configuration* c) {
|
|
if (!c || !seen.insert(c).second) return;
|
|
for (const fs::path& f : c->files) {
|
|
std::string ext = f.extension().string();
|
|
if (ext == ".js" || ext == ".html") continue;
|
|
if (f.filename() == "runtime.js") continue;
|
|
// cfg.files lands flat next to the .wasm by `name = filename()`.
|
|
pushUnique(f.filename().string());
|
|
}
|
|
// cfg.assets — mirror the bin-dir layout the build emits: a
|
|
// directory entry becomes <topName>/<rel inside dir>, single
|
|
// files land flat at the bin root. What CompressedAssetName maps
|
|
// is compressed in place; everything else passes through under its
|
|
// original name.
|
|
for (const fs::path& a : c->assets) {
|
|
if (fs::is_directory(a)) {
|
|
const fs::path topName = a.filename();
|
|
std::error_code ec;
|
|
for (const auto& entry : fs::recursive_directory_iterator(a, ec)) {
|
|
if (ec) break;
|
|
if (!entry.is_regular_file()) continue;
|
|
fs::path rel = fs::relative(entry.path(), a);
|
|
pushUnique((topName / compressedRel(rel)).generic_string());
|
|
}
|
|
} else {
|
|
pushUnique(compressedRel(a.filename()).generic_string());
|
|
}
|
|
}
|
|
for (Configuration* dep : c->dependencies) walkAssets(dep);
|
|
};
|
|
walkAssets(&cfg);
|
|
|
|
fs::path manifestPath = htmlOutDir / "files.json";
|
|
{
|
|
std::ofstream m(manifestPath);
|
|
m << "[";
|
|
for (std::size_t i = 0; i < assetFiles.size(); ++i) {
|
|
if (i) m << ",";
|
|
m << "\"" << assetFiles[i] << "\"";
|
|
}
|
|
m << "]";
|
|
}
|
|
|
|
// Variant manifest. runtime.js fetches this, runs each entry's probes in
|
|
// order, and instantiates the first whose probes all pass — so the
|
|
// preferred (most feature-rich) variants come first and the baseline last
|
|
// as the fallback. Every entry carries WasmBaselineProbes besides its own:
|
|
// every file is built with the baseline flags, so an engine without
|
|
// exception handling can run none of them, and runtime.js tells it so
|
|
// instead of failing to compile the module. A variant with a non-empty
|
|
// label maps to outputName.<label>.wasm (produced by Build's variant
|
|
// driver); the baseline maps to outputName.wasm. Even with no declared
|
|
// variants we still emit a one-entry manifest so the runtime has a
|
|
// single, uniform code path.
|
|
fs::path variantsPath = htmlOutDir / "variants.json";
|
|
{
|
|
std::ofstream v(variantsPath);
|
|
v << "[";
|
|
bool first = true;
|
|
auto emit = [&](const std::string& label, const std::vector<std::string>& ownProbes) {
|
|
if (!first) v << ",";
|
|
first = false;
|
|
std::string url = label.empty()
|
|
? std::format("{}.wasm", cfg.outputName)
|
|
: std::format("{}.{}.wasm", cfg.outputName, label);
|
|
std::vector<std::string> probes = ownProbes;
|
|
probes.insert(probes.end(), WasmBaselineProbes.begin(), WasmBaselineProbes.end());
|
|
v << "{\"label\":" << JsonQuote(label)
|
|
<< ",\"url\":" << JsonQuote(url)
|
|
<< ",\"probes\":[";
|
|
for (std::size_t i = 0; i < probes.size(); ++i) {
|
|
if (i) v << ",";
|
|
v << JsonQuote(probes[i]);
|
|
}
|
|
v << "]}";
|
|
};
|
|
for (const WasmVariant& variant : cfg.wasmVariants) {
|
|
if (variant.label.empty()) continue; // baseline emitted below
|
|
emit(variant.label, variant.probes);
|
|
}
|
|
emit("", {}); // baseline fallback, always last
|
|
v << "]";
|
|
}
|
|
|
|
std::ifstream in(htmlTemplate);
|
|
std::stringstream buf;
|
|
buf << in.rdbuf();
|
|
std::string html = buf.str();
|
|
html = std::regex_replace(html, std::regex(R"(\{\{WASM\}\})"), std::format("{}.wasm", cfg.outputName));
|
|
html = std::regex_replace(html, std::regex(R"(\{\{ENV_SCRIPTS\}\})"), envScriptTags);
|
|
html = std::regex_replace(html, std::regex(R"(\{\{BUILDID\}\})"), buildId);
|
|
std::ofstream out(htmlPath);
|
|
out << html;
|
|
out.close();
|
|
|
|
cfg.files.push_back(runtimeJs);
|
|
cfg.files.push_back(htmlPath);
|
|
cfg.files.push_back(manifestPath);
|
|
cfg.files.push_back(variantsPath);
|
|
}
|
|
|
|
void Crafter::EnableWasiRelaxedSimdVariant(Configuration& cfg) {
|
|
for (const WasmVariant& v : cfg.wasmVariants) {
|
|
if (v.label == "relaxed-simd") return; // idempotent
|
|
}
|
|
cfg.wasmVariants.push_back(WasmVariant{
|
|
.label = "relaxed-simd",
|
|
.flags = {"-mrelaxed-simd"},
|
|
.probes = {"relaxed-simd"},
|
|
});
|
|
}
|
|
|
|
std::string Crafter::HostTarget() {
|
|
return GetToolchain().hostTriple;
|
|
}
|
|
|
|
std::string Crafter::NormalizeTarget(std::string_view triple) {
|
|
// <arch>-<vendor>-<os>-<env>: drop the vendor. A three-part triple only
|
|
// carries one when its middle part is a vendor name rather than an OS
|
|
// (x86_64-unknown-wasip1 yes, x86_64-linux-gnu no).
|
|
std::vector<std::string_view> parts;
|
|
for (std::size_t begin = 0;;) {
|
|
std::size_t dash = triple.find('-', begin);
|
|
parts.push_back(dash == std::string_view::npos ? triple.substr(begin) : triple.substr(begin, dash - begin));
|
|
if (dash == std::string_view::npos) break;
|
|
begin = dash + 1;
|
|
}
|
|
const bool hasVendor = parts.size() == 4 || (parts.size() == 3 && (parts[1] == "unknown" || parts[1] == "pc"));
|
|
if (hasVendor) parts.erase(parts.begin() + 1);
|
|
std::string out;
|
|
for (std::string_view part : parts) {
|
|
if (!out.empty()) out += '-';
|
|
out += part;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
bool Crafter::SameTarget(std::string_view a, std::string_view b) {
|
|
return a == b || NormalizeTarget(a) == NormalizeTarget(b);
|
|
}
|
|
|
|
bool Crafter::ArgQuery::Has(std::string_view flag) const {
|
|
for (std::string_view a : args) if (a == flag) return true;
|
|
return false;
|
|
}
|
|
|
|
std::optional<std::string> Crafter::ArgQuery::Get(std::string_view prefix) const {
|
|
for (std::string_view a : args) {
|
|
if (a.starts_with(prefix)) return std::string(a.substr(prefix.size()));
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
|
|
ArgQuery Crafter::ApplyStandardArgs(Configuration& cfg, std::span<const std::string_view> args) {
|
|
if (const char* envMarch = std::getenv("CRAFTER_BUILD_MARCH"); envMarch && *envMarch) {
|
|
cfg.march = envMarch;
|
|
}
|
|
if (const char* envMtune = std::getenv("CRAFTER_BUILD_MTUNE"); envMtune && *envMtune) {
|
|
cfg.mtune = envMtune;
|
|
}
|
|
if (const char* envCudaArch = std::getenv("CRAFTER_BUILD_CUDA_ARCH"); envCudaArch && *envCudaArch) {
|
|
cfg.cudaArch = envCudaArch;
|
|
}
|
|
bool sawLib = false;
|
|
bool sawShared = false;
|
|
for (std::string_view a : args) {
|
|
if (a == "--debug") cfg.debug = true;
|
|
else if (a == "--lib") sawLib = true;
|
|
else if (a == "--shared") sawShared = true;
|
|
else if (a.starts_with("--target=")) cfg.target = std::string(a.substr(std::string_view("--target=").size()));
|
|
else if (a.starts_with("--march=")) cfg.march = std::string(a.substr(std::string_view("--march=").size()));
|
|
else if (a.starts_with("--mtune=")) cfg.mtune = std::string(a.substr(std::string_view("--mtune=").size()));
|
|
else if (a.starts_with("--cuda-arch=")) cfg.cudaArch = std::string(a.substr(std::string_view("--cuda-arch=").size()));
|
|
else if (a.starts_with("--sysroot=")) cfg.sysroot = std::string(a.substr(std::string_view("--sysroot=").size()));
|
|
else if (a.starts_with("--packaging=")) {
|
|
const std::string_view kind = a.substr(std::string_view("--packaging=").size());
|
|
if (kind != "none" && kind != "flatpak") throw std::invalid_argument(std::format("--packaging={}: expected none or flatpak", kind));
|
|
// The args reach every dependency the project loads, whose
|
|
// executables stay as linked: their consumers run them by path.
|
|
// So only the project crafter-build was pointed at reads it.
|
|
if (IsTopLevelProject()) cfg.packaging = kind == "flatpak" ? Packaging::Flatpak : Packaging::None;
|
|
}
|
|
// Anything else is the project's own flag. Its effect on the output is
|
|
// opaque to the framework, so it has to key into VariantId or two flag
|
|
// settings share a bin dir and leave a bundle matching neither.
|
|
else cfg.projectArgs.emplace_back(a);
|
|
}
|
|
// Sorted and deduplicated so the identity depends on the set of flags, not
|
|
// on how they were ordered or repeated.
|
|
std::ranges::sort(cfg.projectArgs);
|
|
cfg.projectArgs.erase(std::ranges::unique(cfg.projectArgs).begin(), cfg.projectArgs.end());
|
|
if (sawLib && cfg.type == ConfigurationType::Executable) cfg.type = ConfigurationType::LibraryStatic;
|
|
if (sawShared && cfg.type == ConfigurationType::LibraryStatic) cfg.type = ConfigurationType::LibraryDynamic;
|
|
// The WASI sysroot a wasm32 configuration is built against when it
|
|
// names none, stored where the project file can read it and hand it to
|
|
// other configurations it makes. No build depends on it being stored: a
|
|
// configuration that never came through here resolves to the same
|
|
// directory (Configuration::ResolvedSysroot).
|
|
cfg.sysroot = cfg.ResolvedSysroot(GetToolchain());
|
|
return ArgQuery{args};
|
|
}
|
|
|
|
std::vector<fs::path> Crafter::CleanProject(const fs::path& projectFile) {
|
|
fs::path projectDir = fs::absolute(projectFile).lexically_normal().parent_path();
|
|
std::vector<fs::path> removed;
|
|
for (std::string_view name : { "bin", "build" }) {
|
|
fs::path dir = projectDir / name;
|
|
std::error_code ec;
|
|
if (!fs::is_directory(dir, ec)) continue;
|
|
if (fs::remove_all(dir, ec) == static_cast<std::uintmax_t>(-1) || ec) {
|
|
throw std::runtime_error(std::format("could not remove {}: {}", dir.string(), ec.message()));
|
|
}
|
|
removed.push_back(std::move(dir));
|
|
}
|
|
return removed;
|
|
}
|
|
|
|
static void PrintVersion() {
|
|
std::println("crafter-build {}", CrafterBuildVersion());
|
|
const Toolchain& tc = GetToolchain();
|
|
// nvcc only when there is one: most projects have no CUDA sources, and the
|
|
// build that has some says where it looked. The static runtime beside it
|
|
// as well, which says whether one is linked. Found apart from the
|
|
// compiler, so printed whether or not that was resolved.
|
|
const auto cuda = [&tc]() {
|
|
if (!tc.nvcc.empty()) std::println("nvcc {}", tc.nvcc.string());
|
|
if (!tc.cudaRuntime.empty()) std::println("cudart {}", tc.cudaRuntime.string());
|
|
};
|
|
if (!tc.error.empty()) {
|
|
std::println("compiler: {}", tc.error);
|
|
cuda();
|
|
return;
|
|
}
|
|
std::println("compiler {} ({})", tc.clangVersion, tc.clangxx.string());
|
|
if (tc.libcxxVersion != 0) {
|
|
// A sysroot on another libc++ release builds only when its std
|
|
// module source is in the sysroot or among these; printed here
|
|
// because that is the first question when such a build fails.
|
|
std::vector<std::string> shipped;
|
|
std::error_code ec;
|
|
for (const fs::directory_entry& entry : fs::directory_iterator(tc.stdModulesDir, ec)) {
|
|
if (fs::exists(entry.path() / "std.cppm")) shipped.push_back(entry.path().filename().string());
|
|
}
|
|
std::ranges::sort(shipped);
|
|
std::string also;
|
|
for (const std::string& release : shipped) also += std::format(", {}", release);
|
|
std::println("libc++ {}{}", LibcxxVersionString(tc.libcxxVersion), also.empty() ? std::string() : std::format(" (std module sources for sysroots also for{})", also.substr(1)));
|
|
}
|
|
std::println("host {}", tc.hostTriple);
|
|
cuda();
|
|
}
|
|
|
|
static void PrintHelp(std::string_view argv0) {
|
|
std::println(
|
|
R"(Usage:
|
|
{0} [options] [-- project-args...] Build the project in the current directory
|
|
{0} test [test-options] [globs...] Build and run the project's tests
|
|
{0} lint [lint-options] [globs...] Run the project's lint rules over its sources
|
|
{0} format [format-options] [globs...] Apply the project's transform rules (rewrites files)
|
|
{0} run [script [args...]] Run a script the project defines, or list them
|
|
{0} install [options] Build a project packaged as a Flatpak and install it for this user
|
|
{0} bundle [options] Build a project packaged as a Flatpak into a .flatpak file
|
|
{0} clean Delete the project's bin/ and build/ trees
|
|
{0} help | -h | --help Show this help
|
|
{0} --version Print the version and the compiler in use
|
|
|
|
Loads ./project.cpp (override with --project=<path>), compiles it to a shared
|
|
object, and invokes its CrafterBuildProject() to obtain a Configuration that
|
|
drives the build. Outputs land at bin/<name>-<target>-<march>/, intermediates
|
|
at build/<name>-<target>-<march>/. A project of several configurations
|
|
defines CrafterBuildConfigurations() instead, which returns them all and gets
|
|
the same args, and every one of them is built.
|
|
|
|
A build runs at most as many of its steps at once as the machine has hardware
|
|
threads: the compiles of its sources, its shaders and assets, and its links
|
|
and archives, counted together for the project and the dependencies it is
|
|
built on. An external dependency's CMake build is not among them, nor are the
|
|
tests `test` runs. A step counts as one whatever threads it starts for itself,
|
|
as a link and the compression of an asset do.
|
|
|
|
Build options:
|
|
-r Run the produced executable after a successful build:
|
|
one for the host in its own directory, a wasm32 one
|
|
under wasmtime or wasmer, or one built for the
|
|
browser served over HTTP from its directory.
|
|
Libraries cannot be run, and of several
|
|
configurations one has to be the only executable.
|
|
-v, --verbose Verbose progress output.
|
|
-q, --quiet Suppress progress output.
|
|
--project=<path> Path to the project file (default: ./project.cpp).
|
|
-- Ends this tool's options. Every later word is a
|
|
project arg, even one that looks like an option or
|
|
a verb; after test, lint or format, a glob; after
|
|
run, the script's name and then its args.
|
|
|
|
Test options (after the `test` subcommand):
|
|
--list Enumerate matching tests without running them.
|
|
--jobs=<N> Tests built and run at once (default: one per
|
|
hardware thread). The steps of their builds share
|
|
the one limit a build has.
|
|
--timeout=<seconds> Per-test timeout override.
|
|
--runner=<spec> Override the test runner for this run. Specs:
|
|
local
|
|
cmd:<command> (e.g. cmd:wine)
|
|
--compositor=<command> The headless Wayland compositor each test that sets
|
|
Test::wayland runs with, a command run through sh
|
|
that listens on a wayland-<n> socket in the
|
|
XDG_RUNTIME_DIR it is given. Default: weston
|
|
--backend=headless --renderer=gl --no-config
|
|
--idle-time=0. `host` runs those tests on this
|
|
session's own display.
|
|
--target=<triple> Filter to tests whose cfg.target matches. Default:
|
|
sweep across every distinct target declared by the
|
|
project's tests plus the host triple.
|
|
<glob> One or more name globs to filter tests (e.g. 'Unit*').
|
|
|
|
Lint options (after the `lint` subcommand):
|
|
--list Enumerate matching lint rules without running them.
|
|
--no-ast Skip rules that need an AST instead of building the
|
|
module PCMs they require.
|
|
<glob> One or more name globs to filter rules (e.g. 'spdx*').
|
|
|
|
Lint rules are defined in project.cpp via cfg.AddLintRule(name, callback) —
|
|
C++ callbacks run once per source file. No rules ship by default.
|
|
|
|
cfg.AddAstLintRule registers a rule that reads ctx.Decls(), clang's view of
|
|
the declarations in the file. Those need the module PCMs, which the run
|
|
builds if they are missing; a file whose AST cannot be produced is an error,
|
|
never a silent pass. --no-ast skips them instead.
|
|
|
|
Format options (after the `format` subcommand):
|
|
--check Dry run: list files that would change, exit 1 if any.
|
|
--list Enumerate matching rules without running them.
|
|
--no-ast Skip rules that need an AST (see `lint --no-ast`).
|
|
<glob> One or more name globs to filter rules.
|
|
|
|
Rules are shared with lint — a rule that calls ctx.SetContent is a
|
|
transform. `format` rewrites changed files in place; `lint` reports the
|
|
same transforms as would-reformat findings without writing.
|
|
|
|
Run (after the `run` subcommand):
|
|
<script> [args...] Run the named script. Everything after the name is
|
|
handed to the script untouched, including what
|
|
looks like an option of crafter-build itself, so
|
|
-v, -q, --project= and project args go before it.
|
|
--list List the project's scripts. A bare `run` does too.
|
|
|
|
Scripts are defined in project.cpp, as entries of cfg.scripts:
|
|
cfg.scripts.push_back({{"docs", [](Crafter::ScriptContext& ctx) {{
|
|
return ctx.Run("python3 tools/gen-docs.py");
|
|
}}}});
|
|
The callback returns the exit status. ctx.Run runs a shell command with the
|
|
terminal attached and returns its status; ctx.args holds the arguments and
|
|
ctx.projectDir the project's directory. Commands run in the directory
|
|
crafter-build was started from. Only the scripts of the project being run
|
|
are available, never a dependency's.
|
|
|
|
Install and bundle (after the `install` or `bundle` subcommand):
|
|
Both need the project's executable packaged as a Flatpak (cfg.packaging =
|
|
Packaging::Flatpak, or --packaging=flatpak where project.cpp calls
|
|
ApplyStandardArgs), and refuse before building when it is not, or when the
|
|
host's flatpak cannot be reached. They build the project, have the host's
|
|
flatpak build-finish make the app of its files/ with the permissions, which
|
|
it refuses where it does not know one, and export it into the project's
|
|
repo, build/flatpak-apps/<app-id>/repo, with flatpak build-export, or have
|
|
flatpak-builder do both when cfg.flatpak.modules names modules. install
|
|
installs it for this user from the remote crafter-build-<app-id>; bundle
|
|
writes it into a single .flatpak file beside its bin directory, for
|
|
`flatpak install --user`, naming Flathub's repository for the runtime. Both
|
|
run the host's flatpak, inside crafter-build's Flatpak through
|
|
flatpak-spawn --host, and refuse a project whose bin/ and build/ the host
|
|
does not see where crafter-build does, as in the sandbox's own /tmp, /var,
|
|
/usr, /etc and /app, which they ask the host before building. Of several
|
|
configurations they export the one that is packaged as a Flatpak, and
|
|
refuse before building when none is, or more than one.
|
|
|
|
Clean (after the `clean` subcommand):
|
|
Removes bin/ and build/ next to the project file. Does not load project.cpp,
|
|
so it works when the project itself no longer compiles. Every target, variant
|
|
and dependency artifact under those trees goes with it, and so does the repo
|
|
an app from `install` is installed from: remove the app and its remote
|
|
first, as install says how.
|
|
|
|
AGENTS.md:
|
|
When an AGENTS.template.md sits beside the project file, a build and a test
|
|
run write AGENTS.md from it, with a section holding the AGENTS.consumer.md
|
|
each dependency ships beside its project.cpp, and only when the text changes.
|
|
Commit the template and keep AGENTS.md out of version control. An AGENTS.md
|
|
no build wrote is never replaced, and without a template AGENTS.md is left
|
|
alone. cfg.dependencyNotes picks the dependencies: Transitive (the default),
|
|
Direct, or None.
|
|
|
|
Project args:
|
|
Any flag not consumed above is forwarded verbatim to the project file's
|
|
entry point as part of its `args` span. Project-specific flags (e.g.
|
|
--target=, custom feature toggles) live there. ApplyStandardArgs reads
|
|
--debug, --target=, --march=, --mtune=, --cuda-arch=, --sysroot=, --lib,
|
|
--shared and --packaging=none|flatpak, the last for the project
|
|
crafter-build was pointed at only. Flags it does not itself interpret are
|
|
folded into the variant hash, so switching one lands in its own bin/ and
|
|
build/ directory instead of overwriting the other setting's.
|
|
|
|
Environment:
|
|
CRAFTER_BUILD_MARCH Override -march (default: native).
|
|
CRAFTER_BUILD_MTUNE Override -mtune (default: native).
|
|
CRAFTER_BUILD_CUDA_ARCH Override nvcc's -arch for cfg.cuda
|
|
(default: native).
|
|
CUDA_PATH CUDA toolkit whose bin/nvcc compiles
|
|
cfg.cuda. Default: /opt/cuda, then
|
|
/usr/local/cuda (in the Flatpak, the
|
|
host's), then nvcc on PATH.
|
|
CRAFTER_BUILD_RUNNER_<TARGET> Default test runner for a target triple.
|
|
Replace '-' and '.' with '_' in the
|
|
triple. CLI --runner= overrides this.
|
|
CRAFTER_BUILD_COMPOSITOR Default headless Wayland compositor for
|
|
tests that set Test::wayland, as for
|
|
--compositor=, which overrides it.
|
|
CRAFTER_BUILD_LLVM_DIR LLVM prefix to use instead of a toolchain
|
|
installed beside crafter-build or PATH.
|
|
CRAFTER_BUILD_LIBCXX_DIR libc++ install to compile and link against
|
|
instead of the compiler's own.
|
|
CRAFTER_BUILD_LIBCLANG Exact libclang to load for lint.
|
|
CRAFTER_BUILD_WASI_SYSROOT WASI sysroot for wasm32 targets.
|
|
CRAFTER_BUILD_FLATPAK_INFO File to read the runtime a Flatpak is
|
|
packaged for from, in place of
|
|
/.flatpak-info; for tests.
|
|
CRAFTER_MINGW_DIR mingw-w64 prefix (holding x86_64-w64-mingw32/
|
|
and lib/gcc/). Default: the mingw gcc on
|
|
PATH; in the Flatpak, the host's /usr when
|
|
it has mingw-w64. Of a prefix that holds a
|
|
Linux system too, such as /usr, clang sees
|
|
only those directories.
|
|
CRAFTER_BUILD_HOME Directory holding the module sources.
|
|
|
|
Exit status:
|
|
0 success / all non-skipped tests passed / lint clean / format applied
|
|
1 build failure, one or more tests failed, lint findings, no rules defined,
|
|
format write errors, `format --check` found files that would change, or
|
|
`install` or `bundle` was refused or its export, install or bundle failed
|
|
`run` exits with the status its script returned, and with 1 when there is no
|
|
such script, when the script throws, or when it returns a value outside 0..255
|
|
)", argv0);
|
|
}
|
|
|
|
// lint-disable-next-line no-char-pointer
|
|
std::int32_t Crafter::Run(std::int32_t argc, char** argv) {
|
|
try {
|
|
std::string_view argv0 = argc > 0 ? argv[0] : "crafter-build";
|
|
fs::path projectFile = "./project.cpp";
|
|
std::vector<std::string_view> projectArgs;
|
|
projectArgs.reserve(argc);
|
|
|
|
// What this invocation does: the first verb on the command line, a
|
|
// build without one. A verb word after it is an operand of that one
|
|
// (`test lint` runs the tests that match "lint", `run test` runs the
|
|
// script called test) or a project arg, never a second verb.
|
|
enum class Verb { Build, Test, Lint, Format, Clean, Run, Install, Bundle };
|
|
Verb verb = Verb::Build;
|
|
bool runAfterBuild = false;
|
|
RunTestsOptions testOpts;
|
|
RunLintOptions lintOpts;
|
|
RunScriptOptions scriptOpts;
|
|
Progress::Verbosity verbosity = Progress::Verbosity::Default;
|
|
// Set by `--`: every later word is an operand of the verb, never an
|
|
// option or a verb of this tool.
|
|
bool operandsOnly = false;
|
|
|
|
for (std::int32_t i = 1; i < argc; ++i) {
|
|
std::string_view arg = argv[i];
|
|
// The two `run` branches come before everything else on purpose.
|
|
// What follows a script's name belongs to the script, whatever
|
|
// it looks like: `run package --help` must not print this
|
|
// tool's help, `run package clean` must not delete build/, and
|
|
// none of it may reach projectArgs, where it would change the
|
|
// variant hash and so the directory the project builds into.
|
|
if (scriptOpts.named) {
|
|
scriptOpts.args.emplace_back(arg);
|
|
} else if (verb == Verb::Run && (operandsOnly || !arg.starts_with("-"))) {
|
|
// The first word after `run`, even one that is a verb
|
|
// elsewhere. Options before it keep their usual meaning.
|
|
scriptOpts.name = arg;
|
|
scriptOpts.named = true;
|
|
} else if (operandsOnly) {
|
|
if (verb == Verb::Test) {
|
|
testOpts.globs.emplace_back(arg);
|
|
} else if (verb == Verb::Lint || verb == Verb::Format) {
|
|
lintOpts.globs.emplace_back(arg);
|
|
} else {
|
|
projectArgs.push_back(arg);
|
|
}
|
|
} else if (arg == "--") {
|
|
// Ends this tool's options and is never forwarded itself. It
|
|
// used to land in projectArgs as a word of its own, giving the
|
|
// project a variant hash of its own, and every sibling project
|
|
// that inherits the args one as well.
|
|
operandsOnly = true;
|
|
} else if (arg == "--version") {
|
|
// Answered here, before the project file is looked for, so
|
|
// it works in any directory and is never forwarded to
|
|
// project.cpp as an unknown argument.
|
|
PrintVersion();
|
|
return 0;
|
|
} else if (arg == "-h" || arg == "--help" || (verb != Verb::Test && verb != Verb::Lint && verb != Verb::Format && arg == "help")) {
|
|
PrintHelp(argv0);
|
|
return 0;
|
|
} else if (verb == Verb::Build && arg == "test") {
|
|
verb = Verb::Test;
|
|
} else if (verb == Verb::Build && arg == "lint") {
|
|
verb = Verb::Lint;
|
|
} else if (verb == Verb::Build && arg == "clean") {
|
|
verb = Verb::Clean;
|
|
} else if (verb == Verb::Build && arg == "format") {
|
|
verb = Verb::Format;
|
|
lintOpts.mode = LintMode::Apply;
|
|
} else if (verb == Verb::Build && arg == "run") {
|
|
verb = Verb::Run;
|
|
} else if (verb == Verb::Build && arg == "install") {
|
|
verb = Verb::Install;
|
|
} else if (verb == Verb::Build && arg == "bundle") {
|
|
verb = Verb::Bundle;
|
|
} else if (verb == Verb::Run && arg == "--list") {
|
|
scriptOpts.listOnly = true;
|
|
} else if (verb == Verb::Format && arg == "--check") {
|
|
lintOpts.mode = LintMode::Check;
|
|
} else if (arg == "-r") {
|
|
runAfterBuild = true;
|
|
} else if (arg == "-v" || arg == "--verbose") {
|
|
verbosity = Progress::Verbosity::Verbose;
|
|
} else if (arg == "-q" || arg == "--quiet") {
|
|
verbosity = Progress::Verbosity::Quiet;
|
|
} else if (arg.starts_with("--project=")) {
|
|
projectFile = arg.substr(std::string_view("--project=").size());
|
|
} else if (verb == Verb::Test && arg.starts_with("--jobs=")) {
|
|
testOpts.jobs = std::stoi(std::string(arg.substr(std::string_view("--jobs=").size())));
|
|
} else if (verb == Verb::Test && arg.starts_with("--timeout=")) {
|
|
testOpts.timeoutOverride = std::chrono::seconds(std::stoi(std::string(arg.substr(std::string_view("--timeout=").size()))));
|
|
} else if (verb == Verb::Test && arg == "--list") {
|
|
testOpts.listOnly = true;
|
|
} else if (verb == Verb::Test && arg.starts_with("--runner=")) {
|
|
testOpts.runnerOverride = std::string(arg.substr(std::string_view("--runner=").size()));
|
|
} else if (verb == Verb::Test && arg.starts_with("--compositor=")) {
|
|
testOpts.compositorOverride = std::string(arg.substr(std::string_view("--compositor=").size()));
|
|
} else if (verb == Verb::Test && !arg.starts_with("-")) {
|
|
testOpts.globs.emplace_back(arg);
|
|
} else if ((verb == Verb::Lint || verb == Verb::Format) && arg == "--list") {
|
|
lintOpts.listOnly = true;
|
|
} else if ((verb == Verb::Lint || verb == Verb::Format) && arg == "--no-ast") {
|
|
lintOpts.noAst = true;
|
|
} else if ((verb == Verb::Lint || verb == Verb::Format) && !arg.starts_with("-")) {
|
|
lintOpts.globs.emplace_back(arg);
|
|
} else {
|
|
projectArgs.push_back(arg);
|
|
}
|
|
}
|
|
|
|
Progress::SetVerbosity(verbosity);
|
|
|
|
// The test run is target-scoped: only tests whose cfg.target equals
|
|
// testOpts.targetFilter are included. Default = host triple, so a
|
|
// bare `crafter-build test` runs everything that targets host.
|
|
for (auto& a : projectArgs) {
|
|
if (a.starts_with("--target=")) {
|
|
testOpts.targetFilter = std::string(a.substr(std::string_view("--target=").size()));
|
|
}
|
|
}
|
|
|
|
if (!fs::exists(projectFile)) {
|
|
std::println(std::cerr, "No project file at {}", projectFile.string());
|
|
return 1;
|
|
}
|
|
|
|
// Ahead of the load on purpose — see CleanProject.
|
|
if (verb == Verb::Clean) {
|
|
std::vector<fs::path> removed = CleanProject(projectFile);
|
|
if (removed.empty()) {
|
|
std::println("Nothing to clean");
|
|
} else {
|
|
for (const fs::path& dir : removed) std::println("Removed {}", dir.string());
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
// What the project file describes: one configuration, or several
|
|
// that are all built.
|
|
const std::vector<Configuration*> configurations = LoadConfigurations(projectFile, projectArgs);
|
|
// The ones the file made itself: every one but those that another
|
|
// project's file returned to GitProject or LocalProject. One of
|
|
// those, returned here in turn, is built with the rest, and -r,
|
|
// install and bundle count it among them, but its tests and its
|
|
// scripts stay that project's: `run` still reaches no script but
|
|
// those of the project crafter-build was pointed at.
|
|
std::vector<Configuration*> own;
|
|
for (Configuration* cfg : configurations) {
|
|
if (!LoadedProjectOf(*cfg)) own.push_back(cfg);
|
|
}
|
|
SetParentProject(configurations);
|
|
|
|
if (verb == Verb::Run) {
|
|
scriptOpts.projectFile = fs::absolute(projectFile).lexically_normal();
|
|
return RunScript(own, scriptOpts);
|
|
}
|
|
|
|
if (verb == Verb::Lint || verb == Verb::Format) {
|
|
// lexically_normal: fs::absolute keeps a "./" component, which
|
|
// would leak into displayed paths and the project-root derivation.
|
|
lintOpts.projectFile = fs::absolute(projectFile).lexically_normal();
|
|
LintSummary lintSummary = RunLint(configurations, lintOpts);
|
|
if (verb == Verb::Lint) return lintSummary.Clean() ? 0 : 1;
|
|
if (lintSummary.noRulesDefined || lintSummary.errors > 0) return 1;
|
|
// Apply: formatting files is success (gofmt convention).
|
|
// Check: a would-change file is the CI failure signal.
|
|
return lintOpts.mode == LintMode::Check && !lintSummary.changedFiles.empty() ? 1 : 0;
|
|
}
|
|
|
|
// What install and bundle cannot export they refuse here, before
|
|
// anything is built: a project that is not packaged as a Flatpak, or
|
|
// a host flatpak out of reach, is known from the loaded project, and
|
|
// so is which of several configurations is the app.
|
|
ExportChoice exported;
|
|
if (verb == Verb::Install || verb == Verb::Bundle) {
|
|
exported = ChooseExport(configurations, verb == Verb::Install ? "install" : "bundle");
|
|
if (!exported.refused.empty()) {
|
|
std::println(std::cerr, "{}", exported.refused);
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
// What the list itself rules out is refused here too, before any of
|
|
// it is built and before AGENTS.md is written: two returned
|
|
// configurations of one directory for every verb that builds, and
|
|
// for the verbs that build the configurations themselves whatever
|
|
// else BuildAll refuses a list for. `test` builds its tests with
|
|
// Build() and never comes to BuildAll, which makes these refusals
|
|
// again for whoever calls it.
|
|
if (const std::string refused = verb == Verb::Test ? SameDirectoryError(configurations) : PlanBuild(configurations).refused; !refused.empty()) {
|
|
Progress::Clear();
|
|
std::println(std::cerr, "{}", refused);
|
|
return 1;
|
|
}
|
|
|
|
// Builds and test runs only: lint and `format --check` promise to
|
|
// write nothing, `format` rewrites the project's sources and nothing
|
|
// else, `run` is for chores and `test --list` only lists. Here,
|
|
// before compiling, because loading has just fetched every
|
|
// dependency, so the notes are current, and an agent fixing a build
|
|
// that fails needs them.
|
|
if (!testOpts.listOnly) UpdateAgentsMd(configurations, projectFile);
|
|
|
|
if (verb == Verb::Test) {
|
|
TestSummary summary = RunTests(own, testOpts, projectArgs);
|
|
return summary.AllPassed() ? 0 : 1;
|
|
}
|
|
|
|
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
|
|
std::mutex depMutex;
|
|
if (const std::string failed = BuildAll(configurations, depResults, depMutex); !failed.empty()) {
|
|
Progress::Clear();
|
|
std::println(std::cerr, "{}", failed);
|
|
return 1;
|
|
}
|
|
|
|
Progress::Finalize();
|
|
|
|
if (verb == Verb::Install || verb == Verb::Bundle) {
|
|
const std::string failed = verb == Verb::Install ? InstallFlatpakApp(*exported.config) : BundleFlatpakApp(*exported.config);
|
|
if (failed.empty()) return 0;
|
|
std::println(std::cerr, "{}", failed);
|
|
return 1;
|
|
}
|
|
|
|
if (runAfterBuild) {
|
|
std::vector<const Configuration*> executables;
|
|
for (const Configuration* cfg : configurations) {
|
|
if (cfg->type == ConfigurationType::Executable) executables.push_back(cfg);
|
|
}
|
|
if (executables.empty()) {
|
|
std::println(std::cerr, "-r: cannot run a library");
|
|
return 1;
|
|
}
|
|
// Everything is built by now, as without -r. Which one to run
|
|
// would be a guess.
|
|
if (executables.size() > 1) {
|
|
std::println(std::cerr, "-r: {} are executables, and -r runs one", NamesOf(executables));
|
|
return 1;
|
|
}
|
|
const Configuration& config = *executables.front();
|
|
fs::path dir = config.ProgramDir();
|
|
fs::path artifact = fs::absolute(ExpectedOutput(config));
|
|
fs::path absDir = fs::absolute(dir);
|
|
|
|
// wasm targets need either a wasm runtime (wasi-cli) or an HTTP
|
|
// server (browser build with index.html). std::system on the
|
|
// .wasm path goes nowhere useful — replace with detection.
|
|
if (config.target.starts_with("wasm32")) {
|
|
const bool browserBuild = fs::exists(absDir / "index.html");
|
|
auto have = [](std::string_view exe) {
|
|
std::string probe = std::format("command -v {} > /dev/null 2>&1", exe);
|
|
return std::system(probe.c_str()) == 0;
|
|
};
|
|
if (browserBuild) {
|
|
// Probe-bind to find a free port starting at 8080 — if the
|
|
// user has another dev server running we shift up rather
|
|
// than letting caddy/python exit with EADDRINUSE.
|
|
auto findFreePort = [](std::int32_t basePort, std::int32_t span) -> std::int32_t {
|
|
using Sock = std::int32_t;
|
|
const Sock invalid = -1;
|
|
auto closesock = [](Sock s){ ::close(s); };
|
|
for (std::int32_t p = basePort; p < basePort + span; ++p) {
|
|
Sock s = ::socket(AF_INET, SOCK_STREAM, 0);
|
|
if (s == invalid) return basePort;
|
|
sockaddr_in addr{};
|
|
addr.sin_family = AF_INET;
|
|
addr.sin_addr.s_addr = htonl(INADDR_ANY);
|
|
addr.sin_port = htons(static_cast<std::uint16_t>(p));
|
|
bool ok = ::bind(s, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == 0;
|
|
closesock(s);
|
|
if (ok) return p;
|
|
}
|
|
return basePort;
|
|
};
|
|
const std::int32_t port = findFreePort(8080, 16);
|
|
// Cross-origin isolation: the browser coarsens
|
|
// performance.now() (and chrono::steady_clock under wasi)
|
|
// to ~0.1ms unless the response carries COOP/COEP, which
|
|
// floors the --timing overlay's sub-ms phase counters to
|
|
// zero. Emitting same-origin / require-corp drops the
|
|
// resolution to ~5µs and also unlocks SharedArrayBuffer
|
|
// for any future threading work. CORP keeps the local
|
|
// asset fetches passing under require-corp.
|
|
auto writeFile = [](const fs::path& p, std::string_view contents) {
|
|
std::ofstream f(p, std::ios::binary | std::ios::trunc);
|
|
f.write(contents.data(), static_cast<std::streamsize>(contents.size()));
|
|
};
|
|
std::string cmd;
|
|
std::string_view picked;
|
|
bool isolated = false;
|
|
if (have("caddy")) {
|
|
picked = "caddy";
|
|
isolated = true;
|
|
// caddy file-server has no --header flag; write a
|
|
// Caddyfile next to the build output. Adapter is
|
|
// inferred from the .caddyfile extension when run
|
|
// via `caddy run`.
|
|
fs::path cf = absDir / "Caddyfile.coi";
|
|
writeFile(cf, std::format(
|
|
":{} {{\n"
|
|
" root * {}\n"
|
|
" header Cross-Origin-Opener-Policy \"same-origin\"\n"
|
|
" header Cross-Origin-Embedder-Policy \"require-corp\"\n"
|
|
" header Cross-Origin-Resource-Policy \"same-origin\"\n"
|
|
" header Cache-Control \"no-store\"\n"
|
|
// Every EnableWasiBrowserRuntime consumer is a
|
|
// single-page wasm app by construction: the
|
|
// generated index.html ships an empty <body> and
|
|
// the module builds the DOM at runtime. So an app
|
|
// that routes on window.location has no file on
|
|
// disk for any path but "/", and a bare
|
|
// file_server 404s every deep link, refresh and
|
|
// shared URL during development.
|
|
//
|
|
// try_files falls through to index.html only for
|
|
// paths that are not real files, so static assets
|
|
// still serve normally and a genuinely missing
|
|
// asset becomes a visible wrong-content-type
|
|
// rather than a silent 404 the app can't see.
|
|
" try_files {{path}} /index.html\n"
|
|
" file_server\n"
|
|
"}}\n",
|
|
port, absDir.string()));
|
|
cmd = std::format("caddy run --config {} --adapter caddyfile", cf.string());
|
|
} else if (have("python3") || have("python")) {
|
|
std::string_view py = have("python3") ? "python3" : "python";
|
|
picked = py;
|
|
isolated = true;
|
|
// Inline a tiny SimpleHTTPRequestHandler subclass
|
|
// that appends the COI headers on every response.
|
|
// Lives in absDir so the user can re-run it manually
|
|
// (`python3 absDir/.serve-coi.py 8080`).
|
|
fs::path sp = absDir / ".serve-coi.py";
|
|
writeFile(sp,
|
|
"import http.server, socketserver, sys, os\n"
|
|
"class H(http.server.SimpleHTTPRequestHandler):\n"
|
|
" def end_headers(self):\n"
|
|
" self.send_header('Cross-Origin-Opener-Policy', 'same-origin')\n"
|
|
" self.send_header('Cross-Origin-Embedder-Policy', 'require-corp')\n"
|
|
" self.send_header('Cross-Origin-Resource-Policy', 'same-origin')\n"
|
|
" self.send_header('Cache-Control', 'no-store')\n"
|
|
" super().end_headers()\n"
|
|
"socketserver.TCPServer.allow_reuse_address = True\n"
|
|
"port = int(sys.argv[1]) if len(sys.argv) > 1 else 8080\n"
|
|
"os.chdir(os.path.dirname(os.path.abspath(__file__)))\n"
|
|
"with socketserver.TCPServer(('', port), H) as s:\n"
|
|
" s.serve_forever()\n");
|
|
cmd = std::format("{} {} {}", py, sp.string(), port);
|
|
} else if (have("php")) {
|
|
picked = "php";
|
|
// php -S supports a router script — emit one that
|
|
// sets COI headers then delegates to the built-in
|
|
// static-file handler by returning false.
|
|
fs::path rp = absDir / ".serve-coi.php";
|
|
writeFile(rp,
|
|
"<?php\n"
|
|
"header('Cross-Origin-Opener-Policy: same-origin');\n"
|
|
"header('Cross-Origin-Embedder-Policy: require-corp');\n"
|
|
"header('Cross-Origin-Resource-Policy: same-origin');\n"
|
|
"header('Cache-Control: no-store');\n"
|
|
"return false;\n");
|
|
isolated = true;
|
|
cmd = std::format("php -S 0.0.0.0:{} -t {} {}", port, absDir.string(), rp.string());
|
|
} else if (have("ruby")) {
|
|
picked = "ruby";
|
|
cmd = std::format("ruby -run -e httpd {} -p{}", absDir.string(), port);
|
|
} else if (have("busybox")) {
|
|
picked = "busybox httpd";
|
|
cmd = std::format("busybox httpd -f -p {} -h {}", port, absDir.string());
|
|
} else if (have("npx")) {
|
|
picked = "npx http-server";
|
|
cmd = std::format("npx --yes http-server {} -p {} --silent", absDir.string(), port);
|
|
} else {
|
|
std::println(std::cerr, "-r wasm: no HTTP server found in PATH. Install one of: " "caddy, python3, python, php, ruby, busybox, npx (Node.js).");
|
|
return 1;
|
|
}
|
|
std::println("listening on port :{}", port);
|
|
if (!isolated) {
|
|
std::println(std::cerr, "warning: {} does not emit COOP/COEP — performance.now() will be coarse " "(~0.1ms). Install caddy, python3, or php for cross-origin isolation.", picked);
|
|
}
|
|
// Silence the backend's own banner/request logs so the
|
|
// experience is identical regardless of which server is
|
|
// picked — the line above is the only output.
|
|
cmd += " > /dev/null 2>&1";
|
|
return std::system(cmd.c_str()) == 0 ? 0 : 1;
|
|
}
|
|
// wasi-cli wasm — needs a standalone runtime.
|
|
if (have("wasmtime")) {
|
|
return std::system(std::format("wasmtime {}", artifact.string()).c_str()) == 0 ? 0 : 1;
|
|
}
|
|
if (have("wasmer")) {
|
|
return std::system(std::format("wasmer run {}", artifact.string()).c_str()) == 0 ? 0 : 1;
|
|
}
|
|
std::println(std::cerr, "-r wasm: no wasm runtime found in PATH. Install wasmtime or wasmer, " "or call EnableWasiBrowserRuntime(cfg) in project.cpp for a browser build.");
|
|
return 1;
|
|
}
|
|
|
|
// Run from the artifact's own directory so relative file opens
|
|
// (shaders, assets copied alongside the exe via cfg.files) resolve
|
|
// against the bin dir rather than the user's cwd. We exit the
|
|
// process immediately after, so no cwd restore needed.
|
|
fs::current_path(dir);
|
|
return std::system(artifact.string().c_str()) == 0 ? 0 : 1;
|
|
}
|
|
|
|
return 0;
|
|
} catch (const std::exception& e) {
|
|
Progress::Clear();
|
|
std::println(std::cerr, "{}", e.what());
|
|
return 1;
|
|
}
|
|
}
|