Skip to content

Commit 7d3d48b

Browse files
fix: a graph's C library leads a Mach-O image's link
The loader of Mach-O runs an image's initialisers before its entry, in link order; openkal-musl is brought up by an initialiser of its own, and the program's objects came before it. A global constructor that allocated (the registration of an mtest case) stopped in the allocator before the library was up: every os test on hosted macOS exited 139 at start. The objects of a package that provides mcpp:c-abi now lead every Mach-O image's objects, in their own order, as a C runtime's start objects do on ELF (e2e 1053). Co-authored-by: speak-agent <248744407+speak-agent@users.noreply.github.com>
1 parent 3a0e411 commit 7d3d48b

5 files changed

Lines changed: 143 additions & 10 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,11 @@
114114
`unaffected`, and the check that every script runs somewhere accepts them
115115
for that run; with main's coverage map in place, it had read them as
116116
uncovered. A shard the set gives no script is not a failure of mtest.
117+
- A C library of the graph (`mcpp:c-abi`, openkal-musl) leads a Mach-O image's
118+
link. The loader runs initialisers in link order before the entry, and the
119+
program's objects came first: a global constructor that allocated (an mtest
120+
case's registration) stopped in openkal-musl's allocator before the library
121+
was up, on hosted macOS (e2e 1053).
117122
- e2e 298 picks a row whose compiler on this host is its convention's: a macOS
118123
host serves `aarch64-linux-musl` through openkal-platform, whose compiler is
119124
llvm, and there llvm alone overrides nothing.

‎docs/35-platforms.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,12 @@ On Windows the arrangement is the GNU ABI's row (`--target x86_64-windows-gnu`);
160160
a triple outside `[platform.hosted] targets` is refused, naming the row of the
161161
same system and architecture that it serves.
162162

163+
A C library of the graph (`mcpp:c-abi`) leads a Mach-O image's link
164+
(2026.11.9.1+). The loader of that format runs an image's initialisers before
165+
its entry, in link order, and the C library is brought up by an initialiser of
166+
its own; with its objects first, it is up before any global constructor of the
167+
program runs, as a C runtime's start objects precede a program on ELF.
168+
163169
## The version group
164170

165171
`[platform.versions]` names one version of each package of a family. From mcpp

‎docs/zh/35-platforms.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,10 @@ platform = "openkal-platform@0.24.0"
137137
Windows 上这一安排对应 GNU ABI 的行(`--target x86_64-windows-gnu`);`[platform.hosted] targets` 之外的
138138
三元组被拒绝,消息给出它所服务的同系统同架构的行。
139139

140+
图中的 C 库(`mcpp:c-abi`)位于 Mach-O 映像链接的最前(2026.11.9.1+)。该格式的加载器在入口之前按链接顺序运行
141+
映像的初始化函数,而 C 库由它自己的一个初始化函数启动;其目标文件在前,C 库便在程序的任何全局构造函数运行之前
142+
就绪,如同 ELF 上 C 运行时的启动目标文件位于程序之前。
143+
140144
## 版本组
141145

142146
`[platform.versions]` 为一个家族列出每个包的一个版本。从 mcpp 2026.11.7.1 起由版本组选择版本:平台是依赖图解析的

‎src/build/plan.cppm‎

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4569,16 +4569,36 @@ make_plan(const mcpp::manifest::Manifest& manifest,
45694569
// unit's objects, a workspace's member archives held its closure: 11 433
45704570
// members for 2 666 objects, 5.3 GB (mcpp#874). An object that is not a
45714571
// compile unit's -- an `object` action's -- is the package's own and stays.
4572-
{
4573-
std::map<std::filesystem::path, std::string> ownerOfObject;
4574-
for (auto const& cu : plan.compileUnits) ownerOfObject.emplace(cu.object, cu.packageName);
4575-
for (auto& lu : plan.linkUnits) {
4576-
if (lu.kind != LinkUnit::StaticLibrary) continue;
4577-
std::erase_if(lu.objects, [&](const std::filesystem::path& o) {
4578-
auto it = ownerOfObject.find(o);
4579-
return it != ownerOfObject.end() && it->second != lu.package;
4580-
});
4581-
}
4572+
std::map<std::filesystem::path, std::string> ownerOfObject;
4573+
for (auto const& cu : plan.compileUnits) ownerOfObject.emplace(cu.object, cu.packageName);
4574+
for (auto& lu : plan.linkUnits) {
4575+
if (lu.kind != LinkUnit::StaticLibrary) continue;
4576+
std::erase_if(lu.objects, [&](const std::filesystem::path& o) {
4577+
auto it = ownerOfObject.find(o);
4578+
return it != ownerOfObject.end() && it->second != lu.package;
4579+
});
4580+
}
4581+
// THE C LIBRARY LEADS A MACH-O IMAGE. This format's loader runs an image's
4582+
// initialisers before its entry, in link order, so a C library of the
4583+
// graph (`mcpp:c-abi`, openkal-musl) is brought up by an initialiser of
4584+
// its own (openkal-musl's port/src/mach/early_init.c). Linked after the
4585+
// program's objects, it came too late: the registration of a test, a
4586+
// global constructor that allocates, stopped in an allocator not yet
4587+
// started (mcpplibs/os#22, hosted macOS). Its objects precede every other
4588+
// package's, in their own order, as a C runtime's start objects do on ELF.
4589+
if (targetTriple.is_mach_o()) {
4590+
std::set<std::string> cLibraries;
4591+
for (auto const& pkg : packages)
4592+
if (std::ranges::any_of(pkg.manifest.provides,
4593+
[](const std::string& p) { return p.starts_with("mcpp:c-abi"); }))
4594+
cLibraries.insert(qualified_package_name(pkg.manifest));
4595+
auto of_c_library = [&](const std::filesystem::path& o) {
4596+
auto it = ownerOfObject.find(o);
4597+
return it != ownerOfObject.end() && cLibraries.contains(it->second);
4598+
};
4599+
if (!cLibraries.empty())
4600+
for (auto& lu : plan.linkUnits)
4601+
if (lu.kind != LinkUnit::StaticLibrary) std::ranges::stable_partition(lu.objects, of_c_library);
45824602
}
45834603
for (auto& v : artifactVariants) plan.compileUnits.push_back(std::move(v));
45844604

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
#!/usr/bin/env bash
2+
# requires: llvm unix-shell
3+
# 1053 -- a Mach-O image's C library is up before the program's initialisers
4+
# (2026.11.9.1).
5+
#
6+
# The loader of this format runs an image's initialisers before its entry, in
7+
# the order the linker placed their objects. A C library of the graph
8+
# (`mcpp:c-abi`: openkal-musl, in openkal-platform's hosted arrangement) is
9+
# brought up by an initialiser of its own; the program's objects came first on
10+
# the link line, and a global constructor that allocated -- the registration of
11+
# an mtest case -- stopped in an allocator not yet started (mcpplibs/os#22,
12+
# hosted macOS, EXC_BAD_ACCESS in mimalloc). The C library's objects now lead
13+
# the link, as a C runtime's start objects do on ELF.
14+
#
15+
# Criteria:
16+
# A. In the image built for `aarch64-macos-musl` over the hosted arrangement, the
17+
# C library's initialiser (`okm_early_init`, openkal-musl's
18+
# port/src/mach/early_init.c) precedes the program's own.
19+
# B. On an arm64 macOS host the program runs, its global constructor
20+
# allocating before `main`.
21+
set -e
22+
source "$(dirname "${BASH_SOURCE[0]}")/_toolchain_env.sh"
23+
24+
TMP=$(mktemp -d)
25+
trap 'rm -rf "$TMP"' EXIT
26+
fail() { echo "FAIL: $1"; shift; for f in "$@"; do echo "--- $f ---"; cat "$f" 2>/dev/null; done; exit 1; }
27+
28+
mkdir -p "$TMP/app/src"
29+
cd "$TMP/app"
30+
printf '[package]\nname = "early"\nversion = "0.1.0"\n' > mcpp.toml
31+
cat > src/main.cpp <<'CPP'
32+
import std;
33+
// A global constructor that allocates, as a test framework's registration does.
34+
std::vector<std::string>* registered = new std::vector<std::string>{std::string(64, 'x')};
35+
int main() {
36+
std::println("registered {}", registered->front().size());
37+
return 0;
38+
}
39+
CPP
40+
41+
"$MCPP" build --target aarch64-macos-musl > build.log 2>&1 || fail "the hosted macOS build" build.log
42+
grep -q "openkal-platform" build.log || {
43+
echo "SKIP: aarch64-macos-musl is not served by openkal-platform's hosted arrangement here"
44+
exit 0
45+
}
46+
bin=$(find target -path '*/bin/early' -type f | head -1)
47+
[ -n "$bin" ] || fail "no image was produced" build.log
48+
49+
# A
50+
objdump="$_e2e_registry_base/xim-x-llvm/${LLVM_VERSION}/bin/llvm-objdump"
51+
nm="$_e2e_registry_base/xim-x-llvm/${LLVM_VERSION}/bin/llvm-nm"
52+
[ -x "$objdump" ] && [ -x "$nm" ] || { echo "SKIP(A): no llvm@${LLVM_VERSION} payload to read the image with"; objdump=""; }
53+
if [ -n "$objdump" ]; then
54+
python3 - "$bin" "$objdump" "$nm" > a.log 2>&1 <<'PY' || fail "A: the order of the image's initialisers" a.log build.log
55+
import subprocess, sys
56+
image, objdump, nm = sys.argv[1:4]
57+
dump = subprocess.run([objdump, "--macho", "-s", "-j", "__init_offsets", image],
58+
capture_output=True, text=True, check=True).stdout
59+
words = []
60+
for line in dump.splitlines():
61+
parts = line.split()
62+
if len(parts) < 2 or not all(c in "0123456789abcdef" for c in parts[0]):
63+
continue
64+
for w in parts[1:5]:
65+
if len(w) == 8 and all(c in "0123456789abcdef" for c in w):
66+
words.append(int.from_bytes(bytes.fromhex(w), "little"))
67+
symbols = []
68+
for line in subprocess.run([nm, "-n", image], capture_output=True, text=True, check=True).stdout.splitlines():
69+
parts = line.split()
70+
if len(parts) == 3:
71+
symbols.append((int(parts[0], 16), parts[2]))
72+
def name_at(offset):
73+
address = 0x100000000 + offset
74+
best = None
75+
for value, name in symbols:
76+
if value > address:
77+
break
78+
best = name
79+
return best or "?"
80+
names = [name_at(o) for o in words]
81+
print("initialisers:", names[:8])
82+
assert any("okm_early_init" in n for n in names), "the C library's initialiser is not in the image"
83+
early = next(i for i, n in enumerate(names) if "okm_early_init" in n)
84+
program = [i for i, n in enumerate(names) if "main.cpp" in n]
85+
assert program, "the program's initialiser is not in the image"
86+
assert early < program[0], f"the program's initialiser runs at {program[0]}, before the C library's at {early}"
87+
PY
88+
echo " ok the C library's initialiser precedes the program's"
89+
fi
90+
91+
# B
92+
if [ "$(uname -s)-$(uname -m)" = Darwin-arm64 ]; then
93+
"$bin" > b.log 2>&1 || fail "B: the image ended with $?" b.log
94+
grep -q "registered 64" b.log || fail "B: the program's output" b.log
95+
echo " ok the program runs, its constructor allocating before main"
96+
fi
97+
98+
echo "OK: a Mach-O image's C library is up before its initialisers"

0 commit comments

Comments
 (0)