Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,53 @@
|
||||
# Dever 发行构建
|
||||
|
||||
## 单文件 dever
|
||||
|
||||
Linux x86_64 的发行文件为原生可执行文件 `dever`。复制到目标机器并赋予执行权限后,即可用 `dever run` 运行项目,用 `dever build` 生成应用程序。开发者无需另装 Rust、Cargo 或链接器。当前发行在 Debian 13(glibc 2.41)上验证。构建使用 Linux 的 `/proc` 和可执行的内存文件,需有可写、可执行的临时目录。
|
||||
|
||||
```sh
|
||||
chmod +x dever
|
||||
./dever new hello
|
||||
./dever run hello -- hello.greeting.greet '{"name":"Dever"}'
|
||||
./dever build hello --output ./hello-app
|
||||
./hello-app hello.greeting.greet '{"name":"Dever"}'
|
||||
```
|
||||
|
||||
发布者在 Debian 13 x86_64 开发容器中用固定工具链构建。输出目录须已存在,输出文件须是新路径:
|
||||
|
||||
```sh
|
||||
export CARGO_TARGET_DIR="$PWD/target/next-cargo"
|
||||
cargo +1.95.0 build --manifest-path rust/Cargo.toml --locked --offline --release --bin dever
|
||||
mkdir target/linux-x86_64
|
||||
python3 build/local.py --compiler "$CARGO_TARGET_DIR/release/dever" \
|
||||
--output target/linux-x86_64/dever > target/linux-x86_64/dever.sha256
|
||||
(cd target/linux-x86_64 && sha256sum -c dever.sha256)
|
||||
```
|
||||
|
||||
Cargo 只编译 CLI;上面的 Python 命令生成可以单独分发的成品。它预编译运行库,并把标准库、编译和链接资源放入 `dever`。每次原生编译把所需资源加载到匿名内存文件,未安装工具链的机器也能构建普通 Dever 应用。前端构建脚本使用项目配置的工具。开发 Go、npm、Python Worker 时,请使用下文的平台工具包及其 SDK。跨架构构建也使用平台工具包。随文件的第三方许可声明可用 `dever --licenses` 查看;发布时同时按所带组件的条款提供相应源码或源码获取方式。
|
||||
|
||||
## 平台开发工具包
|
||||
|
||||
平台维护及交叉构建所用工具包包含源码、SDK 和完整的离线工具链。它与面向应用开发者的 `dever` 是不同的发行物。
|
||||
|
||||
在现有 Debian 13 x86_64 开发容器内组装,复用官方 Rust 1.95.0、Cargo vendor 和 Debian GCC/binutils。不会安装或替换系统 dever,不写用户 Cargo 配置。
|
||||
|
||||
```sh
|
||||
python3 build/development.py --compiler target/next-cargo/release/dever \
|
||||
--work target/release-stage --output target/dever-0.0.2-linux-x86_64.tar.xz
|
||||
```
|
||||
|
||||
work、归档及校验文件必须是新路径。包含编译器、运行库源码、标准库、SDK、Skill、离线 Cargo 依赖、Rust 和 C 编译工具及其许可证。不会复制用户 Cargo home、项目配置、业务数据或 SDK 开发依赖目录。编译器自身没有新增开放许可声明。
|
||||
|
||||
解压归档后从 `dever/bin/dever` 启动。启动器从自身位置设置 `DEVER_ROOT`,工具包可整体移动。目标环境需提供 Linux x86_64、glibc 2.41 以及 shell 和常规系统工具。
|
||||
|
||||
manifest.json 列出交付文件的相对路径、长度、SHA-256 和执行权限;归档另附 SHA-256。Cargo 保留原始 vendor 校验与依赖许可证,Rust 和 Debian 工具许可证在 toolchain/licenses。构建缓存只在首次实际构建时产生,不打入归档。
|
||||
|
||||
外部 Python/npm/Go 依赖按 `dever lib install` 准备原生锁及缓存;应用 build 离线使用已准备资源,解释器和动态依赖内嵌在应用产物中。需要交付这些工具和依赖时,先在独立 DEVER_HOME 中准备实际项目,再给组装命令增加 `--external-home <该目录>`。仅打包固定官方工具与 Go/npm/uv 下载缓存,不复制配置、日志、业务源码和构建缓存;缓存内的符号链接不得越出准备目录。第三方依赖的原始许可证随缓存保留,发布者仍须核对实际依赖的分发条件。
|
||||
|
||||
应用源码与 dever.lock、原生锁文件可以直接搬移;target 中的并发锁由构建建立,无需复制历史 target。三生态离线验证从不带 target 的源码副本构建,确保这一行为。
|
||||
|
||||
带外部附件的启动器在未设置 DEVER_HOME 时使用包内 external 目录;显式设置时使用指定目录,不混用两套缓存。离线能力覆盖已准备的原生锁,不能离线获取未打包的版本。验证入口为 `test/release.py` 和 `test/release_external.py`,后者用空 HOME、不可达代理和搬移后的工具链构建三种生态,并在移走项目源码后运行真实第三方处理函数。aarch64 发行和真实目标执行仍需对应环境验收。
|
||||
|
||||
交叉构建附件由组装时显式选择:增加 --aarch64-native <Debian 13 交叉 GCC 解包根> 与 --aarch64-std <Rust 1.95.0 的 rustlib/aarch64-unknown-linux-gnu>。两者必须同时提供;只纳入官方目标标准库、交叉 GCC/binutils、目标头文件/库及许可证,不复制旧 Dever 运行库或测试 QEMU。随包 Cargo 使用包内目标链接器,搬移后无需系统交叉工具。编译目标用 dever build 的 --target linux-aarch64,外部 Worker 的目标限制见 LANGUAGE。
|
||||
|
||||
可用 test/release.py 的 --aarch64-runner <QEMU 路径> 验证搬移后的离线交叉构建与仿真执行;这项结果必须标作 QEMU,不能算 aarch64 实机或 aarch64 安装包验收。
|
||||
@@ -0,0 +1,301 @@
|
||||
#!/usr/bin/env python3
|
||||
"""在 Debian 13 开发容器内组装 Linux x86_64 完整离线开发包。"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tomllib
|
||||
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[1]
|
||||
TRIPLE = "x86_64-unknown-linux-gnu"
|
||||
PACKAGES = (
|
||||
"gcc-14-x86-64-linux-gnu", "cpp-14-x86-64-linux-gnu", "libgcc-14-dev",
|
||||
"libc6-dev", "linux-libc-dev", "binutils-x86-64-linux-gnu", "libc6", "libgcc-s1",
|
||||
)
|
||||
|
||||
|
||||
def native_input(path):
|
||||
"""只保留原生 C 构建所需工具;Rust LTO 使用包内 LLVM,不需要 GCC LTO。"""
|
||||
name = str(path)
|
||||
if name.startswith("/usr/include/"):
|
||||
return True
|
||||
if path.parent == Path("/usr/bin"):
|
||||
return path.name in {
|
||||
"x86_64-linux-gnu-gcc-14", "x86_64-linux-gnu-as",
|
||||
"x86_64-linux-gnu-ld", "x86_64-linux-gnu-ar", "x86_64-linux-gnu-ranlib",
|
||||
}
|
||||
if name.startswith("/usr/libexec/gcc/"):
|
||||
return path.name in {"cc1", "collect2", "liblto_plugin.so", "lto-wrapper"}
|
||||
if name.startswith("/usr/lib/gcc/"):
|
||||
return "/include/" in name or path.name in {
|
||||
"libgcc.a", "libgcc_eh.a", "libgcc_s.so", "crtbegin.o", "crtbeginS.o",
|
||||
"crtbeginT.o", "crtend.o", "crtendS.o",
|
||||
"liblto_plugin.so",
|
||||
}
|
||||
return path.parent in {Path("/usr/lib/x86_64-linux-gnu"), Path("/usr/lib64")}
|
||||
|
||||
|
||||
def output(*arguments, **options):
|
||||
return subprocess.check_output(arguments, text=True, **options).strip()
|
||||
|
||||
|
||||
def digest(path):
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def copy(source, destination):
|
||||
"""只解引用作者明确选定的工具文件,不复制 Cargo home 或用户配置。"""
|
||||
if source.is_dir():
|
||||
shutil.copytree(source, destination, dirs_exist_ok=True)
|
||||
else:
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source, destination)
|
||||
destination.chmod(0o755 if os.access(source, os.X_OK) else 0o644)
|
||||
|
||||
|
||||
def script(path, body):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text('#!/bin/sh\nset -eu\ntools=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)\n' + body)
|
||||
path.chmod(0o755)
|
||||
|
||||
|
||||
def native_tools(tools):
|
||||
"""保留 Debian 工具的相对安装布局;glibc 只进链接 sysroot,不覆盖宿主加载器。"""
|
||||
base = {str(Path(path).resolve()) for path in output("dpkg-query", "-L", "libc6").splitlines()}
|
||||
packages = set(PACKAGES)
|
||||
executables = []
|
||||
for package in PACKAGES:
|
||||
for name in output("dpkg-query", "-L", package).splitlines():
|
||||
path = Path(name)
|
||||
if not path.is_file() or not native_input(path):
|
||||
continue
|
||||
copy(path, tools / "native" / path.relative_to("/"))
|
||||
# Debian 的链接脚本使用 /lib;发行包展开 usrmerge 别名,不改写官方库文件。
|
||||
if package == "libc6":
|
||||
copy(path, tools / "native" / path.relative_to("/usr"))
|
||||
if os.access(path, os.X_OK):
|
||||
with path.open("rb") as stream:
|
||||
if stream.read(4) == b"\x7fELF":
|
||||
executables.append(path)
|
||||
for name in ("as", "ld", "ar"):
|
||||
copy(Path(f"/usr/bin/x86_64-linux-gnu-{name}"), tools / "native/usr/bin" / name)
|
||||
libraries = set()
|
||||
for executable in executables:
|
||||
listing = subprocess.run(["ldd", str(executable)], text=True, capture_output=True)
|
||||
if listing.returncode and "not a dynamic executable" not in listing.stderr + listing.stdout:
|
||||
raise RuntimeError(f"ldd {executable}: {listing.stderr}{listing.stdout}")
|
||||
for line in listing.stdout.splitlines():
|
||||
if "=> not found" in line:
|
||||
raise RuntimeError(line)
|
||||
fields = line.split()
|
||||
if "=>" in fields and fields[2].startswith("/"):
|
||||
library = Path(fields[2])
|
||||
if str(library.resolve()) not in base:
|
||||
libraries.add(library)
|
||||
for library in sorted(libraries):
|
||||
copy(library, tools / "lib" / library.name)
|
||||
owner = output("dpkg-query", "-S", str(library.resolve())).splitlines()[0].split(": ", 1)[0]
|
||||
packages.add(owner)
|
||||
copy(Path("/usr/lib/x86_64-linux-gnu/libgcc_s.so.1"), tools / "lib/libgcc_s.so.1")
|
||||
packages.add("libgcc-s1")
|
||||
for package in sorted(packages):
|
||||
name = package.split(":", 1)[0]
|
||||
copy(Path("/usr/share/doc") / name / "copyright", tools / "licenses" / name / "copyright")
|
||||
copy(Path("/usr/share/common-licenses"), tools / "licenses/common")
|
||||
(tools / "native-packages.txt").write_text(output("dpkg-query", "-W", *sorted(packages)) + "\n")
|
||||
script(tools / "bin/cc", '''export LD_LIBRARY_PATH="$tools/lib"
|
||||
exec "$tools/native/usr/bin/x86_64-linux-gnu-gcc-14" \\
|
||||
--sysroot="$tools/native" \\
|
||||
-B"$tools/native/usr/lib/gcc/x86_64-linux-gnu/14/" \\
|
||||
-B"$tools/native/usr/libexec/gcc/x86_64-linux-gnu/14/" \\
|
||||
-B"$tools/native/usr/bin/" \\
|
||||
-B"$tools/native/usr/lib/x86_64-linux-gnu/" "$@"
|
||||
''')
|
||||
|
||||
|
||||
def rust_tools(tools, version, vendor):
|
||||
rust = Path(output("rustc", f"+{version}", "--print", "sysroot"))
|
||||
if f"host: {TRIPLE}" not in output("rustc", f"+{version}", "-vV"):
|
||||
raise RuntimeError(f"this package requires the official {TRIPLE} toolchain")
|
||||
for name in ("cargo", "rustc"):
|
||||
copy(rust / "bin" / name, tools / "rust/bin" / name)
|
||||
for library in (rust / "lib").glob("*.so*"):
|
||||
if not library.is_symlink():
|
||||
copy(library, tools / "rust/lib" / library.name)
|
||||
for name in ("lib", "bin"):
|
||||
copy(rust / "lib/rustlib" / TRIPLE / name, tools / "rust/lib/rustlib" / TRIPLE / name)
|
||||
# 只裁剪已链接的工具;标准库 rlib/rmeta 中的符号、类型元数据与位码仍用于编译。
|
||||
binaries = [*(tools / "rust/bin").iterdir(), *(tools / "rust/lib").glob("*.so*")]
|
||||
binaries.extend(path for path in (tools / "rust/lib/rustlib" / TRIPLE / "bin").rglob("*")
|
||||
if path.is_file())
|
||||
for binary in binaries:
|
||||
# 官方 .so 目录也含链接脚本,按原样保留,只处理 ELF 文件。
|
||||
with binary.open("rb") as stream:
|
||||
if stream.read(4) == b"\x7fELF":
|
||||
subprocess.run(["strip", "--strip-unneeded", str(binary)], check=True)
|
||||
copy(rust / "share/doc/rust", tools / "licenses/rust")
|
||||
if vendor:
|
||||
copy(vendor, tools / "vendor")
|
||||
else:
|
||||
subprocess.run([
|
||||
"cargo", f"+{version}", "vendor", "--locked", "--offline", "--versioned-dirs",
|
||||
str(tools / "vendor"),
|
||||
], cwd=SOURCE / "rust", check=True)
|
||||
config = tools / ".cargo/config.toml"
|
||||
config.parent.mkdir()
|
||||
config.write_text('''[source.crates-io]
|
||||
replace-with = "vendored-sources"
|
||||
|
||||
[source.vendored-sources]
|
||||
directory = "vendor"
|
||||
''')
|
||||
script(tools / "bin/cargo", '''export CARGO_HOME="$tools/.cargo"
|
||||
export RUSTC="$tools/rust/bin/rustc"
|
||||
export CC="$tools/bin/cc"
|
||||
export AR="$tools/native/usr/bin/x86_64-linux-gnu-ar"
|
||||
export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER="$CC"
|
||||
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER="$tools/bin/aarch64-linux-gnu-gcc"
|
||||
export CC_aarch64_unknown_linux_gnu="$tools/bin/aarch64-linux-gnu-gcc"
|
||||
export AR_aarch64_unknown_linux_gnu="$tools/cross/usr/bin/aarch64-linux-gnu-ar"
|
||||
export LD_LIBRARY_PATH="$tools/cross/usr/lib/x86_64-linux-gnu:$tools/lib"
|
||||
export PATH="$tools/native/usr/bin:/usr/bin:/bin"
|
||||
exec "$tools/rust/bin/cargo" --config "$tools/.cargo/config.toml" "$@"
|
||||
''')
|
||||
script(tools / "bin/rustc", '''export LD_LIBRARY_PATH="$tools/lib"
|
||||
exec "$tools/rust/bin/rustc" "$@"
|
||||
''')
|
||||
|
||||
|
||||
def prepare(compiler, work):
|
||||
work.mkdir()
|
||||
bundle = work / "dever"
|
||||
bundle.mkdir()
|
||||
for name in ("rust/Cargo.toml", "rust/Cargo.lock", "rust/src", "lib",
|
||||
"skills/dever/SKILL.md", "GETTING_STARTED.md", "LANGUAGE.md",
|
||||
"DOCUMENTATION.md", "sdk/README.md",
|
||||
"test/rust/native/combinations.dever"):
|
||||
copy(SOURCE / name, bundle / name)
|
||||
for language in ("python", "javascript", "go", "c"):
|
||||
for path in sorted((SOURCE / "sdk" / language).iterdir()):
|
||||
if path.is_file():
|
||||
copy(path, bundle / path.relative_to(SOURCE))
|
||||
copy(compiler, bundle / "bin/dever-core")
|
||||
script(bundle / "bin/dever", '''export DEVER_ROOT="$tools"
|
||||
exec "$tools/bin/dever-core" "$@"
|
||||
''')
|
||||
return bundle
|
||||
|
||||
|
||||
def aarch64_tools(tools, native, standard):
|
||||
"""复用已准备的 Debian 交叉工具与官方目标标准库,不带旧 Dever 运行库。"""
|
||||
copy(standard, tools / "rust/lib/rustlib/aarch64-unknown-linux-gnu")
|
||||
for name in ("usr/aarch64-linux-gnu", "usr/lib/gcc-cross/aarch64-linux-gnu",
|
||||
"usr/libexec/gcc-cross/aarch64-linux-gnu", "usr/lib/x86_64-linux-gnu"):
|
||||
# libcc1 是 GDB 的表达式求值插件;包内 Rust/C 构建不包含调试器。
|
||||
shutil.copytree(native / name, tools / "cross" / name,
|
||||
ignore=shutil.ignore_patterns("libcc1.so"))
|
||||
for name in ("gcc-14", "as", "ld", "ar", "ranlib"):
|
||||
copy(native / "usr/bin" / f"aarch64-linux-gnu-{name}",
|
||||
tools / "cross/usr/bin" / f"aarch64-linux-gnu-{name}")
|
||||
for path in (native / "usr/share/doc").iterdir():
|
||||
if any(name in path.name for name in ("aarch64", "arm64", "cross-base")):
|
||||
copy(path / "copyright", tools / "licenses/cross" / path.name / "copyright")
|
||||
script(tools / "bin/aarch64-linux-gnu-gcc", '''export LD_LIBRARY_PATH="$tools/cross/usr/lib/x86_64-linux-gnu:$tools/lib"
|
||||
exec "$tools/cross/usr/bin/aarch64-linux-gnu-gcc-14" \\
|
||||
--sysroot="$tools/cross" \\
|
||||
-B"$tools/cross/usr/lib/gcc-cross/aarch64-linux-gnu/14/" \\
|
||||
-B"$tools/cross/usr/libexec/gcc-cross/aarch64-linux-gnu/14/" \\
|
||||
-B"$tools/cross/usr/bin/" "$@"
|
||||
''')
|
||||
|
||||
|
||||
def record(bundle, compiler):
|
||||
files = []
|
||||
for path in sorted(bundle.rglob("*")):
|
||||
if path.is_symlink():
|
||||
raise RuntimeError(f"release contains a symlink: {path}")
|
||||
if path.is_file():
|
||||
files.append({"path": path.relative_to(bundle).as_posix(),
|
||||
"bytes": path.stat().st_size, "sha256": digest(path),
|
||||
"executable": os.access(path, os.X_OK)})
|
||||
version = tomllib.loads((bundle / "rust/Cargo.toml").read_text())["package"]["version"]
|
||||
if output(str(compiler), "--version") != f"dever {version}":
|
||||
raise RuntimeError("compiler version differs from release sources")
|
||||
manifest = {"format": "dever-development-1", "version": version, "target": TRIPLE,
|
||||
"rust": "1.95.0", "compiler_sha256": digest(compiler), "files": files}
|
||||
(bundle / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
|
||||
return manifest
|
||||
|
||||
|
||||
def external_tools(home, bundle):
|
||||
"""只选独立准备目录中的工具和下载缓存;不带日志、配置或编译缓存。"""
|
||||
home = home.resolve(strict=True)
|
||||
selected = ["tools/go", "tools/node", "tools/uv", "tools/python", "tools/patchelf",
|
||||
"go/modules", "npm/_cacache", "uv/archive-v0", "uv/wheels-v5",
|
||||
"uv/simple-v18", "uv/sdists-v9"]
|
||||
for name in selected:
|
||||
source = home / name
|
||||
if not source.is_dir():
|
||||
raise RuntimeError(f"external distribution input is not prepared: {name}")
|
||||
for path in source.rglob("*"):
|
||||
if path.is_symlink() and not path.resolve(strict=True).is_relative_to(home):
|
||||
raise RuntimeError(f"external cache link escapes its prepared directory: {path}")
|
||||
copy(source, bundle / "external" / name)
|
||||
script(bundle / "bin/dever", '''export DEVER_ROOT="$tools"
|
||||
export DEVER_HOME="${DEVER_HOME:-$tools/external}"
|
||||
exec "$tools/bin/dever-core" "$@"
|
||||
''')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--compiler", required=True, type=Path)
|
||||
parser.add_argument("--work", required=True, type=Path, help="new staging directory")
|
||||
parser.add_argument("--output", required=True, type=Path, help="new .tar.xz or .tar.gz archive")
|
||||
parser.add_argument("--external-home", type=Path, help="isolated prepared DEVER_HOME to include official tools and dependency download caches")
|
||||
parser.add_argument("--aarch64-native", type=Path, help="prepared Debian 13 cross-GCC root; paired with --aarch64-std")
|
||||
parser.add_argument("--aarch64-std", type=Path, help="official Rust 1.95 rustlib/aarch64-unknown-linux-gnu directory")
|
||||
args = parser.parse_args()
|
||||
if bool(args.aarch64_native) != bool(args.aarch64_std):
|
||||
parser.error("--aarch64-native and --aarch64-std must be provided together")
|
||||
system = Path("/etc/os-release").read_text()
|
||||
if 'ID=debian\n' not in system or 'VERSION_ID="13"' not in system:
|
||||
parser.error("prepare this package in the Debian 13 development container")
|
||||
args.compiler = args.compiler.resolve(strict=True)
|
||||
args.work = args.work.absolute()
|
||||
args.output = args.output.absolute()
|
||||
if not args.output.name.endswith((".tar.xz", ".tar.gz")):
|
||||
parser.error("output must end in .tar.xz or .tar.gz")
|
||||
checksum = Path(str(args.output) + ".sha256")
|
||||
if args.output.exists() or checksum.exists():
|
||||
parser.error("output archive and checksum must not exist")
|
||||
bundle = prepare(args.compiler, args.work)
|
||||
tools = bundle / "toolchain"
|
||||
tools.mkdir()
|
||||
native_tools(tools)
|
||||
rust_tools(tools, "1.95.0", None)
|
||||
if args.aarch64_native:
|
||||
aarch64_tools(tools, args.aarch64_native.resolve(strict=True), args.aarch64_std.resolve(strict=True))
|
||||
if args.external_home:
|
||||
external_tools(args.external_home, bundle)
|
||||
copy(SOURCE / "build/README.md", bundle / "DEVELOPMENT.md")
|
||||
manifest = record(bundle, args.compiler)
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
compressor = "xz -3 -T4" if args.output.suffix == ".xz" else "gzip -6"
|
||||
with args.output.open("xb") as stream:
|
||||
subprocess.run(["tar", "-C", str(args.work), "-I", compressor, "-cf", "-", "dever"],
|
||||
stdout=stream, check=True)
|
||||
with checksum.open("x") as stream:
|
||||
stream.write(f"{digest(args.output)} {args.output.name}\n")
|
||||
print(json.dumps({"archive": str(args.output), "bytes": args.output.stat().st_size,
|
||||
"files": len(manifest["files"]), "compiler_sha256": digest(args.compiler)}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env python3
|
||||
"""生成内置原生构建能力的 Linux x86_64 dever。"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import tomllib
|
||||
|
||||
from development import SOURCE, TRIPLE, digest, output
|
||||
|
||||
|
||||
FOOTER = b"DVRLOC01"
|
||||
RUST = "+1.95.0"
|
||||
MANIFEST = str(SOURCE / "rust/Cargo.toml")
|
||||
NATIVE_PACKAGES = ("libc6", "libc6-dev", "libgcc-s1", "zlib1g")
|
||||
|
||||
|
||||
def runtime(work):
|
||||
command = ["cargo", RUST, "build", "--manifest-path", MANIFEST,
|
||||
"-p", "dever-runtime", "--all-features", "--locked", "--offline", "--release",
|
||||
"--message-format=json"]
|
||||
with (work / "runtime.jsonl").open("w+") as events:
|
||||
subprocess.run(command, stdout=events, check=True)
|
||||
events.seek(0)
|
||||
for line in events:
|
||||
event = json.loads(line)
|
||||
if event["reason"] == "compiler-artifact":
|
||||
for name in event["filenames"]:
|
||||
path = Path(name)
|
||||
if path.suffix in {".rlib", ".so"}:
|
||||
yield f"crates/{path.name}", path
|
||||
elif event["reason"] == "build-script-executed" and event["linked_libs"]:
|
||||
for path in Path(event["out_dir"]).glob("*.a"):
|
||||
yield f"native/{path.name}", path
|
||||
|
||||
|
||||
def licenses(rust, work):
|
||||
notices = work / "THIRD-PARTY.txt"
|
||||
docs = rust / "share/doc/rust"
|
||||
packages = json.loads(output(
|
||||
"cargo", RUST, "metadata", "--manifest-path", MANIFEST, "--locked", "--offline",
|
||||
"--all-features", "--filter-platform", TRIPLE, "--format-version", "1",
|
||||
))["packages"]
|
||||
with notices.open("wb") as stream:
|
||||
def copy_notice(name, path):
|
||||
stream.write(f"\n=== {name} ===\n".encode())
|
||||
with path.open("rb") as notice:
|
||||
shutil.copyfileobj(notice, stream)
|
||||
stream.write(b"\n")
|
||||
|
||||
stream.write(b"Dever distribution: third-party notices\n")
|
||||
for path in sorted(docs.rglob("*")):
|
||||
if path.is_file():
|
||||
copy_notice(f"Rust {RUST[1:]}/{path.relative_to(docs)}", path)
|
||||
for name, version in (line.split("\t") for line in output(
|
||||
"dpkg-query", "-W", *NATIVE_PACKAGES).splitlines()):
|
||||
copy_notice(f"Debian {name} {version}",
|
||||
Path("/usr/share/doc") / name.split(":")[0] / "copyright")
|
||||
for path in sorted(Path("/usr/share/common-licenses").iterdir()):
|
||||
if path.is_file() and not path.is_symlink():
|
||||
copy_notice(f"Debian common licenses/{path.name}", path)
|
||||
for package in packages:
|
||||
if not package["source"]:
|
||||
continue
|
||||
name = f'{package["name"]} {package["version"]}'
|
||||
stream.write(f'\n{name}: {package["license"]}\n'.encode())
|
||||
directory = Path(package["manifest_path"]).parent
|
||||
files = {path for path in directory.iterdir() if path.is_file() and
|
||||
path.name.upper().startswith(("LICENSE", "LICENCE", "COPYING", "COPYRIGHT", "NOTICE", "UNLICENSE"))}
|
||||
if package["license_file"]:
|
||||
files.add(directory / package["license_file"])
|
||||
for path in sorted(files):
|
||||
copy_notice(f"{name}/{path.name}", path)
|
||||
return notices
|
||||
|
||||
|
||||
def inputs(work):
|
||||
rust = Path(output("rustc", RUST, "--print", "sysroot"))
|
||||
if f"host: {TRIPLE}" not in output("rustc", RUST, "-vV"):
|
||||
raise RuntimeError(f"expected a {TRIPLE} release environment")
|
||||
standard = rust / "lib/rustlib" / TRIPLE
|
||||
engine, = (rust / "lib").glob("librustc_driver-*.so")
|
||||
backend, = (rust / "lib").glob("libLLVM.so.*")
|
||||
native = Path("/usr/lib/x86_64-linux-gnu")
|
||||
selected = {
|
||||
"THIRD-PARTY.txt": licenses(rust, work),
|
||||
"bin/compile": rust / "bin/rustc",
|
||||
"bin/link": standard / "bin/rust-lld",
|
||||
"lib/engine": engine,
|
||||
"lib/backend": backend,
|
||||
"lib/zlib": native / "libz.so.1",
|
||||
}
|
||||
for path in (standard / "lib").iterdir():
|
||||
if path.suffix in {".rlib", ".rmeta"}:
|
||||
selected[f"sysroot/lib/rustlib/{TRIPLE}/lib/{path.name}"] = path
|
||||
for name in ("Scrt1.o", "crti.o", "crtn.o", "libc_nonshared.a", "libdl.a", "librt.a",
|
||||
"libpthread.a", "libutil.a"):
|
||||
selected[f"crt/{name}"] = native / name
|
||||
for library in ("libc", "libm", "libgcc_s"):
|
||||
suffix = "1" if library == "libgcc_s" else "6"
|
||||
selected[f"crt/{library}.so"] = native / f"{library}.so.{suffix}"
|
||||
for name, path in runtime(work):
|
||||
previous = selected.setdefault(name, path)
|
||||
if previous != path:
|
||||
raise RuntimeError(f"conflicting build resource {name}: {previous} and {path}")
|
||||
return selected
|
||||
|
||||
|
||||
def append_resources(destination, selected, work):
|
||||
with subprocess.Popen(["xz", "-3", "-T2"], stdin=subprocess.PIPE, stdout=destination) as xz:
|
||||
with tarfile.open(fileobj=xz.stdin, mode="w|") as archive:
|
||||
for name, path in sorted(selected.items()):
|
||||
if name.startswith(("bin/", "lib/")) or path.suffix == ".so":
|
||||
stripped = work / "elf"
|
||||
shutil.copyfile(path, stripped)
|
||||
subprocess.run(["strip", "--strip-unneeded", str(stripped)], check=True)
|
||||
path = stripped
|
||||
path = path.resolve(strict=True)
|
||||
info = archive.gettarinfo(str(path), arcname=name)
|
||||
info.mode, info.mtime, info.uid, info.gid = 0o600, 0, 0, 0
|
||||
info.uname = info.gname = ""
|
||||
with path.open("rb") as source:
|
||||
archive.addfile(info, source)
|
||||
xz.stdin.close()
|
||||
if xz.wait():
|
||||
raise RuntimeError("compressing native build resources failed")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--compiler", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
compiler = args.compiler.resolve(strict=True)
|
||||
destination = args.output.absolute()
|
||||
version = tomllib.loads((SOURCE / "rust/Cargo.toml").read_text())["package"]["version"]
|
||||
if output(str(compiler), "--version") != f"dever {version}":
|
||||
parser.error("compiler and source versions differ")
|
||||
with compiler.open("rb") as source:
|
||||
if source.read(4) != b"\x7fELF":
|
||||
parser.error("expected a native ELF compiler")
|
||||
source.seek(-len(FOOTER), os.SEEK_END)
|
||||
if source.read() == FOOTER:
|
||||
parser.error("compiler already contains a native build image")
|
||||
if destination.exists():
|
||||
parser.error("output must be a new path")
|
||||
with tempfile.TemporaryDirectory(prefix="dever-native-", dir=destination.parent) as work:
|
||||
work = Path(work)
|
||||
selected = inputs(work)
|
||||
stage = work / "dever"
|
||||
shutil.copyfile(compiler, stage)
|
||||
with stage.open("r+b", buffering=0) as stream:
|
||||
start = stream.seek(0, os.SEEK_END)
|
||||
append_resources(stream, selected, work)
|
||||
end = stream.seek(0, os.SEEK_END)
|
||||
stream.write(struct.pack("<Q", end - start) + FOOTER)
|
||||
stage.chmod(0o755)
|
||||
os.link(stage, destination)
|
||||
print(f"{digest(destination)} {destination.name}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user