File size: 14,278 Bytes
5f25733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
"""Check real Mach-O relocation and fail-closed native input handling."""

import ctypes
import json
import os
from pathlib import Path
import platform
import shutil
import struct
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch

from macos_runtime import PLUGINS, digest, inspect, project


@unittest.skipUnless(sys.platform == "darwin", "macOS native runtime projection")
class RuntimeTests(unittest.TestCase):
    def setUp(self):
        temporary = tempfile.TemporaryDirectory(prefix="native voice ")
        self.addCleanup(temporary.cleanup)
        self.root = Path(temporary.name)
        self.prefix = self.root / "input"
        self.receipts = self.root / "receipts"
        self.output = self.root / "runtime"
        self.target = (
            "aarch64" if platform.machine() == "arm64" else "x86_64"
        ) + "-apple-darwin"
        (self.prefix / "lib/gstreamer-1.0").mkdir(parents=True)
        (self.receipts / "inspection").mkdir(parents=True)
        source = self.root / "fixture.c"
        source.write_text("int voice_fixture(void) { return 42; }\n")
        self.library = self.prefix / "lib/libfixture.1.2.dylib"
        subprocess.run(
            [
                "/usr/bin/cc",
                "-dynamiclib",
                str(source),
                "-o",
                str(self.library),
                "-Wl,-install_name,@rpath/libfixture.1.dylib",
                "-Wl,-headerpad_max_install_names",
            ],
            check=True,
            capture_output=True,
        )
        (self.prefix / "lib/libfixture.1.dylib").symlink_to(self.library.name)
        gio = self.prefix / "lib/libgio-2.0.0.dylib"
        shutil.copy2(self.library, gio)
        subprocess.run(
            ["/usr/bin/install_name_tool", "-id", "@rpath/" + gio.name, str(gio)],
            check=True,
            capture_output=True,
        )
        source.write_text(
            "extern int voice_fixture(void); int voice_plugin(void) { return voice_fixture(); }\n"
        )
        prototype = self.prefix / f"lib/gstreamer-1.0/libgst{PLUGINS[0]}.dylib"
        subprocess.run(
            [
                "/usr/bin/cc",
                "-dynamiclib",
                str(source),
                str(self.library),
                "-o",
                str(prototype),
                f"-Wl,-install_name,{prototype}",
                f"-Wl,-rpath,{self.prefix / 'lib'}",
                "-Wl,-headerpad_max_install_names",
            ],
            check=True,
            capture_output=True,
        )
        for name in PLUGINS[1:]:
            path = self.prefix / f"lib/gstreamer-1.0/libgst{name}.dylib"
            shutil.copy2(prototype, path)
            subprocess.run(
                ["/usr/bin/install_name_tool", "-id", str(path), str(path)],
                check=True,
                capture_output=True,
            )
        self.ci = {
            "commit": "a" * 40,
            "target": self.target,
            "build_complete": True,
            "inspection_complete": True,
            "manifest_sha256": digest(Path(__file__).with_name("sources.json")),
        }
        (self.receipts / "ci.json").write_text(json.dumps(self.ci))
        self.inventory = [
            {
                "path": p.relative_to(self.prefix).as_posix(),
                "target": self.target,
                "sha256": digest(p),
            }
            for p in sorted(self.prefix.rglob("*.dylib"))
            if not p.is_symlink()
        ]
        self.inventory_path = self.receipts / "inspection/binaries.json"
        self.inventory_path.write_text(json.dumps(self.inventory))

    def test_relocated_payload_loads_after_original_prefix_is_removed(self):
        subprocess.run(
            [
                sys.executable,
                str(Path(__file__).with_name("macos_runtime.py").resolve()),
                "--prefix",
                str(self.prefix),
                "--receipts",
                str(self.receipts),
                "--target",
                self.target,
                "--output",
                str(self.output),
            ],
            check=True,
            capture_output=True,
            cwd=self.root,
            env={**os.environ, "PYTHONSAFEPATH": "1"},
        )
        manifest = json.loads((self.output / "runtime.json").read_text())
        before = {r["path"]: digest(self.prefix / r["path"]) for r in self.inventory}
        self.assertEqual(before, {r["path"]: r["sha256"] for r in self.inventory})
        self.assertEqual(
            {r["path"] for r in manifest["libraries"]},
            {
                "lib/libfixture.1.dylib",
                "lib/libgio-2.0.0.dylib",
                *(f"plugins/libgst{name}.dylib" for name in PLUGINS),
            },
        )
        moved = self.root / "relocated package"
        self.output.rename(moved)
        shutil.rmtree(self.prefix)
        for relative in manifest["plugins"]:
            plugin = ctypes.CDLL(str(moved / relative))
            self.assertEqual(plugin.voice_plugin(), 42)
        for record in manifest["libraries"]:
            metadata = inspect(moved / record["path"], self.target)
            self.assertEqual(metadata.rpaths, ())
            self.assertEqual(metadata.imports, tuple(record["imports"]))
            self.assertEqual(digest(moved / record["path"]), record["sha256"])

    def test_input_digest_target_and_receipt_must_match(self):
        for key, value in [
            ("build_complete", False),
            ("manifest_sha256", "b" * 64),
            ("target", "wrong"),
        ]:
            with self.subTest(key=key), self.assertRaises(ValueError):
                (self.receipts / "ci.json").write_text(
                    json.dumps({**self.ci, key: value})
                )
                project(self.prefix, self.receipts, self.target, self.output)
            self.assertFalse(self.output.exists())
        (self.receipts / "ci.json").write_text(json.dumps(self.ci))
        self.library.write_bytes(b"tampered")
        with self.assertRaisesRegex(ValueError, "digest mismatch"):
            project(self.prefix, self.receipts, self.target, self.output)
        self.assertFalse(self.output.exists())

    def test_case_alias_cannot_place_output_inside_inputs(self):
        for source in (self.prefix, self.receipts):
            alias = source.with_name(source.name.upper())
            if not alias.exists():
                self.skipTest("requires a case-insensitive filesystem")
            with (
                self.subTest(source=source),
                self.assertRaisesRegex(ValueError, "outside the inputs"),
            ):
                project(self.prefix, self.receipts, self.target, alias / "runtime")
            self.assertFalse((source / "runtime").exists())

    def test_case_colliding_library_destinations_are_rejected(self):
        duplicate = self.prefix / "lib/another.dylib"
        shutil.copy2(self.library, duplicate)
        subprocess.run(
            [
                "/usr/bin/install_name_tool",
                "-id",
                "@rpath/LIBFIXTURE.1.dylib",
                str(duplicate),
            ],
            check=True,
            capture_output=True,
        )
        self.inventory.append(
            {
                "path": duplicate.relative_to(self.prefix).as_posix(),
                "target": self.target,
                "sha256": digest(duplicate),
            }
        )
        self.inventory_path.write_text(json.dumps(self.inventory))
        with self.assertRaisesRegex(ValueError, "colliding runtime library filenames"):
            project(self.prefix, self.receipts, self.target, self.output)
        self.assertFalse(self.output.exists())

    def test_changed_source_at_copy_is_rejected(self):
        copy = shutil.copy2

        def change_then_copy(source, destination):
            source.write_bytes(source.read_bytes() + b"changed after verification")
            return copy(source, destination)

        with patch("runtime.shutil.copy2", side_effect=change_then_copy):
            with self.assertRaisesRegex(ValueError, "copied native input changed"):
                project(self.prefix, self.receipts, self.target, self.output)
        self.assertFalse(self.output.exists())

    def test_missing_dependency_and_duplicate_identity_fail_before_output_creation(
        self,
    ):
        self.inventory_path.write_text(
            json.dumps([r for r in self.inventory if "libgio" not in r["path"]])
        )
        with self.assertRaisesRegex(ValueError, "missing required native library"):
            project(self.prefix, self.receipts, self.target, self.output)
        self.assertFalse(self.output.exists())
        self.inventory_path.write_text(
            json.dumps([r for r in self.inventory if "libfixture" not in r["path"]])
        )
        with self.assertRaisesRegex(ValueError, "undeclared native dependency"):
            project(self.prefix, self.receipts, self.target, self.output)
        self.inventory_path.write_text(json.dumps([*self.inventory, self.inventory[0]]))
        with self.assertRaisesRegex(ValueError, "duplicate"):
            project(self.prefix, self.receipts, self.target, self.output)
        self.assertFalse(self.output.exists())

    def test_inventory_cannot_escape_prefix(self):
        for relative in (
            "../fixture.c",
            str(self.library),
            "lib/../lib/libfixture.1.2.dylib",
        ):
            self.inventory_path.write_text(
                json.dumps([{**self.inventory[0], "path": relative}])
            )
            with self.subTest(path=relative), self.assertRaises(ValueError):
                project(self.prefix, self.receipts, self.target, self.output)
            self.assertFalse(self.output.exists())

    def test_multiline_import_cannot_impersonate_a_system_library(self):
        external = self.root / "outside\n         name /usr/lib/libSystem.B.dylib"
        external.parent.mkdir(parents=True)
        shutil.copy2(self.library, external)
        plugin = self.prefix / f"lib/gstreamer-1.0/libgst{PLUGINS[0]}.dylib"
        subprocess.run(
            [
                "/usr/bin/install_name_tool",
                "-change",
                "@rpath/libfixture.1.dylib",
                str(external),
                str(plugin),
            ],
            check=True,
            capture_output=True,
        )
        for record in self.inventory:
            record["sha256"] = digest(self.prefix / record["path"])
        self.inventory_path.write_text(json.dumps(self.inventory))
        with self.assertRaisesRegex(ValueError, "undeclared native dependency"):
            project(self.prefix, self.receipts, self.target, self.output)
        self.assertFalse(self.output.exists())

    def test_malformed_load_command_bounds_and_strings_are_rejected(self):
        command = struct.pack("<6I", 0xD, 32, 24, 0, 0, 0) + b"test\0\0\0\0"
        for count, size, payload in (
            (1, 1024 * 1024 + 1, command),
            (2, 32, command),
            (1, 32, command[:-1]),
            (1, 32, struct.pack("<3I", 0xD, 40, 24) + command[12:]),
            (1, 32, struct.pack("<3I", 0xD, 32, 8) + command[12:]),
            (1, 32, command[:24] + b"no null!"),
        ):
            with self.subTest(count=count, size=size, payload=payload):
                cpu = 0x100000C if self.target.startswith("aarch64") else 0x1000007
                self.library.write_bytes(
                    struct.pack("<8I", 0xFEEDFACF, cpu, 0, 6, count, size, 0, 0)
                    + payload
                )
                with self.assertRaises(ValueError):
                    inspect(self.library, self.target)

    def test_tool_cannot_hide_other_architectures_or_loader_commands(self):
        cpu = 0x100000C if self.target.startswith("aarch64") else 0x1000007
        name = b"@rpath/libtest.dylib\0"
        command = (
            struct.pack("<6I", 0xD, 48, 24, 0, 0, 0) + name + bytes(24 - len(name))
        )
        thin = struct.pack("<8I", 0xFEEDFACF, cpu, 0, 6, 1, 48, 0, 0) + command
        for tag in (0x2B, 0x3A):
            self.library.write_bytes(
                struct.pack("<8I", 0xFEEDFACF, cpu, 0, 6, 2, 64, 0, 0)
                + command
                + struct.pack("<4I", tag, 16, 0, 0)
            )
            with self.subTest(tag=tag), self.assertRaises(ValueError):
                inspect(self.library, self.target)
        fat = struct.pack(">7I", 0xCAFEBABE, 1, cpu, 0, 4096, len(thin), 12)
        self.library.write_bytes(fat + bytes(4096 - len(fat)) + thin)
        with self.assertRaises(ValueError):
            inspect(self.library, self.target)
        fake_cpu = "X86_64" if cpu == 0x100000C else "ARM64"
        fake_target = (
            "x86_64-apple-darwin" if cpu == 0x100000C else "aarch64-apple-darwin"
        )
        path = (
            self.root
            / f"fake\nMH_MAGIC_64 {fake_cpu} ALL 0x00 DYLIB 1 48 0x00000000\n\n.dylib"
        )
        path.write_bytes(thin)
        with self.assertRaises(ValueError):
            inspect(path, fake_target)

    def test_existing_outputs_and_failed_transform_preserve_inputs(self):
        for output in (self.prefix, self.prefix / "nested", self.receipts / "nested"):
            with self.subTest(output=output), self.assertRaises(ValueError):
                project(self.prefix, self.receipts, self.target, output)
        import macos_runtime

        original_run = macos_runtime.run

        def fail_transform(command):
            if command[0].endswith("install_name_tool"):
                raise subprocess.CalledProcessError(1, command)
            return original_run(command)

        with patch("macos_runtime.run", side_effect=fail_transform):
            with self.assertRaises(subprocess.CalledProcessError):
                project(self.prefix, self.receipts, self.target, self.output)
        self.assertFalse(self.output.exists())
        self.assertEqual(
            {r["path"]: digest(self.prefix / r["path"]) for r in self.inventory},
            {r["path"]: r["sha256"] for r in self.inventory},
        )


if __name__ == "__main__":
    unittest.main()