Add rolling release built with Zig's musl toolchain
Build a static Linux x86_64 binary with zig cc, linking OpenSSL in and serving it to moonbitlang/async through a dlopen shim. CI publishes it to the rolling release on every push to main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3ca9e8ed1d
commit
2d815bbb75
9 files changed
+368
No files matched your search
Executable
+76
@@ -0,0 +1,76 @@
|
||||
#!/bin/sh
|
||||
# Build a fully static Orbit with Zig's musl toolchain:
|
||||
# dist/orbit-linux-x86_64 and dist/SHA256SUMS
|
||||
#
|
||||
# Needs moon, zig, perl, make, and curl. OpenSSL is built once, with zig, into
|
||||
# _build/musl-deps (set ORBIT_MUSL_DEPS to keep it elsewhere).
|
||||
set -eu
|
||||
|
||||
openssl_version=3.5.9
|
||||
openssl_sha256=603f5602e2eef00d77fbd429d34dcd5822bb301757a1bc9cdb24c670f1eb859a
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
root=$PWD
|
||||
|
||||
# Only x86_64: the libbacktrace.a that moon links is prebuilt for the host.
|
||||
if [ "$(uname -sm)" != "Linux x86_64" ]; then
|
||||
echo "build-musl.sh only supports Linux x86_64" >&2
|
||||
exit 1
|
||||
fi
|
||||
export ORBIT_MUSL_TARGET=x86_64-linux-musl
|
||||
|
||||
deps=${ORBIT_MUSL_DEPS:-$root/_build/musl-deps}
|
||||
prefix=$deps/openssl-$openssl_version-zig-$(zig version)
|
||||
|
||||
if [ ! -f "$prefix/lib/libssl.a" ]; then
|
||||
echo "Building OpenSSL $openssl_version with zig $(zig version)" >&2
|
||||
mkdir -p "$deps"
|
||||
work=$(mktemp -d "$deps/build.XXXXXX")
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
curl -fsSL --retry 5 -o "$work/openssl.tar.gz" \
|
||||
"https://github.com/openssl/openssl/releases/download/openssl-$openssl_version/openssl-$openssl_version.tar.gz"
|
||||
printf '%s %s\n' "$openssl_sha256" "$work/openssl.tar.gz" | sha256sum -c - >&2
|
||||
tar -xzf "$work/openssl.tar.gz" -C "$work"
|
||||
(
|
||||
cd "$work/openssl-$openssl_version"
|
||||
# no-autoload-config: the host's openssl.cnf may name modules we can't load.
|
||||
CC="$root/scripts/musl/cc" AR="$root/scripts/musl/ar" RANLIB="zig ranlib" \
|
||||
./Configure linux-x86_64 --prefix="$work/out" --libdir=lib --openssldir=/etc/ssl \
|
||||
no-shared no-module no-dso no-apps no-tests no-docs no-legacy no-autoload-config \
|
||||
no-ssl3 no-tls1 no-tls1_1 no-dtls no-comp no-afalgeng
|
||||
make -s -j"$(nproc)" build_libs
|
||||
make -s install_dev
|
||||
) > "$work/log" 2>&1 || { tail -n 60 "$work/log" >&2; exit 1; }
|
||||
rm -rf "$prefix"
|
||||
mv "$work/out" "$prefix"
|
||||
fi
|
||||
|
||||
if [ ! -d .mooncakes/moonbitlang/async ]; then moon install >&2; fi
|
||||
obj=$root/_build/musl-shim
|
||||
mkdir -p "$obj"
|
||||
sed -nE 's/^ *IMPORT_FUNC(_WITH_ALT_NAMES)?\([^,]+, *([A-Za-z0-9_]+) *,.*/ORBIT_SYMBOL(\2)/p' \
|
||||
.mooncakes/moonbitlang/async/src/tls/openssl.c > "$obj/openssl_symbols.h"
|
||||
if [ "$(wc -l < "$obj/openssl_symbols.h")" -lt 20 ]; then
|
||||
echo "Could not read the OpenSSL imports from moonbitlang/async" >&2
|
||||
exit 1
|
||||
fi
|
||||
scripts/musl/cc -c -O2 -I"$prefix/include" -I"$obj" \
|
||||
scripts/musl/openssl_static.c -o "$obj/openssl_static.o"
|
||||
|
||||
# A separate target directory keeps these objects apart from the usual glibc ones.
|
||||
# moon doesn't track ORBIT_MUSL_LINK, so relink every time.
|
||||
rm -f _build/musl/native/release/build/main/main.exe
|
||||
# async's dir.c uses NAME_MAX without limits.h, which only glibc's dirent.h pulls in.
|
||||
MOON_CC=$root/scripts/musl/cc MOON_AR=$root/scripts/musl/ar \
|
||||
ORBIT_MUSL_CFLAGS="-include limits.h" \
|
||||
ORBIT_MUSL_LINK="$obj/openssl_static.o $prefix/lib/libssl.a $prefix/lib/libcrypto.a" \
|
||||
moon build --target native --release --target-dir _build/musl >&2
|
||||
|
||||
mkdir -p dist
|
||||
install -m 755 _build/musl/native/release/build/main/main.exe dist/orbit-linux-x86_64
|
||||
if readelf -lW dist/orbit-linux-x86_64 | grep -q INTERP; then
|
||||
echo "dist/orbit-linux-x86_64 is not static" >&2
|
||||
exit 1
|
||||
fi
|
||||
(cd dist && sha256sum orbit-linux-x86_64 > SHA256SUMS)
|
||||
ls -l dist >&2
|
||||
Executable
+2
@@ -0,0 +1,2 @@
|
||||
#!/bin/sh
|
||||
exec zig ar "$@"
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
# MOON_CC for static musl builds: `zig cc`, plus the static OpenSSL objects when linking.
|
||||
set -eu
|
||||
# shellcheck disable=SC2086 # ORBIT_MUSL_* are space-separated lists
|
||||
|
||||
for arg in "$@"; do
|
||||
case $arg in
|
||||
-c) exec zig cc -target "$ORBIT_MUSL_TARGET" -ffunction-sections -fdata-sections ${ORBIT_MUSL_CFLAGS-} "$@" ;;
|
||||
esac
|
||||
done
|
||||
exec zig cc -target "$ORBIT_MUSL_TARGET" -static -s -Wl,--gc-sections "$@" ${ORBIT_MUSL_LINK-}
|
||||
@@ -0,0 +1,66 @@
|
||||
// moonbitlang/async loads OpenSSL with dlopen/dlsym, which a static musl binary
|
||||
// can't do. These definitions replace musl's stubs (nothing else in Orbit uses
|
||||
// them) and hand out the statically linked OpenSSL functions instead.
|
||||
//
|
||||
// openssl_symbols.h is generated by scripts/build-musl.sh from async's own
|
||||
// import list, so a function OpenSSL lacks fails the link, not the first request.
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <openssl/crypto.h>
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/objects.h>
|
||||
#include <openssl/rand.h>
|
||||
#include <openssl/sha.h>
|
||||
#include <openssl/ssl.h>
|
||||
#include <openssl/x509.h>
|
||||
|
||||
// SSL_CTX_set_default_verify_paths only checks the OPENSSLDIR chosen at build
|
||||
// time (/etc/ssl). Also load the CA bundle from where other distros keep it,
|
||||
// unless the user picked their own with SSL_CERT_FILE or SSL_CERT_DIR.
|
||||
static int set_default_verify_paths(SSL_CTX *ctx) {
|
||||
static const char *const bundles[] = {
|
||||
"/etc/ssl/certs/ca-certificates.crt", // Debian, Arch, Alpine, Nix
|
||||
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // Fedora, RHEL
|
||||
"/etc/pki/tls/certs/ca-bundle.crt", // older Fedora, RHEL
|
||||
"/etc/ssl/ca-bundle.pem", // openSUSE
|
||||
"/etc/ssl/cert.pem", // Alpine, Void
|
||||
};
|
||||
if (!SSL_CTX_set_default_verify_paths(ctx)) return 0;
|
||||
if (getenv("SSL_CERT_FILE") || getenv("SSL_CERT_DIR")) return 1;
|
||||
for (size_t i = 0; i < sizeof(bundles) / sizeof(bundles[0]); ++i) {
|
||||
if (access(bundles[i], R_OK) == 0 &&
|
||||
SSL_CTX_load_verify_file(ctx, bundles[i])) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static const struct {
|
||||
const char *name;
|
||||
void *address;
|
||||
} symbols[] = {
|
||||
{ "OpenSSL_version_num", (void *)OpenSSL_version_num },
|
||||
#define ORBIT_SYMBOL(name) { #name, (void *)name },
|
||||
#include "openssl_symbols.h"
|
||||
#undef ORBIT_SYMBOL
|
||||
};
|
||||
|
||||
void *dlopen(const char *file, int mode) {
|
||||
(void)mode;
|
||||
return file && strncmp(file, "libssl.so", 9) == 0 ? (void *)symbols : NULL;
|
||||
}
|
||||
|
||||
void *dlsym(void *handle, const char *name) {
|
||||
if (handle != (void *)symbols) return NULL;
|
||||
if (strcmp(name, "SSL_CTX_set_default_verify_paths") == 0) {
|
||||
return (void *)set_default_verify_paths;
|
||||
}
|
||||
for (size_t i = 0; i < sizeof(symbols) / sizeof(symbols[0]); ++i) {
|
||||
if (strcmp(name, symbols[i].name) == 0) return symbols[i].address;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
Executable
+92
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish dist/ as the rolling Gitea release. Run by .gitea/workflows/rolling-release.yml."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
TAG = "rolling"
|
||||
STAGED = "new-"
|
||||
ASSETS = ["orbit-linux-x86_64", "SHA256SUMS"]
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
DIST = ROOT / "dist"
|
||||
SERVER = os.environ["GITHUB_SERVER_URL"].rstrip("/")
|
||||
REPO = os.environ["GITHUB_REPOSITORY"]
|
||||
COMMIT = os.environ["GITHUB_SHA"]
|
||||
TOKEN = os.environ["GITEA_TOKEN"]
|
||||
RELEASES = f"{SERVER}/api/v1/repos/{REPO}/releases"
|
||||
|
||||
|
||||
def call(method, url, data=None, content_type="application/json"):
|
||||
"""Make a Gitea API call. Returns None when a GET finds nothing."""
|
||||
if isinstance(data, dict):
|
||||
data = json.dumps(data).encode()
|
||||
request = urllib.request.Request(url, data=data, method=method)
|
||||
request.add_header("Authorization", f"token {TOKEN}")
|
||||
if data is not None:
|
||||
request.add_header("Content-Type", content_type)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=300) as response:
|
||||
body = response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
if method == "GET" and error.code == 404:
|
||||
return None
|
||||
detail = error.read().decode(errors="replace")
|
||||
raise SystemExit(f"{method} {url}: HTTP {error.code}: {detail}")
|
||||
return json.loads(body) if body else None
|
||||
|
||||
|
||||
def replace_assets(release_id):
|
||||
"""Upload under staging names, then swap, so downloads are only missing for a moment."""
|
||||
assets_url = f"{RELEASES}/{release_id}/assets"
|
||||
for asset in call("GET", assets_url):
|
||||
if asset["name"].startswith(STAGED):
|
||||
call("DELETE", f"{assets_url}/{asset['id']}")
|
||||
for name in ASSETS:
|
||||
query = urllib.parse.urlencode({"name": STAGED + name})
|
||||
call("POST", f"{assets_url}?{query}", (DIST / name).read_bytes(), "application/octet-stream")
|
||||
ids = {asset["name"]: asset["id"] for asset in call("GET", assets_url)}
|
||||
for name in ASSETS:
|
||||
if name in ids:
|
||||
call("DELETE", f"{assets_url}/{ids[name]}")
|
||||
call("PATCH", f"{assets_url}/{ids[STAGED + name]}", {"name": name})
|
||||
|
||||
|
||||
def main():
|
||||
missing = [name for name in ASSETS if not (DIST / name).is_file()]
|
||||
if missing:
|
||||
raise SystemExit(f"missing from dist/: {', '.join(missing)}")
|
||||
|
||||
sums = (DIST / "SHA256SUMS").read_text().strip()
|
||||
download = f"{SERVER}/{REPO}/releases/download/{TAG}"
|
||||
release = {
|
||||
"tag_name": TAG,
|
||||
"target_commitish": COMMIT,
|
||||
"name": f"Rolling build ({COMMIT[:7]})",
|
||||
"prerelease": True,
|
||||
"body": (
|
||||
f"Automated build of `main` at [`{COMMIT[:7]}`]({SERVER}/{REPO}/commit/{COMMIT}). "
|
||||
"A static Linux x86_64 binary built with Zig's musl toolchain, with OpenSSL included.\n\n"
|
||||
f"```sh\ncurl -fLo orbit {download}/orbit-linux-x86_64\nchmod +x orbit\n```\n\n"
|
||||
f"```\n{sums}\n```\n"
|
||||
),
|
||||
}
|
||||
|
||||
existing = call("GET", f"{RELEASES}/tags/{TAG}")
|
||||
if existing is None:
|
||||
existing = call("POST", RELEASES, {**release, "draft": False})
|
||||
replace_assets(existing["id"])
|
||||
subprocess.run(
|
||||
["git", "push", "--force", "origin", f"{COMMIT}:refs/tags/{TAG}"], cwd=ROOT, check=True
|
||||
)
|
||||
call("PATCH", f"{RELEASES}/{existing['id']}", {**release, "draft": False})
|
||||
print(f"Published {SERVER}/{REPO}/releases/tag/{TAG}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user