Repository navigation
Expand file tree
/
Copy pathsetup_simulator.py
More file actions
319 lines (294 loc) · 15.6 KB
/
Copy pathsetup_simulator.py
File metadata and controls
319 lines (294 loc) · 15.6 KB
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
"""Create a new offline simulator venv from pinned local wheels. No device APIs."""
import argparse
import hashlib
import json
import os
from email.parser import BytesParser
from pathlib import Path
from pathlib import PurePosixPath
import platform
import re
import subprocess
import sys
import sysconfig
import venv
import zipfile
ROOT = Path(__file__).resolve().parents[1]
LOCKS = {
'macos-arm64-py314': Path(__file__).with_name('simulator-wheels.json'),
'linux-arm64-musl-py312': Path(__file__).with_name('simulator-wheels-linux-arm64-musl-py312.json'),
}
TARGETS = {
'macos-arm64-py314': {
'host': ('darwin', 'arm64'), 'platform': 'darwin-arm64', 'python': [3, 14],
'musl_minimum': None, 'requires_url': False,
'wheel_platform': 'macosx_11_0_arm64',
},
'linux-arm64-musl-py312': {
'host': ('linux', 'aarch64'), 'platform': 'linux-aarch64-musl', 'python': [3, 12],
'musl_minimum': [1, 2, 0], 'requires_url': True,
'wheel_platform': 'musllinux_1_2_aarch64',
},
}
PACKAGE_CONTRACTS = {
'macos-arm64-py314': {
'unicorn': {
'version': '2.1.4', 'wheel': 'unicorn-2.1.4-cp37-abi3-macosx_11_0_arm64.whl',
'sha256': 'd6c93e0f60328d8f4a1792af3f834137a28050fcc2305f2ec01efe8558a9844e',
'tag': 'cp37-abi3-macosx_11_0_arm64',
'requires_python': '!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7',
},
'capstone': {
'version': '5.0.9', 'wheel': 'capstone-5.0.9-py3-none-macosx_11_0_arm64.whl',
'sha256': 'fc269c5082e17d7f9f265cd6980e2fdc6ab572df913951d76db0357e06b8001d',
'tag': 'py3-none-macosx_11_0_arm64', 'requires_python': '>=3.8',
},
},
'linux-arm64-musl-py312': {
'unicorn': {
'version': '2.1.4', 'wheel': 'unicorn-2.1.4-cp37-abi3-musllinux_1_2_aarch64.whl',
'sha256': '01d744ba01c5cc68f1d7afe3d183f1868720fd440ec4eaedc4d1d5d9bf54b84c',
'url': 'https://files.pythonhosted.org/packages/70/38/ba5a051c844026e59ab6e0017db8cec77dbe20ab5f1d6edae1ce9d885b06/unicorn-2.1.4-cp37-abi3-musllinux_1_2_aarch64.whl',
'tag': 'cp37-abi3-musllinux_1_2_aarch64',
'requires_python': '!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7',
},
'capstone': {
'version': '5.0.9', 'wheel': 'capstone-5.0.9-py3-none-musllinux_1_2_aarch64.whl',
'sha256': '69064219c814ad64af35469a7c4ddd19b730cacb96a1a796435ccde0e1567d05',
'url': 'https://files.pythonhosted.org/packages/b9/74/c178ac241892bb3668b633065bdbe6dc719c2aa54668d68a8e23a6753525/capstone-5.0.9-py3-none-musllinux_1_2_aarch64.whl',
'tag': 'py3-none-musllinux_1_2_aarch64', 'requires_python': '>=3.8',
},
},
}
def _musl_loader_from_maps(maps_text):
loaders = set()
has_glibc = False
has_deleted_loader = False
for line in maps_text.splitlines():
fields = line.split(maxsplit=5)
if len(fields) < 6:
continue
mapped = fields[5]
if mapped.endswith(' (deleted)'):
if 'ld-musl-' in mapped:
has_deleted_loader = True
continue
if 'ld-linux' in mapped or 'libc.so.6' in mapped:
has_glibc = True
if re.fullmatch(r'/[^\x00-\x1f]*ld-musl-aarch64\.so\.1', mapped):
loaders.add(mapped)
if has_glibc or has_deleted_loader or len(loaders) != 1:
return None
return loaders.pop()
def _musl_version_from_maps(maps_text, run=subprocess.run):
loader = _musl_loader_from_maps(maps_text)
if loader is None:
return None
try:
result = run([loader, '--version'], check=False, text=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
stdin=subprocess.DEVNULL, timeout=3)
except (OSError, subprocess.TimeoutExpired):
return None
match = re.search(r'^Version\s+(\d+)\.(\d+)\.(\d+)\s*$', result.stdout, re.MULTILINE)
if 'musl libc (aarch64)' not in result.stdout or not match:
return None
return tuple(map(int, match.groups()))
def detect_musl_version():
try:
maps_text = Path('/proc/self/maps').read_text()
except OSError:
return None
return _musl_version_from_maps(maps_text)
def validate_lock(lock, target):
spec = TARGETS[target]
expected_top = {'schema', 'platform', 'python', 'packages'}
if spec['musl_minimum'] is not None:
expected_top.add('musl_minimum')
if not isinstance(lock, dict):
raise ValueError(f'Wheel lock is not an object: {target}')
missing_top = expected_top - set(lock)
if 'musl_minimum' in missing_top:
raise ValueError(f'Wheel lock is missing required libc minimum: {target}')
if 'python' in missing_top:
raise ValueError(f'Wheel lock is missing required Python version: {target}')
if 'packages' in missing_top:
raise ValueError(f'Wheel lock has no valid package list: {target}')
if missing_top or set(lock) - expected_top:
raise ValueError(f'Wheel lock has invalid fields for target: {target}')
if lock['schema'] != 'blackwall-simulator-wheels/1' or lock['platform'] != spec['platform']:
raise ValueError(f'Wheel lock does not match selected target: {target}')
if lock['python'] != spec['python']:
raise ValueError(f'Wheel lock Python version does not match selected target: {target}')
if spec['musl_minimum'] is not None and lock['musl_minimum'] != spec['musl_minimum']:
raise ValueError(f'Wheel lock must require musl libc >= 1.2.0: {target}')
packages = lock['packages']
contracts = PACKAGE_CONTRACTS[target]
if not isinstance(packages, list) or len(packages) != len(contracts):
raise ValueError(f'Wheel lock package set does not match target: {target}')
allowed_fields = {'name', 'version', 'wheel', 'sha256'} | ({'url'} if spec['requires_url'] else set())
seen = set()
for package in packages:
if not isinstance(package, dict) or set(package) != allowed_fields:
raise ValueError(f'Wheel lock contains an incomplete package entry: {target}')
name = package['name']
if not isinstance(name, str) or not name.strip() or any(ord(c) < 32 for c in name):
raise ValueError(f'Wheel lock contains an invalid package name: {target}')
if name in seen:
raise ValueError(f'Wheel lock contains duplicate package: {name}')
seen.add(name)
wheel = package['wheel']
if (not isinstance(wheel, str) or not wheel.endswith('.whl') or '/' in wheel or '\\' in wheel
or PurePosixPath(wheel).name != wheel or any(ord(c) < 32 for c in wheel)):
raise ValueError(f'Wheel lock contains an unsafe wheel filename: {name}')
expected = contracts.get(name)
if expected is None:
raise ValueError(f'Wheel lock contains an unsupported package: {name}')
if any(package.get(key) != value for key, value in expected.items()
if key in {'version', 'wheel', 'sha256', 'url'}):
raise ValueError(f'Wheel lock package does not match approved pin: {name}')
if seen != set(contracts):
raise ValueError(f'Wheel lock package set does not match target: {target}')
return contracts
def _python_specifier_supports(specifier, version):
if specifier == '!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7':
return version >= (3, 7) or (version[0] == 2 and version >= (2, 7))
match = re.fullmatch(r'>=(\d+)\.(\d+)', specifier)
if match:
return version >= tuple(map(int, match.groups()))
return False
def _wheel_tag_supports(tag, wheel_platform, python_version):
parts = tag.split('-')
if len(parts) != 3 or parts[2] != wheel_platform:
return False
interpreter, abi, _ = parts
if interpreter == 'py3' and abi == 'none':
return python_version >= (3, 0)
match = re.fullmatch(r'cp(\d)(\d+)', interpreter)
return (match is not None and abi == 'abi3' and sys.implementation.name == 'cpython'
and python_version >= tuple(map(int, match.groups())))
def validate_wheel_metadata(path, name, package, contract, python_version, target):
try:
with zipfile.ZipFile(path) as archive:
wheel_names = [item for item in archive.namelist() if item.endswith('.dist-info/WHEEL')]
metadata_names = [item for item in archive.namelist() if item.endswith('.dist-info/METADATA')]
if len(wheel_names) != 1 or len(metadata_names) != 1:
raise ValueError(f'Wheel metadata files are ambiguous: {name}')
wheel_text = archive.read(wheel_names[0]).decode('ascii')
metadata = BytesParser().parsebytes(archive.read(metadata_names[0]))
except (OSError, UnicodeError, zipfile.BadZipFile, KeyError) as error:
raise ValueError(f'Invalid wheel archive: {name}') from error
tags = re.findall(r'^Tag:\s*(\S+)\s*$', wheel_text, re.MULTILINE)
if (metadata.get('Name') != name or metadata.get('Version') != package['version']
or metadata.get('Requires-Python') != contract['requires_python']
or tags != [contract['tag']]):
raise ValueError(f'Wheel metadata does not match approved target: {name}')
compatible = _wheel_tag_supports(contract['tag'], TARGETS[target]['wheel_platform'],
tuple(python_version))
python_supported = _python_specifier_supports(contract['requires_python'], tuple(python_version))<
8000
/div>
if not compatible or not python_supported:
raise ValueError(f'Wheel is incompatible with selected Python/platform: {name}')
def validate(wheels, output, target='macos-arm64-py314'):
output_input = Path(output)
if output_input.is_symlink():
raise ValueError('Output must not be a symlink')
output = output_input.resolve()
if output.is_relative_to(ROOT):
raise ValueError('Simulator environment must be outside the repository')
if output.exists():
raise ValueError('Output exists; preserve the current environment')
wheels_input = Path(wheels)
if wheels_input.is_symlink():
raise ValueError('Wheel directory must not be a symlink')
try:
wheels = wheels_input.resolve(strict=True)
except OSError as error:
raise ValueError(f'Wheel directory does not exist: {wheels_input}') from error
if not wheels.is_dir() or wheels.is_relative_to(ROOT):
raise ValueError('Wheel directory must be an existing directory outside the repository')
if wheels.is_relative_to(output) or output.is_relative_to(wheels):
raise ValueError('Output and wheel directories must be separate')
if target not in LOCKS:
raise ValueError(f'Unsupported simulator target: {target}')
lock_path = LOCKS[target]
lock_bytes = lock_path.read_bytes()
lock = json.loads(lock_bytes)
spec = TARGETS[target]
expected_system, expected_machine = spec['host']
contracts = validate_lock(lock, target)
packages = lock['packages']
if (platform.system().lower() != expected_system or platform.machine().lower() != expected_machine
or list(sys.version_info[:2]) != spec['python']):
required_python = '.'.join(map(str, spec['python']))
raise ValueError(f'Target {target} requires {expected_system} {expected_machine} and Python {required_python}')
gil_disabled = sysconfig.get_config_var('Py_GIL_DISABLED')
if gil_disabled is not None and str(gil_disabled).strip().lower() not in ('', '0', 'false', 'no'):
raise ValueError('Pinned abi3 wheel sets require a GIL-enabled CPython build')
if spec['musl_minimum'] is not None:
musl = detect_musl_version()
minimum = tuple(spec['musl_minimum'])
if musl is None or musl < minimum:
required = '.'.join(map(str, minimum))
found = 'not detected' if musl is None else '.'.join(map(str, musl))
raise ValueError(f'Target {target} requires musl libc >= {required}; found {found}')
for package in packages:
path = wheels/package['wheel']
if not path.is_file():
raise ValueError('Missing pinned wheel: '+str(path)+'; prepare files listed in '+str(lock_path))
resolved_wheel = path.resolve(strict=True)
if not resolved_wheel.is_relative_to(wheels) or not resolved_wheel.is_file():
raise ValueError('Wheel resolves outside the wheel directory: '+package['name'])
if hashlib.sha256(resolved_wheel.read_bytes()).hexdigest() != package['sha256']:
raise ValueError('Wheel SHA256 mismatch: '+package['name'])
validate_wheel_metadata(resolved_wheel, package['name'], package,
contracts[package['name']], spec['python'], target)
return output, lock, hashlib.sha256(lock_bytes).hexdigest()
def _pip_install_environment():
environment = os.environ.copy()
environment['PIP_CONFIG_FILE'] = os.devnull
return environment
def setup(wheels, output, target='macos-arm64-py314'):
output, lock, lock_hash = validate(wheels, output, target)
venv.EnvBuilder(with_pip=True).create(output)
requirements = output/'simulator-requirements.lock'
requirements.write_text(''.join(f"{p['name']}=={p['version']} --hash=sha256:{p['sha256']}\n" for p in lock['packages']))
python = output/'bin/python'
pip_env = _pip_install_environment()
with (output/'install.log').open('x') as log:
subprocess.run([str(python), '-I', '-m', 'pip', '--isolated', '--disable-pip-version-check',
'install', '--no-cache-dir', '--no-index', '--find-links', str(wheels.resolve()),
'--only-binary=:all:', '--require-hashes', '-r', str(requirements)],
check=True, stdout=log, stderr=subprocess.STDOUT, env=pip_env)
smoke = '''import json,sys,importlib.metadata
import unicorn,capstone
from unicorn import arm_const
cpu=unicorn.Uc(unicorn.UC_ARCH_ARM,unicorn.UC_MODE_THUMB|unicorn.UC_MODE_MCLASS)
cpu.ctl_set_cpu_model(arm_const.UC_CPU_ARM_CORTEX_M4)
print(json.dumps({"python":sys.version,"packages":{n:importlib.metadata.version(n) for n in ("unicorn","capstone")},"module_paths":{"unicorn":unicorn.__file__,"capstone":capstone.__file__}}))
'''
installed = json.loads(subprocess.check_output([str(python), '-I', '-c', smoke], text=True))
if installed['packages'] != {p['name']:p['version'] for p in lock['packages']}:
raise ValueError('Installed versions differ from wheel lock')
if not all(Path(path).resolve().is_relative_to(output) for path in installed['module_paths'].values()):
raise ValueError('Simulator modules were loaded outside the new environment')
report = dict(schema='blackwall-simulator-environment/1', lock_sha256=lock_hash,
installed=installed, wheel_directory=str(wheels.resolve()), network_install=False,
pip_configuration_ignored=True, device_access=False, simulator_complete=False)
with (output/'blackwall-environment.json').open('x') as handle:
json.dump(report, handle, indent=2)
handle.write('\n')
return report
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--wheels', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--target', choices=LOCKS, default='macos-arm64-py314',
help='explicit wheel target (default: macos-arm64-py314)')
args = parser.parse_args()
try:
report = setup(args.wheels, args.output, args.target)
except (OSError, ValueError, subprocess.CalledProcessError) as error:
parser.exit(1, f'Simulator setup failed: {error}\n')
print(json.dumps(report['installed']))
if __name__ == '__main__':
main()