Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git
commit 580bdab864a794f48c7a230c9723936b6187c899
parent f0871a8b3f357864011a6887c7da2b4183b4dc63
Author: sentomk <sentomk@proton.me>
Date:   Tue,  6 Oct 2026 22:58:42 +0800

feat: make the builder cross-platform

Diffstat:
Mkumo_builder.cpp | 368++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
1 file changed, 311 insertions(+), 57 deletions(-)

diff --git a/kumo_builder.cpp b/kumo_builder.cpp @@ -1,47 +1,104 @@ /// @file kumo_builder.cpp /// @brief The Kumo builder: the build script is itself a C++ program. /// +/// Supported platforms: macOS, Linux and Windows (clang++ must be on `PATH`). +/// The builder is built on the machine that uses it, so the host is also the +/// target; cross-compilation is not supported. +/// +/// Bootstrap (once, from the project root): /// @code -/// clang++ -std=c++20 kumo_builder.cpp -o kumoko +/// clang++ -std=c++20 kumo_builder.cpp -o kumoko # macOS, Linux +/// clang++ -std=c++20 kumo_builder.cpp -o kumoko.exe # Windows /// @endcode /// -/// Usage (always from the project root): +/// Usage (always from the project root; on Windows run `.\kumoko`): /// @code /// ./kumoko # incremental build /// ./kumoko run # incremental build, then run the executable /// ./kumoko clean # delete all build output /// @endcode /// +/// Platform-specific source files are marked by their name, see +/// is_built_here(). +/// /// @note There is no need to bootstrap again after editing this file: on the /// next run the builder notices it is out of date and recompiles itself. - +/// @warning The Windows code paths have not been run on a real Windows +/// machine yet. + +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include <windows.h> +#else #include <spawn.h> #include <sys/wait.h> #include <unistd.h> +#endif +#include <algorithm> +#include <cerrno> #include <cstdio> #include <cstdlib> #include <filesystem> #include <fstream> +#include <sstream> #include <string> +#include <system_error> #include <thread> #include <vector> +#if !defined(_WIN32) /// @brief The environment of the current process, provided by libc. /// /// Passed unchanged to every child process. extern char** environ; +#endif namespace fs = std::filesystem; +/// @brief A command as an argument list; element 0 is the program name. +/// +/// Commands are never joined into one string for a shell to parse, so paths +/// containing spaces or quotes need no escaping. using Cmd = std::vector<std::string>; /// @name Configuration /// Every build setting of the project lives here. /// @{ +/// @brief Operating systems the builder knows about. +enum class Platform { Mac, Linux, Windows }; + +/// @brief The platform being built for. +#if defined(__APPLE__) +static constexpr Platform HOST = Platform::Mac; +#elif defined(__linux__) +static constexpr Platform HOST = Platform::Linux; +#elif defined(_WIN32) +static constexpr Platform HOST = Platform::Windows; +#else +#error "kumo_builder supports only macOS, Linux and Windows" +#endif + +/// @brief File name extension of executables on this platform. +static constexpr const char* EXE_SUFFIX = + HOST == Platform::Windows ? ".exe" : ""; + static const char* const CXX = "clang++"; static const fs::path SELF_SRC = "kumo_builder.cpp"; + +/// @brief Path of the builder's own executable. +/// +/// A fixed name instead of `argv[0]`, because on Windows the user may type +/// `kumoko` without the `.exe` that the file actually has. +static const fs::path SELF_EXE = std::string("kumoko") + EXE_SUFFIX; + +/// @brief Where the running builder is moved to while it replaces itself. +/// +/// Windows refuses to overwrite a running executable but allows renaming it. +static const fs::path SELF_OLD_EXE = std::string("kumoko.old") + EXE_SUFFIX; + static const fs::path SRC_DIR = "src"; /// @brief Output root. @@ -50,10 +107,10 @@ static const fs::path SRC_DIR = "src"; /// @code /// build/obj/src/foo/bar.cpp.o object file (mirrors the source tree) /// build/obj/src/foo/bar.cpp.d list of headers that file depends on -/// build/kumo final executable +/// build/kumo final executable (kumo.exe on Windows) /// @endcode static const fs::path OUT_DIR = "build"; -static const fs::path EXE = OUT_DIR / "kumo"; +static const fs::path EXE = OUT_DIR / (std::string("kumo") + EXE_SUFFIX); /// @brief Flags passed to every compile command. static const Cmd CXX_FLAGS = { @@ -62,15 +119,62 @@ static const Cmd CXX_FLAGS = { "-Isrc", // allows includes relative to src/, e.g. #include "core/math.h" }; +/// @brief Extra compile flags that only some platforms need. +/// +/// On Windows the MSVC standard library must be told explicitly that +/// exceptions are off, otherwise its headers still contain `try` blocks. +static const Cmd PLATFORM_CXX_FLAGS = + HOST == Platform::Windows ? Cmd{"-D_HAS_EXCEPTIONS=0"} : Cmd{}; + /// @brief Extra flags for Objective-C++ (`.mm`) files only. /// /// ARC makes the compiler insert retain/release calls for Objective-C objects. static const Cmd OBJCXX_FLAGS = {"-fobjc-arc"}; /// @brief Flags passed to the link command. -static const Cmd LINK_FLAGS = { - "-framework", "Cocoa", "-framework", "Metal", "-framework", "QuartzCore", -}; +/// +/// Linux needs "-lX11" and Windows needs "-luser32", "-lgdi32" once the window +/// code for those platforms exists. +static const Cmd LINK_FLAGS = + HOST == Platform::Mac ? Cmd{"-framework", "Cocoa", "-framework", + "Metal", "-framework", "QuartzCore"} + : Cmd{}; + +/// @} + +/// @name Platform selection +/// Deciding which source files belong to the current platform. +/// @{ + +/// @brief Tells whether a source file is built on the current platform. +/// +/// Platform-specific code is marked by its name: +/// - `.mm` (Objective-C++) files build on macOS only; +/// - a `_mac`, `_linux` or `_win` suffix on the file name, before the +/// extension, restricts the file to that platform. +/// +/// Everything else builds everywhere. The suffix test is purely textual, so +/// avoid ending a portable file's name with one of them (e.g. `big_win.cpp`). +/// +/// @param src Path of the source file. +/// @return `true` if the file must be compiled on this platform. +static bool is_built_here(const fs::path& src) { + if (src.extension() == ".mm") return HOST == Platform::Mac; + + static const struct { + const char* suffix; + Platform platform; + } SUFFIXES[] = { + {"_mac", Platform::Mac}, + {"_linux", Platform::Linux}, + {"_win", Platform::Windows}, + }; + const std::string stem = src.stem().string(); + for (const auto& entry : SUFFIXES) { + if (stem.ends_with(entry.suffix)) return entry.platform == HOST; + } + return true; +} /// @} @@ -78,16 +182,93 @@ static const Cmd LINK_FLAGS = { /// Spawning children and limiting how many run at once. /// @{ -/// @brief Start a child process without waiting for it. +/// @brief Handle of a running child: a process id on POSIX, a `HANDLE` on +/// Windows. +#if defined(_WIN32) +using Process = HANDLE; +#else +using Process = pid_t; +#endif + +#if defined(_WIN32) +/// @brief Quotes one argument for a Windows command line. +/// +/// Windows passes a child its arguments as a single string, which the child's +/// runtime splits again. The rules: an argument containing a space, tab or +/// quote is wrapped in quotes; inside it a quote becomes a backslash-quote, and +/// backslashes directly before a quote (or before the closing quote) are +/// doubled. +/// +/// @param arg Raw argument. +/// @return The argument, quoted if necessary. +static std::string quote_arg(const std::string& arg) { + if (!arg.empty() && arg.find_first_of(" \t\"") == std::string::npos) { + return arg; + } + std::string out = "\""; + size_t backslashes = 0; // run of backslashes not yet written + for (char c : arg) { + if (c == '\\') { + ++backslashes; + continue; + } + if (c == '"') { + out.append(backslashes * 2 + 1, '\\'); // double them, then escape the " + } else { + out.append(backslashes, '\\'); // not before a quote: written as is + } + out += c; + backslashes = 0; + } + out.append(backslashes * 2, '\\'); // they now sit before the closing quote + out += '"'; + return out; +} +#endif + +/// @brief Starts a child process without waiting for it. /// /// Exits the builder if the process cannot be started. /// /// @param cmd Command to run; `cmd[0]` is looked up in `PATH`. -/// @return Process id of the child. -static pid_t spawn(const Cmd& cmd) { +/// @return Handle of the child. +static Process spawn(const Cmd& cmd) { + // Our own log lines may still sit in stdout's buffer. Flushing before the + // child starts keeps them ahead of the child's output even when stdout is a + // pipe or a file. + std::fflush(stdout); + +#if defined(_WIN32) + std::string line; + for (size_t i = 0; i < cmd.size(); ++i) { + if (i > 0) line += ' '; + line += quote_arg(cmd[i]); + } + + // Hand our standard streams to the child explicitly, so redirected output + // (a pipe or a file) is inherited as well. + STARTUPINFOA startup = {}; + startup.cb = sizeof(startup); + startup.dwFlags = STARTF_USESTDHANDLES; + startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE); + startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); + startup.hStdError = GetStdHandle(STD_ERROR_HANDLE); + + // With no application name, the first word of the command line is looked up + // in PATH and ".exe" is appended if needed. The command line buffer must be + // writable, which std::string::data() is. + PROCESS_INFORMATION info = {}; + if (!CreateProcessA(nullptr, line.data(), nullptr, nullptr, TRUE, 0, nullptr, + nullptr, &startup, &info)) { + std::fprintf(stderr, "failed to spawn %s (error %lu)\n", cmd[0].c_str(), + static_cast<unsigned long>(GetLastError())); + std::exit(EXIT_FAILURE); + } + CloseHandle(info.hThread); // only the process handle is needed + return info.hProcess; +#else // posix_spawnp wants a C-style argv: an array of char* ending in nullptr. std::vector<char*> argv; - for (const std::string& arg : cmd) { argv.push_back(const_cast<char*>(arg.c_str())); } @@ -102,15 +283,46 @@ static pid_t spawn(const Cmd& cmd) { std::exit(EXIT_FAILURE); } return pid; +#endif } -/// @brief Blocks until any one child process exits. +/// @brief Blocks until any one of the running children exits. /// -/// @return `true` if that child exited normally with status 0. -static bool wait_one() { +/// The child that finished is removed from @p running. +/// +/// @param running Children that were started and not yet waited for. +/// @return `true` if that child exited normally with status 0. `false` if it +/// failed or waiting itself failed; in the latter case @p running is +/// emptied, since the remaining children can no longer be tracked. +static bool wait_any(std::vector<Process>& running) { +#if defined(_WIN32) + DWORD index = WaitForMultipleObjects(static_cast<DWORD>(running.size()), + running.data(), FALSE, INFINITE); + // On success the result is WAIT_OBJECT_0 (== 0) plus the index of the handle + // that became signaled; anything else is an error. + if (index >= running.size()) { + running.clear(); + return false; + } + DWORD code = 1; + GetExitCodeProcess(running[index], &code); + CloseHandle(running[index]); + running.erase(running.begin() + index); + return code == 0; +#else int status = 0; - waitpid(-1, &status, 0); // -1 means "any child" + pid_t done; + do { + done = waitpid(-1, &status, 0); // -1 means "any child" + } while (done < 0 && errno == EINTR); // retry if a signal interrupted us + if (done < 0) { + running.clear(); + return false; + } + running.erase(std::remove(running.begin(), running.end(), done), + running.end()); return WIFEXITED(status) && WEXITSTATUS(status) == 0; +#endif } /// @brief Runs a batch of commands with bounded parallelism. @@ -125,18 +337,19 @@ static bool wait_one() { /// /// @param cmds Commands to run, started in order. /// @param max_jobs Maximum number of commands running at the same time. +/// Capped at 60, because Windows can wait on at most 64 +/// handles at once. /// @return `true` only if every command succeeded. static bool run_all(const std::vector<Cmd>& cmds, unsigned max_jobs) { - size_t next = 0; // index of the next command to start - unsigned running = 0; // number of children currently running + max_jobs = std::min(max_jobs, 60u); + size_t next = 0; // index of the next command to start + std::vector<Process> running; // children currently running bool ok = true; - while ((ok && next < cmds.size()) || running > 0) { - if (ok && next < cmds.size() && running < max_jobs) { - spawn(cmds[next++]); - running++; - } else { - if (!wait_one()) ok = false; - running--; + while ((ok && next < cmds.size()) || !running.empty()) { + if (ok && next < cmds.size() && running.size() < max_jobs) { + running.push_back(spawn(cmds[next++])); + } else if (!wait_any(running)) { + ok = false; } } return ok; @@ -157,10 +370,12 @@ static bool run(const Cmd& cmd) { return run_all({cmd}, 1); } /// @brief Reads a dependency file written by the compiler's `-MD` flag. /// /// The file uses Makefile syntax: `obj: dep dep dep`, where a backslash at the -/// end of a line continues the list on the next line. Only three rules matter: +/// end of a line continues the list on the next line. Only these rules matter: /// - the dependency list starts after the first `": "`; /// - dependencies are separated by whitespace or a line continuation; -/// - a space inside a path is escaped with a backslash. +/// - a space inside a path is escaped with a backslash; +/// - any other backslash is part of the path, which is how Windows paths such +/// as `C:\dir\file.h` appear. /// /// @param path Path of the `.d` file. /// @return Every dependency listed in the file; empty if it cannot be parsed. @@ -177,19 +392,25 @@ static std::vector<fs::path> read_depfile(const fs::path& path) { std::string token; // the path currently being accumulated // The loop deliberately runs one step past the end (i == size) and treats - // end-of file as a newline, so the last path is flushed as well. + // end-of-file as a newline, so the last path is flushed as well. for (i += 2; i <= text.size(); ++i) { char c = i < text.size() ? text[i] : '\n'; - if (c == '\\' && i + 1 < text.size() && text[i + 1] == ' ') { + char next = i + 1 < text.size() ? text[i + 1] : '\0'; + if (c == '\\' && next == ' ') { // An escaped space that belongs to the current path. token += ' '; ++i; - } else if (c == '\\' || c == ' ' || c == '\n' || c == '\r') { + } else if (c == '\\' && (next == '\n' || next == '\r')) { + // A line continuation: the current path ends here. The newline itself + // is a separator too and is handled by the next iteration. + if (!token.empty()) deps.push_back(token); + token.clear(); + } else if (c == ' ' || c == '\n' || c == '\r') { // A separator: the current path ends here. if (!token.empty()) deps.push_back(token); token.clear(); } else { - token += c; + token += c; // includes a backslash that is part of a Windows path } } return deps; @@ -247,7 +468,7 @@ static std::string json_escape(const std::string& s) { /// /// One object is written per file: /// @code{.json} -/// {"directory": "<cwd>", "file": "<source>", "arguments": ["<argv", ...]} +/// {"directory": "<cwd>", "file": "<source>", "arguments": ["<argv>", ...]} /// @endcode /// /// @param sources Every source file. @@ -259,7 +480,7 @@ static void write_compile_commands(const std::vector<fs::path>& sources, out << "[\n"; for (size_t i = 0; i < sources.size(); ++i) { out << " {\"directory\": \"" << dir << "\", \"file\": \"" - << json_escape(sources[i].string()) << "\", \"arguments\": ["; + << json_escape(sources[i].generic_string()) << "\", \"arguments\": ["; for (size_t j = 0; j < cmds[i].size(); j++) { out << (j ? ", " : "") << '"' << json_escape(cmds[i][j]) << '"'; } @@ -271,30 +492,61 @@ static void write_compile_commands(const std::vector<fs::path>& sources, /// @} -/// @} - /// @name Entry point /// @{ /// @brief Recompiles and restarts the builder if its source has changed. /// -/// If #SELF_SRC is newer than the running binary, it is recompiled and `execv` -/// replaces the current process with the new binary, which starts again from -/// main(). The new binary is always newer than the source, so this cannot -/// loop forever. +/// If #SELF_SRC is newer than the builder's executable, it is recompiled and +/// the new binary takes over with the same arguments. The new binary is always +/// newer than the source, so this cannot loop forever. /// -/// @param argv The argument vector of main(); `argv[0]` is the binary to -/// replace, and the whole vector is forwarded to the new process. -static void rebuild_self(char** argv) { - if (fs::last_write_time(SELF_SRC) <= fs::last_write_time(argv[0])) return; - - std::printf("[self] %s changed, rebuilding\n", SELF_SRC.c_str()); - if (!run({CXX, "-std=c++20", SELF_SRC.string(), "-o", argv[0]})) std::exit(1); +/// On macOS and Linux `execv` replaces the current process. Windows has no +/// equivalent, so the running executable is renamed out of the way, the new one +/// is built under the original name, and it is then run as a child whose exit +/// status becomes ours. +/// +/// @param argc Argument count of main(). +/// @param argv Argument vector of main(), forwarded to the new binary. +static void rebuild_self([[maybe_unused]] int argc, char** argv) { +#if defined(_WIN32) + // Left over from the previous self-rebuild; it could not be deleted then + // because it was still running. Failure to delete it is harmless. + std::error_code ignored; + fs::remove(SELF_OLD_EXE, ignored); +#endif + + if (fs::last_write_time(SELF_SRC) <= fs::last_write_time(SELF_EXE)) return; + + std::printf("[self] %s changed, rebuilding\n", + SELF_SRC.generic_string().c_str()); + const Cmd compile = {CXX, "-std=c++20", SELF_SRC.string(), "-o", + SELF_EXE.string()}; + +#if defined(_WIN32) + std::error_code ec; + fs::rename(SELF_EXE, SELF_OLD_EXE, ec); + if (ec) { + std::fprintf(stderr, "cannot move %s aside: %s\n", + SELF_EXE.string().c_str(), ec.message().c_str()); + std::exit(1); + } + if (!run(compile)) { + // Put the old builder back so the next run can try again. + fs::rename(SELF_OLD_EXE, SELF_EXE, ec); + std::exit(1); + } + Cmd relaunch(argv, argv + argc); + relaunch[0] = SELF_EXE.string(); + std::exit(run(relaunch) ? 0 : 1); +#else + if (!run(compile)) std::exit(1); - execv(argv[0], argv); + execv(SELF_EXE.c_str(), argv); // execv does not return on success; reaching this line means it failed. std::perror("execv"); std::exit(1); +#endif } /// @brief Builds the project. @@ -303,12 +555,7 @@ static void rebuild_self(char** argv) { /// @param argv `argv[1]` selects the mode: `build` (default), `run` or `clean`. /// @return 0 on success, 1 if compiling, linking or running failed. int main(int argc, char** argv) { - // stdout is fully buffered when it is not a terminal, which would make our - // log lines appear after the output of the child processes. Line buffering - // keeps them in order. - std::setvbuf(stdout, nullptr, _IOLBF, 0); - - rebuild_self(argv); + rebuild_self(argc, argv); std::string mode = argc > 1 ? argv[1] : "build"; if (mode == "clean") { @@ -316,7 +563,7 @@ int main(int argc, char** argv) { return 0; } - fs::file_time_type self_time = fs::last_write_time(argv[0]); + fs::file_time_type self_time = fs::last_write_time(SELF_EXE); // Step 1: scan the sources, build a compile command for each one, and pick // out the stale ones. @@ -329,6 +576,7 @@ int main(int argc, char** argv) { fs::recursive_directory_iterator(SRC_DIR)) { fs::path src = entry.path(); if (src.extension() != ".cpp" && src.extension() != ".mm") continue; + if (!is_built_here(src)) continue; // src/foo/bar.cpp -> build/obj/src/foo/bar.cpp.o // The full file name is kept and a suffix appended, so bar.cpp and @@ -340,6 +588,7 @@ int main(int argc, char** argv) { // -MD -MF <dep>: write the dependency list to dep while compiling. Cmd cmd = {CXX}; cmd.insert(cmd.end(), CXX_FLAGS.begin(), CXX_FLAGS.end()); + cmd.insert(cmd.end(), PLATFORM_CXX_FLAGS.begin(), PLATFORM_CXX_FLAGS.end()); if (src.extension() == ".mm") { cmd.insert(cmd.end(), OBJCXX_FLAGS.begin(), OBJCXX_FLAGS.end()); } @@ -347,7 +596,7 @@ int main(int argc, char** argv) { obj.string()}); if (needs_compile(obj, dep, self_time)) { - std::printf("[cc] %s\n", src.c_str()); + std::printf("[cc] %s\n", src.generic_string().c_str()); stale_cmds.push_back(cmd); } sources.push_back(src); @@ -371,7 +620,7 @@ int main(int argc, char** argv) { link_needed = true; } if (link_needed) { - std::printf("[link] %s\n", EXE.c_str()); + std::printf("[link] %s\n", EXE.generic_string().c_str()); Cmd link = {CXX}; for (const fs::path& obj : objects) link.push_back(obj.string()); link.insert(link.end(), LINK_FLAGS.begin(), LINK_FLAGS.end()); @@ -379,7 +628,12 @@ int main(int argc, char** argv) { if (!run(link)) return 1; } - if (mode == "run") return run({EXE.string()}) ? 0 : 1; + if (mode == "run") { + // Windows wants backslashes in the path of a program to start. + fs::path program = EXE; + program.make_preferred(); + return run({program.string()}) ? 0 : 1; + } return 0; }