Skip to content

Truly independent web browser

6.6 KB
Raw Blame
#!/usr/bin/env python3

# Copyright (c) 2026-present, the Ladybird developers.
#
# SPDX-License-Identifier: BSD-2-Clause

import argparse
import json
import re
import shlex
import subprocess

from pathlib import Path

HELPERS = (
    "AudioServer",
    "Compositor",
    "ImageDecoder",
    "MediaServer",
    "RequestServer",
    "VideoDecoderServer",
    "WebContent",
    "WebRTCClient",
)


def git_revision(source):
    # Source tarballs record their commit in a REVISION file, since they have no Git history of their own. They might be
    # unpacked inside another Git repository though, so the file takes precedence.
    revision_file = source / "REVISION"
    if revision_file.exists():
        revision = revision_file.read_text().strip()
        return (revision if re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", revision) else "unknown"), "unknown"

    try:
        revision = subprocess.check_output(
            ["git", "-C", str(source), "rev-parse", "--verify", "HEAD"], stderr=subprocess.DEVNULL, text=True
        ).strip()
        if not re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", revision):
            return "unknown", "unknown"
        result = subprocess.run(
            ["git", "-C", str(source), "diff-index", "--quiet", "HEAD", "--"],
            check=False,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
        return revision, {0: "clean", 1: "modified"}.get(result.returncode, "unknown")
    except (OSError, subprocess.CalledProcessError):
        return "unknown", "unknown"


def compiler_flags(command):
    # Never copy include/output paths, response files, arbitrary string defines,
    # or plugin arguments. Keep code-generation flags and numeric build defines.
    flags = []
    arguments = iter(shlex.split(command))
    for argument in arguments:
        if argument in (
            "-I",
            "-isystem",
            "-iquote",
            "-include",
            "-isysroot",
            "-o",
            "-MF",
            "-MT",
            "-Xclang",
            "-Xlinker",
        ):
            next(arguments, None)
            continue
        if argument in ("-arch", "-target"):
            value = next(arguments, "")
            if re.fullmatch(r"[a-zA-Z0-9_.-]+", value):
                flags.extend((argument, value))
            continue
        if (
            re.fullmatch(r"-D[A-Z][A-Z0-9_]*(=[0-9]+)?", argument)
            or re.fullmatch(r"-(O[0-3sgz]|g[0-3]?|ggnu-pubnames|std=[a-z+0-9]+|[fWm][a-zA-Z0-9-]+)", argument)
            or re.fullmatch(r"-[fm][a-zA-Z0-9-]+=(native|hidden|default|off|on|fast|zero|pattern|[0-9.]+)", argument)
            or re.fullmatch(r"-fsanitize=[a-z,-]+", argument)
        ):
            flags.append(argument)
    return " ".join(flags) or "unavailable"


def build_options(cache):
    options = []
    for line in cache.splitlines():
        match = re.fullmatch(r"((?:ENABLE_|USE_|BUILD_|LADYBIRD_)[A-Z0-9_]+):BOOL=(ON|OFF|TRUE|FALSE|0|1)", line)
        if match:
            options.append(f"{match[1]}={match[2]}")
    return "; ".join(sorted(options)) or "unavailable"


def generate(source, build, compiler):
    revision, state = git_revision(source)
    options = build_options((build / "CMakeCache.txt").read_text())
    commands_path = build / "compile_commands.json"
    commands = json.loads(commands_path.read_text()) if commands_path.exists() else []

    result = f"""// Generated by Meta/generate-build-information.py.

#pragma once

#include <AK/StringBuilder.h>
#include <AK/StringView.h>
#include <LibCore/BrowserVersion.h>
#include <LibWebCommon/Loader/UserAgent.h>
#include <LibWebView/ProcessType.h>

namespace WebView {{

constexpr inline auto LADYBIRD_COMMIT = {json.dumps(revision)}sv;

inline void append_build_information_for_process(StringBuilder& builder, ProcessType type)
{{
    builder.appendff("Version: {{}}\\nPlatform: {{}}\\nArchitecture: {{}}\\n", BROWSER_VERSION, OS_STRING, CPU_STRING);
    builder.appendff("Build configuration: {{}}\\n", BROWSER_BUILD_CONFIGURATION);
    builder.appendff("Git commit: {{}}\\n", LADYBIRD_COMMIT);
    builder.appendff("Tracked source state: {{}}\\n", {json.dumps(state)}sv);
    builder.appendff("C++ compiler: {{}}\\n", {json.dumps(compiler)}sv);
    builder.appendff("Build options: {{}}\\n", {json.dumps(options)}sv);

    switch (type) {{
    case ProcessType::Browser:
    case ProcessType::UI:
    case ProcessType::Hub:
        break;
"""

    for helper in HELPERS:
        entry = next(
            (entry for entry in commands if Path(entry["file"]) == source / "Services" / helper / "main.cpp"), None
        )

        flags = compiler_flags(entry["command"]) if entry else "unavailable"

        result += f"""    case ProcessType::{helper}:
        builder.appendff("C++ flags: {{}}\\n", {json.dumps(flags)}sv);
"""

        sdk = re.search(r"/MacOSX([0-9.]+)\.sdk", entry["command"]) if entry else None
        if sdk:
            result += f'        builder.appendff("macOS SDK: {{}}\\n", {json.dumps(sdk[1])}sv);\n'

        result += "        break;\n"

    result += """    }
}

}
"""
    return result


def escape_depfile_path(path):
    return (
        str(path).replace("$", "$$").replace("\\", "\\\\").replace(" ", "\\ ").replace("#", "\\#").replace(":", "\\:")
    )


def write_depfile(source, output, target):
    try:
        tracked_files = subprocess.check_output(
            ["git", "-C", str(source), "ls-files", "-z"], stderr=subprocess.DEVNULL
        ).split(b"\0")
    except (OSError, subprocess.CalledProcessError):
        tracked_files = []

    dependencies = (
        path
        for tracked_file in tracked_files
        if tracked_file
        for path in [(source / Path(tracked_file.decode())).resolve()]
    )

    escaped_dependencies = " ".join(escape_depfile_path(path) for path in dependencies)
    output.write_text(f"{escape_depfile_path(target)}: {escaped_dependencies}\n")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("source", type=Path)
    parser.add_argument("build", type=Path)
    parser.add_argument("output", type=Path)
    parser.add_argument("compiler")
    parser.add_argument("--depfile", type=Path, required=True)
    parser.add_argument("--stamp", type=Path, required=True)
    args = parser.parse_args()

    if not re.fullmatch(r"[a-zA-Z0-9_. +()-]+", args.compiler):
        raise ValueError("Invalid compiler identity")

    source = args.source.resolve()
    contents = generate(source, args.build.resolve(), args.compiler)

    if not args.output.exists() or args.output.read_text() != contents:
        args.output.write_text(contents)

    write_depfile(source, args.depfile, args.stamp)


if __name__ == "__main__":
    main()