Add the runtime library, libmacrt.a, and archive support in the linkers

runtime/build.sh builds compiler-rt's builtins (the 68000's 32-bit
multiply and divide, 64-bit arithmetic, soft float on 68k, conversions)
and runtime/string.c (the mem* functions clang calls for structure
copies, and the common str* ones) into lib/m68k/libmacrt.a and
lib/ppc/libmacrt.a.

codelink.py and peflink.py read ar archives (tools/link/archive.py) and
link only the members a program needs; macapp.py links the runtime
library when it has been built.

tests/runtime.c checks every helper. tests/run.sh builds the library
when LLVM_SRC is set and runs the 68k test as a 68000 and a 68020 in
sim68k; CI does both, with compiler-rt from the prebuilt clang's commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRSuLMRWD4gxrktBpac
Signed-off-by: Claude <noreply@anthropic.com>
This commit is contained in:
Claude committed 2026-11-08 09:32:32 +00:00
1 parent ebb8bac60b
commit 3ac904b451
11 files changed
+511 -30

No files matched your search

+14 -2
View File
@@ -2,6 +2,7 @@
# push: compile every header for 68k and PowerPC, check record sizes and the
# ROM-checked argument blocks, build the examples, and check that the
# generated files (include/, docs/coverage.md) match their generators.
# It also builds the runtime library from compiler-rt and runs its test.
#
# clang comes from clang-retro/llvm's llvm-prebuilt release, which holds the
# LLVM tools built from recent commits of its main branch; the newest Linux
@@ -33,7 +34,7 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: pip install pyyaml
- run: pip install pyyaml unicorn
- name: Get clang
env:
GH_TOKEN: ${{ github.token }}
@@ -46,6 +47,9 @@ jobs:
tar --zstd -xf llvm.tar.zst -C "$RUNNER_TEMP/llvm"
rm llvm.tar.zst
echo "CLANG=$RUNNER_TEMP/llvm/bin/clang" >> "$GITHUB_ENV"
# llvm-linux-COMMIT-SCRIPTHASH.tar.zst: compiler-rt from the same commit.
sha=${asset#llvm-linux-}
echo "LLVM_SHA=${sha%%-*}" >> "$GITHUB_ENV"
"$RUNNER_TEMP/llvm/bin/clang" --version
- name: Generated files are up to date
run: |
@@ -54,5 +58,13 @@ jobs:
git status --porcelain
git diff --exit-code
test -z "$(git status --porcelain)"
- name: Get compiler-rt's builtins
uses: actions/checkout@v4
with:
repository: clang-retro/llvm
ref: ${{ env.LLVM_SHA }}
path: llvm
sparse-checkout: compiler-rt/lib/builtins
persist-credentials: false
- name: Tests
run: tests/run.sh
run: LLVM_SRC=$PWD/llvm tests/run.sh
+1
View File
@@ -1,2 +1,3 @@
__pycache__/
/site/
/lib/
+36 -9
View File
@@ -219,7 +219,7 @@ as the ROM's PowerPC glue does; the high-level File Manager, Device
Manager and serial calls fill in a parameter block; the lowercase
C-string calls (`fsopen`, `getwtitle`, ...) convert their strings and
call the Pascal routine. The glue avoids `memcpy`, `memset` and 32-bit
multiplies, since there is no 68k runtime library yet (BlockMoveData
multiplies, so the headers work without the runtime library (BlockMoveData
copies instead). `include/needs-glue.txt` lists what is left: mostly
calls that never ran on 68k (Navigation Services, Driver Services, the
Name Registry).
@@ -262,8 +262,33 @@ The linkers it runs are in `tools/link/` and can be used on their own:
by `cfrg`, and the 68k code in CODE. A Power Mac runs the PowerPC
code and a 68k Mac runs CODE.
Not done yet in the linkers: archives (`.a`), static constructors,
shared libraries (exports), and pattern-compressed PEF data.
Both linkers take archives (`.a`) and link only the members a program
needs. Not done yet in them: static constructors, shared libraries
(exports), and pattern-compressed PEF data.
### The runtime library
clang calls helper functions for what the CPU cannot do in a few
instructions: on the 68000, 32-bit multiply and divide (`__mulsi3`,
`__udivsi3`, ...), and on both CPUs 64-bit divide, soft float on 68k
(`__adddf3`, ...), conversions, and `memcpy` and `memset` for structure
copies. `runtime/build.sh` builds them into `libmacrt.a` for each CPU,
from compiler-rt's builtins and `runtime/string.c` (the `mem*` functions
and the common `str*` ones):
```sh
CLANG=path/to/clang LLVM_SRC=path/to/clang-retro/llvm runtime/build.sh
```
It writes `lib/m68k/libmacrt.a` and `lib/ppc/libmacrt.a`, which
`tools/macapp.py` links when they are there (`--no-runtime` leaves them
out). There is no C library yet: declare the `<string.h>` functions you
use yourself, as `tests/runtime.c` does. Soft float is large on 68k
and counts towards the 32 KB limit: `tests/runtime.c`, which uses float
and double arithmetic and conversions, links to 20 KB.
`tests/runtime.c` checks each helper; `tests/run.sh` runs its 68k build
as a 68000 and a 68020 in `tools/sim68k.py`.
### Testing
@@ -297,7 +322,8 @@ CLANG=path/to/clang tests/run.sh
It compiles every header for both targets in C and C++, generates code
for every 68k inline function, checks the size of every record whose
definition gives one, checks the argument-block calls against the ROM,
and links every example into a fat application.
and links every example into a fat application. With `LLVM_SRC` set it
also builds the runtime library and runs its test.
`.github/workflows/check.yml` runs it for every pull request and push,
with the newest clang from clang-retro/llvm's `llvm-prebuilt` release,
@@ -309,11 +335,12 @@ and also fails when `include/` or `docs/coverage.md` differ from what
- Coverage: the headers declare all but 3 undocumented symbols of what
the ROM's InterfaceLib exports (see docs/coverage.md).
- 68k glue for the rest of `needs-glue.txt` that did run on 68k (the
Fixed/extended conversions, the 64-bit Wide math, TESetWordBreak and TESetClickLoop, which need a register
trampoline), and a runtime library (`__udivsi3`, `memcpy` and the
other helpers clang calls on 68k).
- Archives, static constructors and shared libraries in the linkers,
and a large code model for 68k programs over 32 KB.
Fixed/extended conversions, the 64-bit Wide math, TESetWordBreak and
TESetClickLoop, which need a register trampoline).
- A C library (`<stdio.h>` over the File Manager, `malloc` over the
Memory Manager).
- Static constructors and shared libraries in the linkers, and a large
code model for 68k programs over 32 KB.
## License
+71
View File
@@ -0,0 +1,71 @@
#!/bin/sh
# Build the runtime library, libmacrt.a, for 68k and PowerPC: compiler-rt's
# builtins (32-bit multiply and divide for the 68000, 64-bit arithmetic,
# soft float on 68k, conversions) and the memory and string functions in
# string.c.
#
# CLANG=... LLVM_SRC=... runtime/build.sh [OUT]
#
# CLANG clang-retro's clang (default: clang on the PATH); llvm-ar is
# taken from the same directory
# LLVM_SRC a clang-retro/llvm checkout (only compiler-rt/lib/builtins
# is read)
# OUT where to put m68k/libmacrt.a and ppc/libmacrt.a (default:
# lib/ in the SDK, where tools/macapp.py looks)
#
# Each builtin is its own archive member, so a program links only those
# it calls. The archives are in the GNU ar format, which codelink.py and
# peflink.py read.
set -e
here=$(cd "$(dirname "$0")" && pwd)
sdk=$(dirname "$here")
: "${LLVM_SRC:?set LLVM_SRC to a clang-retro/llvm checkout}"
CLANG=${CLANG:-clang}
out=${1:-$sdk/lib}
builtins=$LLVM_SRC/compiler-rt/lib/builtins
[ -f "$builtins/int_lib.h" ] || { echo "no compiler-rt builtins in $LLVM_SRC" >&2; exit 1; }
bindir=$(dirname "$(command -v "$CLANG")")
AR=${AR:-$bindir/llvm-ar}
work=$(mktemp -d "${TMPDIR:-/tmp}/macrt.XXXXXX")
trap 'rm -rf "$work"' EXIT
# Files that need an operating system, or a type these targets lack.
skip=" atomic crtbegin crtend emutls enable_execute_stack eprintf clear_cache
gcc_personality_v0 trampoline_setup os_version_check cpu_model
truncdfbf2 truncsfbf2 extendhfxf2 truncxfhf2 "
for cpu in m68k ppc; do
case $cpu in
m68k) target=m68k-apple-macos; flags="-mcpu=68000" ;;
# The PowerPC target makes XCOFF, as AIX does; compiler-rt knows how
# to make aliases there only for AIX.
ppc) target=powerpc-apple-macos9; flags="-D_AIX" ;;
esac
mkdir -p "$work/$cpu" "$out/$cpu"
cc="$CLANG --target=$target -O2 -ffreestanding -fno-builtin $flags"
for f in "$builtins"/*.c; do
n=$(basename "$f" .c)
case $skip in *" $n "*) continue ;; esac
# Some builtins are for types or CPUs these targets lack (__int128,
# x87 long double); they fail to compile and are left out.
$cc -c "$f" -o "$work/$cpu/$n.o" 2>/dev/null || rm -f "$work/$cpu/$n.o"
done
# The 68000's 32-bit multiply is in assembly.
if [ $cpu = m68k ]; then
for f in "$builtins"/m68k/*.S; do
$cc -c "$f" -o "$work/$cpu/$(basename "$f" .S).o"
done
fi
# The ones clang calls for plain C must be there.
need="divdi3 udivdi3 moddi3 umoddi3 fixdfdi floatdidf fixunsdfsi"
[ $cpu = m68k ] && need="$need mulsi3 divsi3 udivsi3 modsi3 umodsi3 muldi3
addsf3 subsf3 mulsf3 divsf3 adddf3 subdf3 muldf3 divdf3 comparesf2
comparedf2 fixdfsi floatsidf fixsfsi floatsisf extendsfdf2 truncdfsf2"
for n in $need; do
[ -f "$work/$cpu/$n.o" ] || { echo "$cpu: $n.c did not compile" >&2; exit 1; }
done
$cc -Wall -Wextra -Werror -c "$here/string.c" -o "$work/$cpu/string.o"
rm -f "$out/$cpu/libmacrt.a"
"$AR" --format=gnu rcs "$out/$cpu/libmacrt.a" "$work/$cpu"/*.o
echo "$cpu: $(ls "$work/$cpu" | wc -l) objects in $out/$cpu/libmacrt.a"
done
+130
View File
@@ -0,0 +1,130 @@
/* The memory and string functions that clang calls on its own (memcpy,
* memmove, memset for structure copies and zeroing, memcmp) and the
* common <string.h> ones, for programs that have no C library.
*
* Copyright (C) clang-retro contributors.
* SPDX-License-Identifier: AGPL-3.0-only
*
* Built with -ffreestanding -fno-builtin, so clang does not turn these
* loops back into calls to themselves. */
#include <stddef.h>
void *memcpy(void *restrict dst, const void *restrict src, size_t n) {
unsigned char *d = dst;
const unsigned char *s = src;
/* Word copies when both are even: the 68000 faults on odd word access. */
if ((((unsigned long)d | (unsigned long)s) & 1) == 0) {
for (; n >= 4; n -= 4, d += 4, s += 4)
*(unsigned long *)d = *(const unsigned long *)s;
}
while (n--)
*d++ = *s++;
return dst;
}
void *memmove(void *dst, const void *src, size_t n) {
unsigned char *d = dst;
const unsigned char *s = src;
if (d == s || n == 0)
return dst;
if (d < s || d >= s + n)
return memcpy(dst, src, n);
d += n;
s += n;
while (n--)
*--d = *--s;
return dst;
}
void *memset(void *dst, int c, size_t n) {
unsigned char *d = dst;
if (((unsigned long)d & 1) == 0 && n >= 4) {
unsigned long w = (unsigned char)c;
w |= w << 8;
w |= w << 16;
for (; n >= 4; n -= 4, d += 4)
*(unsigned long *)d = w;
}
while (n--)
*d++ = (unsigned char)c;
return dst;
}
int memcmp(const void *a, const void *b, size_t n) {
const unsigned char *p = a, *q = b;
for (; n; n--, p++, q++)
if (*p != *q)
return *p - *q;
return 0;
}
void *memchr(const void *s, int c, size_t n) {
const unsigned char *p = s;
for (; n; n--, p++)
if (*p == (unsigned char)c)
return (void *)p;
return NULL;
}
size_t strlen(const char *s) {
const char *p = s;
while (*p)
p++;
return p - s;
}
char *strcpy(char *restrict dst, const char *restrict src) {
char *d = dst;
while ((*d++ = *src++))
;
return dst;
}
char *strncpy(char *restrict dst, const char *restrict src, size_t n) {
char *d = dst;
for (; n && *src; n--)
*d++ = *src++;
for (; n; n--)
*d++ = 0;
return dst;
}
char *strcat(char *restrict dst, const char *restrict src) {
strcpy(dst + strlen(dst), src);
return dst;
}
int strcmp(const char *a, const char *b) {
for (; *a && *a == *b; a++, b++)
;
return (unsigned char)*a - (unsigned char)*b;
}
int strncmp(const char *a, const char *b, size_t n) {
for (; n; n--, a++, b++) {
if (*a != *b)
return (unsigned char)*a - (unsigned char)*b;
if (!*a)
break;
}
return 0;
}
char *strchr(const char *s, int c) {
for (;; s++) {
if (*s == (char)c)
return (char *)s;
if (!*s)
return NULL;
}
}
char *strrchr(const char *s, int c) {
const char *r = NULL;
for (;; s++) {
if (*s == (char)c)
r = s;
if (!*s)
return (char *)r;
}
}
+23 -1
View File
@@ -2,7 +2,8 @@
# Compile every header for both targets, in C and C++, and check record
# sizes (tests/sizes.c, and every size given in defs/), and check the
# argument-block calls against the ROM, and link the examples into
# applications. CLANG defaults to clang on the PATH.
# applications. CLANG defaults to clang on the PATH. With LLVM_SRC set to
# a clang-retro/llvm checkout, also build and check the runtime library.
set -e
cd "$(dirname "$0")/.."
CLANG=${CLANG:-clang}
@@ -43,3 +44,24 @@ for ex in examples/*.c; do
-- -Wall -Werror "$ex" >/dev/null
done
echo "examples: linked"
# The runtime library, when LLVM_SRC names a clang-retro/llvm checkout (for
# compiler-rt): build it, link tests/runtime.c for both CPUs, and run the
# 68k build as a 68000 and a 68020 in tools/sim68k.py (with unicorn).
if [ -n "$LLVM_SRC" ]; then
CLANG="$CLANG" LLVM_SRC="$LLVM_SRC" runtime/build.sh "$APPS/lib"
for cpu in 68k ppc; do
CLANG="$CLANG" python3 tools/macapp.py --cpu $cpu --lib "$APPS/lib" \
-o "$APPS/runtime-$cpu.bin" -- -Wall -Werror tests/runtime.c >/dev/null
done
if python3 -c "import unicorn" 2>/dev/null; then
for c in 68000 68020; do
python3 tools/sim68k.py --cpu $c "$APPS/runtime-68k.bin" >"$APPS/sim.txt" || {
cat "$APPS/sim.txt"; exit 1; }
grep -q "DrawString('all ok')" "$APPS/sim.txt" || {
grep DrawString "$APPS/sim.txt" | grep -v "'ok'"; exit 1; }
done
echo "runtime: ok"
else
echo "runtime: linked (install unicorn to run it)"
fi
fi
+84
View File
@@ -0,0 +1,84 @@
/* Checks the runtime library (runtime/build.sh): the builtins clang calls
* for 32- and 64-bit arithmetic and soft float, and the memory and string
* functions. tests/run.sh links it for both CPUs and runs the 68k build in
* tools/sim68k.py, which prints each DrawString: "ok" for each check that
* passes, and the check's name for one that fails.
*
* Copyright (C) clang-retro contributors.
* SPDX-License-Identifier: AGPL-3.0-only */
#include <Quickdraw.h>
#include <stddef.h>
/* There is no C library yet; these are in the runtime library. */
void *memcpy(void *, const void *, size_t);
void *memmove(void *, const void *, size_t);
void *memset(void *, int, size_t);
int memcmp(const void *, const void *, size_t);
void *memchr(const void *, int, size_t);
size_t strlen(const char *);
char *strcpy(char *, const char *);
char *strcat(char *, const char *);
int strcmp(const char *, const char *);
int strncmp(const char *, const char *, size_t);
char *strchr(const char *, int);
char *strrchr(const char *, int);
/* volatile, so clang cannot work the answers out while compiling. */
static volatile long a32 = -1234567, b32 = 89;
static volatile unsigned long ua = 4000000000UL, ub = 7;
static volatile long long a64 = -123456789012345LL, b64 = 10007;
static volatile double da = 2.5, db = -0.75;
static volatile float fa = 3.0f, fb = 0.5f;
struct big { char c[61]; long l; };
static int failures;
static void say(const char *what) {
Str255 s;
size_t n = strlen(what);
s[0] = (unsigned char)n;
memcpy(s + 1, what, n);
DrawString(s);
}
static void report(const char *what, int ok) {
say(ok ? "ok" : what);
if (!ok)
failures++;
}
#define MUL64 (-1235432087646536415LL)
#define DIV64 (-12337042971LL)
#define MOD64 (-1548)
int main(void) {
struct big x, y;
char buf[32];
report("mul32", a32 * b32 == -109876463);
report("div32", a32 / b32 == -13871 && a32 % b32 == -48);
report("udiv32", ua / ub == 571428571UL && ua % ub == 3);
report("mul64", a64 * b64 == MUL64);
report("div64", a64 / b64 == DIV64 && a64 % b64 == MOD64);
report("shift64", (a64 << 13) >> 13 == a64 && ((unsigned long long)ua << 20) >> 20 == ua);
report("double", da * db == -1.875 && da / db < -3.33 && da / db > -3.34 &&
da + db == 1.75 && da - db == 3.25);
report("float", fa * fb == 1.5f && fa / fb == 6.0f && fa - fb == 2.5f);
report("convert", (long)(da * 1000.0) == 2500 && (double)b32 == 89.0 &&
(long long)(da * 1e12) == 2500000000000LL &&
(float)da == 2.5f && (unsigned long)(fa * 1e9f) == 3000000000UL);
memset(&x, 0x5A, sizeof x);
x.l = 42;
y = x;
report("struct", memcmp(&x, &y, sizeof x) == 0 && y.l == 42 && y.c[60] == 0x5A);
strcpy(buf, "Hello, ");
strcat(buf, "Mac");
report("string", strlen(buf) == 10 && strcmp(buf, "Hello, Mac") == 0 &&
strncmp(buf, "Help", 3) == 0 && strchr(buf, 'M') == buf + 7 &&
strrchr(buf, 'l') == buf + 3 && memchr(buf, ',', 10) == buf + 5);
memmove(buf + 1, buf, 5);
report("memmove", memcmp(buf, "HHello", 6) == 0);
say(failures ? "FAILED" : "all ok");
return 0;
}
+92
View File
@@ -0,0 +1,92 @@
"""Static libraries (ar archives) for codelink.py and peflink.py.
Reads the GNU and BSD ar formats (llvm-ar --format=gnu writes the GNU
one for both CPUs) and picks the members a program needs, the way a Unix
linker does: a member is linked when it defines a symbol that the
objects linked so far reference and nothing defines, until no more
members are needed. Archives are searched together, so members may
refer to each other in any order.
"""
class ArchiveError(Exception):
pass
def is_archive(blob):
return blob[:8] == b"!<arch>\n"
def members(path, blob):
"""Return [(member name, bytes)] for every object in the archive."""
if blob[:8] == b"<bigaf>\n":
raise ArchiveError(f"{path}: AIX big archive; make it with "
f"llvm-ar --format=gnu")
if not is_archive(blob):
raise ArchiveError(f"{path}: not an ar archive")
out = []
longnames = b""
pos = 8
while pos + 60 <= len(blob):
hdr = blob[pos:pos + 60]
if hdr[58:60] != b"`\n":
raise ArchiveError(f"{path}: bad member header at {pos:#x}")
name = hdr[:16].rstrip(b" ")
size = int(hdr[48:58].strip() or b"0")
body = blob[pos + 60:pos + 60 + size]
pos += 60 + size + (size & 1)
if name in (b"/", b"/SYM64/", b"__.SYMDEF", b"__.SYMDEF SORTED"):
continue # symbol table: we read the members
if name == b"//":
longnames = body
continue
if name.startswith(b"#1/"): # BSD: name before the data
n = int(name[3:])
name, body = body[:n].rstrip(b"\0"), body[n:]
elif name.startswith(b"/") and name[1:].isdigit():
o = int(name[1:])
end = longnames.index(b"\n", o)
name = longnames[o:end].rstrip(b"/")
else:
name = name.rstrip(b"/")
out.append((name.decode("latin-1"), body))
return out
def select(objs, archives, load, defines, references):
"""Add to objs the archive members that resolve its undefined symbols.
archives: [(path, blob)]. load(label, blob) parses one member;
defines(obj) and references(obj) give the global names an object
defines and refers to. Returns the members added, in link order.
"""
pool = []
for path, blob in archives:
for name, body in members(path, blob):
pool.append([f"{path}({name})", body, None])
defined, wanted = set(), set()
for o in objs:
defined |= defines(o)
wanted |= references(o)
added = []
changed = True
while changed:
changed = False
need = wanted - defined
if not need:
break
for m in pool:
if m[2] is False:
continue # already linked
if m[2] is None:
m[2] = load(m[0], m[1])
obj = m[2]
if not defines(obj) & need:
continue
added.append(obj)
defined |= defines(obj)
wanted |= references(obj)
m[2] = False
changed = True
need = wanted - defined
return added
+21 -6
View File
@@ -8,10 +8,11 @@ the lot in CODE 1. CODE 0 holds a one-entry jump table that sends the
Segment Loader to __start (start.s), which adds the image's load address
to each listed pointer and calls main.
python3 codelink.py -o Hello.bin start.o hello.o [more.o ...]
python3 codelink.py -o Hello.bin start.o hello.o [more.o ...] [lib.a ...]
[--name Hello] [--creator ????] [--size KB] [--map FILE]
The output is MacBinary II, for hfsutils' "hcopy -m". Put start.o first.
From archives (.a), only the members the program needs are linked.
"""
import argparse
import os
@@ -20,6 +21,7 @@ import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from macres import macbinary, resource_fork, size_res # noqa: E402
import archive # noqa: E402
SHT_PROGBITS, SHT_SYMTAB, SHT_NOBITS, SHT_RELA = 1, 2, 8, 4
SHF_ALLOC = 2
@@ -105,6 +107,16 @@ class ElfObject:
sec.relocs.append((off, info >> 8, info & 0xFF, addend))
def defined_names(o):
return {s["name"] for s in o.symbols
if s["bind"] != STB_LOCAL and s["name"] and s["shndx"] != SHN_UNDEF}
def referenced_names(o):
return {s["name"] for s in o.symbols
if s["bind"] != STB_LOCAL and s["name"] and s["shndx"] == SHN_UNDEF}
def link(objs):
# Lay out the image: text, rodata, data, then bss.
order = ["text", "rodata", "data", "bss"]
@@ -248,14 +260,17 @@ def main():
ap.add_argument("--map", help="write symbol addresses here")
a = ap.parse_args()
try:
objs = []
objs, libs = [], []
for p in a.inputs:
blob = open(p, "rb").read()
if blob[:8] == b"!<arch>\n":
raise LinkError(f"{p}: archives are not supported yet")
objs.append(ElfObject(p, blob))
if archive.is_archive(blob):
libs.append((p, blob))
else:
objs.append(ElfObject(p, blob))
objs += archive.select(objs, libs, ElfObject, defined_names,
referenced_names)
image, syms, _ = link(objs)
except LinkError as e:
except (LinkError, archive.ArchiveError) as e:
sys.exit(f"codelink: error: {e}")
code0, code1 = code_resources(image)
name = a.name or os.path.splitext(os.path.basename(a.output))[0]
+23 -7
View File
@@ -10,7 +10,7 @@ writes the PEF loader section, and wraps the result as a Mac application
with a 'cfrg' resource (and a 'SIZE' resource) in MacBinary form, ready
for hfsutils' "hcopy -m".
python3 peflink.py -o Hello.bin hello.o [more.o ...]
python3 peflink.py -o Hello.bin hello.o [more.o ...] [lib.a ...]
[--imports imports.json] [--carbon] [--name Hello]
[--creator ????] [--size KB] [--pef out.pef]
@@ -24,6 +24,7 @@ import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from macres import cfrg, macbinary, resource_fork, size_res # noqa: E402
import archive # noqa: E402
# ---------------------------------------------------------------- XCOFF
@@ -145,14 +146,29 @@ class XcoffObject:
f"outside every csect")
def defined_names(o):
return {s.name for s in o.symbols.values()
if s.sclass in (C_EXT, C_WEAKEXT) and s.csect is not None
and s.smtyp in (XTY_SD, XTY_LD, XTY_CM)}
def referenced_names(o):
return {s.name for s in o.symbols.values()
if s.sclass in (C_EXT, C_WEAKEXT) and s.smtyp == XTY_ER}
def read_inputs(paths):
objs = []
"""Read the objects, then the archive members they need (before the
shared libraries, so a library can stand in for an import)."""
objs, libs = [], []
for p in paths:
blob = open(p, "rb").read()
if blob[:8] == b"!<arch>\n":
raise LinkError(f"{p}: archives are not supported yet")
objs.append(XcoffObject(p, blob))
return objs
if archive.is_archive(blob) or blob[:8] == b"<bigaf>\n":
libs.append((p, blob))
else:
objs.append(XcoffObject(p, blob))
return objs + archive.select(objs, libs, XcoffObject, defined_names,
referenced_names)
# ---------------------------------------------------------------- imports
@@ -542,7 +558,7 @@ def main():
imports = Imports(a.imports, a.carbon)
img = link(objs, imports)
pef = build_pef(img, imports)
except LinkError as e:
except (LinkError, archive.ArchiveError) as e:
sys.exit(f"peflink: error: {e}")
name = a.name or os.path.splitext(os.path.basename(a.output))[0]
+16 -5
View File
@@ -2,15 +2,19 @@
"""Compile C sources and link them into a classic Mac OS application.
python3 tools/macapp.py -o Hello.bin [--cpu fat|68k|ppc] [--name Hello]
[--creator ????] [--size KB] [--carbon] [-- clang flags] hello.c ...
[--creator ????] [--size KB] [--carbon] [--no-runtime] [--lib DIR]
[-- clang flags] hello.c ...
It compiles each source with clang (the CLANG environment variable, or
clang on the PATH) for m68k-apple-macos and powerpc-apple-macos9 with
this SDK's headers, links the 68k objects with tools/link/start.s by
codelink.py and the PowerPC ones by peflink.py, and with --cpu fat (the
default) merges the two with fatlink.py. Objects (.o) are linked as
they are, for the CPU named by --cpu (not fat). The output is MacBinary
II, for hfsutils' "hcopy -m".
they are, for the CPU named by --cpu (not fat), and so are archives (.a),
from which only the members needed are linked. The runtime library that
runtime/build.sh makes (lib/m68k/libmacrt.a and lib/ppc/libmacrt.a) is
linked last when it is there. The output is MacBinary II, for hfsutils'
"hcopy -m".
"""
import argparse
import os
@@ -40,7 +44,7 @@ def build(cpu, a, clang, tmp):
os.path.join(LINK, "start.s"), "-o", start])
objs.append(start)
for i, src in enumerate(a.sources):
if src.endswith(".o"):
if src.endswith((".o", ".a")):
objs.append(src)
continue
obj = os.path.join(tmp, f"{cpu}-{i}-{os.path.basename(src)}.o")
@@ -48,6 +52,9 @@ def build(cpu, a, clang, tmp):
"-I", os.path.join(SDK, "include")] + a.cflags +
["-c", src, "-o", obj])
objs.append(obj)
rt = os.path.join(a.lib, {"68k": "m68k"}.get(cpu, cpu), "libmacrt.a")
if a.runtime and os.path.exists(rt):
objs.append(rt)
out = os.path.join(tmp, f"{cpu}.bin") if a.cpu == "fat" else a.output
args = ["-o", out, "--name", a.name, "--size", str(a.size)]
if cpu == "68k":
@@ -77,12 +84,16 @@ def main():
ap.add_argument("--creator", default="????")
ap.add_argument("--size", type=int, default=1024,
help="memory partition in KiB")
ap.add_argument("--lib", default=os.path.join(SDK, "lib"),
help="where runtime/build.sh put the runtime library")
ap.add_argument("--no-runtime", dest="runtime", action="store_false",
help="do not link the runtime library")
ap.add_argument("--carbon", action="store_true",
help="PowerPC: import from CarbonLib first")
a = ap.parse_args(argv)
a.cflags = cflags
a.name = a.name or os.path.splitext(os.path.basename(a.output))[0]
if a.cpu == "fat" and any(s.endswith(".o") for s in a.sources):
if a.cpu == "fat" and any(s.endswith((".o", ".a")) for s in a.sources):
sys.exit("macapp: objects are for one CPU; use --cpu 68k or ppc")
clang = shlex.split(os.environ.get("CLANG", "clang"))
with tempfile.TemporaryDirectory() as tmp: