Skip to content

Truly independent web browser

Meta+CI: Package the source code of the LGPL modules of the Flatpak

Jelle Raaijmakers871b8d215e87
diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.yml
index 6bcd5cbb0f7..73a9be55788 100644
--- a/.github/workflows/build-release.yml
+++ b/.github/workflows/build-release.yml
@@ -304,6 +304,7 @@ jobs:
env:
BUNDLE: ladybird-${{ inputs.version && format('{0}-', inputs.version) }}Linux-${{ matrix.arch }}.flatpak
DEBUG_BUNDLE: ladybird-${{ inputs.version && format('{0}-', inputs.version) }}Linux-${{ matrix.arch }}-debug.flatpak
+ THIRD_PARTY_SOURCES: ladybird-${{ inputs.version }}-Flatpak-${{ matrix.arch }}-third-party-sources.tar
steps:
- name: Download the source
@@ -355,6 +356,13 @@ jobs:
cache: false
upload-artifact: false
+ # release-tools publishes the source archive of every LGPL module with the release.
+ - name: Package the source code of the LGPL libraries
+ if: ${{ inputs.version != '' }}
+ run: |
+ python3 Meta/generate-licenses.py --flatpak-manifest Meta/CMake/flatpak/org.ladybird.Ladybird.json \
+ --third-party-sources "$THIRD_PARTY_SOURCES"
+
- name: Attest
if: ${{ inputs.version != '' }}
uses: actions/attest@v4
@@ -362,6 +370,7 @@ jobs:
subject-path: |
${{ env.BUNDLE }}
${{ env.DEBUG_BUNDLE }}
+ ${{ env.THIRD_PARTY_SOURCES }}
- name: Upload
uses: actions/upload-artifact@v7
@@ -376,3 +385,11 @@ jobs:
path: ${{ env.DEBUG_BUNDLE }}
archive: false
if-no-files-found: error
+
+ - name: Upload the source code of the LGPL libraries
+ if: ${{ inputs.version != '' }}
+ uses: actions/upload-artifact@v7
+ with:
+ path: ${{ env.THIRD_PARTY_SOURCES }}
+ archive: false
+ if-no-files-found: error
diff --git a/Meta/CMake/flatpak/org.ladybird.Ladybird.json b/Meta/CMake/flatpak/org.ladybird.Ladybird.json
index 8c37d0b94af..95810383cbd 100644
--- a/Meta/CMake/flatpak/org.ladybird.Ladybird.json
+++ b/Meta/CMake/flatpak/org.ladybird.Ladybird.json
@@ -474,6 +474,7 @@
{
"type": "git",
"url": "https://github.com/davea42/libdwarf-code.git",
+ "commit": "1c267616a4c8dc46b3380f0be4296ff8767bdfbb",
"tag": "v2.3.3"
}
],
diff --git a/Meta/Linters/check_flatpak.py b/Meta/Linters/check_flatpak.py
index 40dc56151e6..d2220010374 100755
--- a/Meta/Linters/check_flatpak.py
+++ b/Meta/Linters/check_flatpak.py
@@ -22,6 +22,7 @@ VCPKG_OVERLAYS_PORTS = LADYBIRD_SOURCE_DIR / "Meta" / "CMake" / "vcpkg" / "overl
VCPKG_REPO = LADYBIRD_SOURCE_DIR / "Build" / "vcpkg-release"
VCPKG_BASELINE_URL = "https://raw.githubusercontent.com/microsoft/vcpkg/{}/versions/baseline.json"
FLATPAK_MANIFEST = LADYBIRD_SOURCE_DIR / "Meta" / "CMake" / "flatpak" / "org.ladybird.Ladybird.json"
+LGPL_LIBRARIES = LADYBIRD_SOURCE_DIR / "Meta" / "CMake" / "lgpl-libraries.txt"
CARGO_LOCK = LADYBIRD_SOURCE_DIR / "Cargo.lock"
CARGO_SOURCES = LADYBIRD_SOURCE_DIR / "Meta" / "CMake" / "flatpak" / "cargo-sources.json"
GENERATE_CARGO_SOURCES = LADYBIRD_SOURCE_DIR / "Meta" / "CMake" / "flatpak" / "generate-cargo-sources.py"
@@ -232,6 +233,39 @@ def check_vcpkg_vs_flatpak_versioning(vcpkg_repo: Path):
return mismatch_found
+# The build options that make a library shared, by the build systems of the modules, and those that make it static.
+SHARED_BUILD_OPTIONS = ("--enable-shared", "-DBUILD_SHARED_LIBS=ON", "-DBUILD_SHARED=ON", "-Ddefault_library=shared")
+STATIC_BUILD_OPTIONS = ("--disable-shared", "--enable-static", "-DBUILD_SHARED_LIBS=OFF", "-DBUILD_SHARED=OFF")
+
+
+def check_lgpl_modules_build_shared_libraries():
+ """Every module under the LGPL has to build a shared library, so that the library can be relinked."""
+ with open(LGPL_LIBRARIES) as input:
+ lgpl_libraries = {line.strip() for line in input if line.strip() and not line.startswith("#")}
+ with open(FLATPAK_MANIFEST) as input:
+ modules = [module for module in json.load(input)["modules"] if module["name"] in lgpl_libraries]
+
+ failed = False
+ for module in modules:
+ options = " ".join([*module.get("config-opts", []), *module.get("build-commands", [])]).split()
+ # A CMake cache entry may name its type, as in -DBUILD_SHARED:BOOL=ON.
+ options = [re.sub(r"^(-D[^:=]+):[A-Za-z]+=", r"\1=", option) for option in options]
+ # Autotools-style builds make static libraries too unless told not to.
+ static_by_default = "--enable-shared" in options and "--disable-static" not in options
+ if (
+ static_by_default
+ or any(option in STATIC_BUILD_OPTIONS for option in options)
+ or not any(option in SHARED_BUILD_OPTIONS for option in options)
+ ):
+ failed = True
+ print(
+ f"The Flatpak module {module['name']} is under the LGPL, so it has to build a shared library only, with "
+ f"one of {', '.join(SHARED_BUILD_OPTIONS)} (--enable-shared together with --disable-static) and none "
+ f"of {', '.join(STATIC_BUILD_OPTIONS)}"
+ )
+ return failed
+
+
def check_cargo_sources_match_cargo_lock():
return subprocess.run([sys.executable, GENERATE_CARGO_SOURCES, "--check"]).returncode != 0
@@ -239,7 +273,9 @@ def check_cargo_sources_match_cargo_lock():
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--vcpkg-repo", required=False, type=Path, default=VCPKG_REPO)
- parser.add_argument("file_list", type=Path, nargs="*", default=[VCPKG, CARGO_LOCK])
+ parser.add_argument(
+ "file_list", type=Path, nargs="*", default=[VCPKG, FLATPAK_MANIFEST, LGPL_LIBRARIES, CARGO_LOCK]
+ )
args = parser.parse_args()
vcpkg_repo = args.vcpkg_repo.resolve()
@@ -250,6 +286,9 @@ def main():
if VCPKG in file_list or FLATPAK_MANIFEST in file_list:
did_fail = check_vcpkg_vs_flatpak_versioning(vcpkg_repo)
+ if FLATPAK_MANIFEST in file_list or LGPL_LIBRARIES in file_list:
+ did_fail |= check_lgpl_modules_build_shared_libraries()
+
if any(path in requested for path in (CARGO_LOCK, CARGO_SOURCES, GENERATE_CARGO_SOURCES)):
did_fail |= check_cargo_sources_match_cargo_lock()
diff --git a/Meta/generate-licenses.py b/Meta/generate-licenses.py
index d18b8b96cdb..12fdd5b5349 100755
--- a/Meta/generate-licenses.py
+++ b/Meta/generate-licenses.py
@@ -409,10 +409,138 @@ def package_third_party_sources(args: argparse.Namespace) -> None:
archives.append(work_dir / source.archive_name())
print(f"Packaged the source of {source.port.name} {source.port.version} as {source.archive_name()}")
- args.third_party_sources.parent.mkdir(parents=True, exist_ok=True)
- with tarfile.open(args.third_party_sources, "w", format=tarfile.USTAR_FORMAT) as bundle:
- for archive in archives:
- bundle.add(archive, arcname=archive.name)
+ write_bundle(args.third_party_sources, archives)
+
+
+def write_bundle(path: pathlib.Path, archives: list[pathlib.Path]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with tarfile.open(path, "w", format=tarfile.USTAR_FORMAT) as bundle:
+ for archive in archives:
+ bundle.add(archive, arcname=archive.name)
+
+
+def flatpak_lgpl_modules(manifest_path: pathlib.Path, source_dir: pathlib.Path) -> list[dict[str, Any]]:
+ lgpl_libraries = read_lgpl_libraries(source_dir)
+ found = []
+ pending = list(json.loads(read_text(manifest_path))["modules"])
+ while pending:
+ module = pending.pop(0)
+ if isinstance(module, str):
+ raise RuntimeError(f"The Flatpak manifest includes the module file {module}, which this script cannot read")
+ pending += module.get("modules", [])
+ if module["name"] in lgpl_libraries:
+ found.append(module)
+ return found
+
+
+def flatpak_patch(module: dict[str, Any], source: dict[str, Any], manifest_dir: pathlib.Path) -> pathlib.Path:
+ if "path" not in source:
+ raise RuntimeError(f"A patch of the Flatpak module {module['name']} has no single path")
+ return manifest_dir / source["path"]
+
+
+# Like the archive of a vcpkg port, the name says what the archive holds: the module that builds the library, which
+# pins the commits and digests of its sources, and the patches that it applies.
+def flatpak_archive_name(module: dict[str, Any], manifest_dir: pathlib.Path) -> str:
+ lines = [f"module {json.dumps(module, sort_keys=True)}"]
+ for source in module["sources"]:
+ if source.get("type") == "patch":
+ path = flatpak_patch(module, source, manifest_dir)
+ lines.append(f"patch {source['path']} {hashlib.sha256(path.read_bytes()).hexdigest()}")
+ digest = hashlib.sha256("\n".join(lines).encode()).hexdigest()
+ git = next((source for source in module["sources"] if source.get("type") == "git"), {})
+ version = git.get("tag") or git.get("commit", "")[:12] or "source"
+ return UNSAFE_NAME_CHARACTERS.sub("_", f"{module['name']}-{version}-{digest[:12]}") + ".tar"
+
+
+def fetch_git_source(source: dict[str, Any], work_dir: pathlib.Path) -> tuple[str, bytes]:
+ reference = source.get("commit") or f"refs/tags/{source['tag']}"
+ repository = work_dir / "git"
+ subprocess.run(["git", "init", "--quiet", "--bare", str(repository)], check=True)
+ subprocess.run(
+ ["git", "-C", str(repository), "fetch", "--quiet", "--depth=1", source["url"], reference], check=True
+ )
+ commit = subprocess.run(
+ ["git", "-C", str(repository), "rev-parse", "FETCH_HEAD^{commit}"],
+ check=True,
+ stdout=subprocess.PIPE,
+ text=True,
+ ).stdout.strip()
+ if source.get("commit") and commit != source["commit"]:
+ raise RuntimeError(f"{source['url']} has {commit} at {reference}, not {source['commit']}")
+ name = source["url"].rstrip("/").removesuffix(".git").rpartition("/")[2]
+ root = f"{name}-{source.get('tag') or commit}"
+ archive = subprocess.run(
+ ["git", "-C", str(repository), "archive", "--format=tar.gz", f"--prefix={root}/", commit],
+ check=True,
+ stdout=subprocess.PIPE,
+ ).stdout
+ shutil.rmtree(repository)
+ return f"{root}.tar.gz", archive
+
+
+def fetch_archive_source(source: dict[str, Any]) -> tuple[str, bytes]:
+ with urllib.request.urlopen(source["url"], timeout=60) as response:
+ data = response.read()
+ if hashlib.sha256(data).hexdigest() != source.get("sha256"):
+ raise RuntimeError(f"{source['url']} does not have the SHA-256 that the Flatpak manifest names")
+ return source.get("dest-filename") or urllib.parse.urlparse(source["url"]).path.rpartition("/")[2], data
+
+
+def write_flatpak_module_archive(
+ module: dict[str, Any], manifest_dir: pathlib.Path, work_dir: pathlib.Path, destination: pathlib.Path
+) -> None:
+ files: dict[str, bytes] = {}
+ listing = []
+ for source in module["sources"]:
+ kind = source.get("type")
+ if kind == "git":
+ name, data = fetch_git_source(source, work_dir)
+ listing.append(f" {name}: the tree of {source['url']} at {source.get('tag') or source['commit']}")
+ elif kind == "archive":
+ name, data = fetch_archive_source(source)
+ listing.append(f" {name}: {source['url']}")
+ elif kind == "patch":
+ path = flatpak_patch(module, source, manifest_dir)
+ name, data = f"patches/{path.name}", path.read_bytes()
+ else:
+ raise RuntimeError(
+ f"The Flatpak module {module['name']} has a {kind} source, which this script cannot read"
+ )
+ if name in files or UNSAFE_NAME_CHARACTERS.search(name.removeprefix("patches/")):
+ raise RuntimeError(f"The Flatpak module {module['name']} names the source {name!r} unsafely or twice")
+ files[name] = data
+
+ root = destination.name.removesuffix(".tar")
+ readme = "\n".join(
+ [
+ f"The source code of {module['name']}, as the Ladybird Flatpak builds it with flatpak-builder.",
+ "",
+ "flatpak-module.json is the module of the Flatpak manifest that builds the library, and patches/ holds",
+ "our patches, which it applies in order. The other files are the sources that it fetches:",
+ "",
+ *listing,
+ "",
+ ]
+ )
+ with tarfile.open(destination, "w", format=tarfile.USTAR_FORMAT) as archive:
+ add_to_archive(archive, f"{root}/README", readme.encode())
+ add_to_archive(archive, f"{root}/flatpak-module.json", (json.dumps(module, indent=4) + "\n").encode())
+ for name, data in sorted(files.items()):
+ add_to_archive(archive, f"{root}/{name}", data)
+
+
+def package_flatpak_third_party_sources(args: argparse.Namespace) -> None:
+ manifest_dir = args.flatpak_manifest.resolve().parent
+ with tempfile.TemporaryDirectory() as work:
+ work_dir = pathlib.Path(work)
+ archives = []
+ for module in flatpak_lgpl_modules(args.flatpak_manifest, args.source_dir):
+ name = flatpak_archive_name(module, manifest_dir)
+ write_flatpak_module_archive(module, manifest_dir, work_dir, work_dir / name)
+ archives.append(work_dir / name)
+ print(f"Packaged the source of {module['name']} as {name}")
+ write_bundle(args.third_party_sources, archives)
def cargo_metadata(cargo: str, source_dir: pathlib.Path, rust_target: Optional[str], offline: bool) -> dict[str, Any]:
@@ -588,11 +716,19 @@ def main() -> int:
help="instead of the licenses, write an archive with the source archive of each LGPL port to this path",
)
parser.add_argument("--vcpkg-root", type=pathlib.Path, default=os.environ.get("VCPKG_ROOT"))
+ parser.add_argument(
+ "--flatpak-manifest",
+ type=pathlib.Path,
+ help="with --third-party-sources, package the LGPL modules of this Flatpak manifest instead of vcpkg ports",
+ )
args = parser.parse_args()
if args.third_party_sources:
try:
- package_third_party_sources(args)
+ if args.flatpak_manifest:
+ package_flatpak_third_party_sources(args)
+ else:
+ package_third_party_sources(args)
except (RuntimeError, OSError, subprocess.CalledProcessError) as error:
print(f"error: {error}", file=sys.stderr)
return 1