xy-forever 0.1.0.dev135__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
xy_forever/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Host-side tooling for XY Forever, the OP-XY firmware and mod manager."""
2
+
3
+ import sys
4
+
5
+ __version__ = '0.1.0'
6
+
7
+ if 'unittest' in sys.modules: # a test run: no real device here or in any process it starts
8
+ from xy_forever import no_device
9
+
10
+ no_device.switch_on()
xy_forever/bounds.py ADDED
@@ -0,0 +1,14 @@
1
+ """Hard bounds on tests, processes and simulator calls (#230): a hang ends, named, within its bound.
2
+
3
+ A bound ends a hang, never a slow run: each is several times what its work takes on a busy machine, as the
4
+ CPU budgets (tests/conftest.py) are what hold a test to its speed. Never raise one to make a test pass.
5
+ """
6
+
7
+ TEST_S = 60.0 # one test with the fixtures before it (pytest-timeout's timeout, set by tests/conftest.py; HUNG)
8
+ SIM_TEST_S = 20.0 # one simulator core test (the `sim` tier, #233): hard-killed past it
9
+ SIM_DEADLINE_S = 45.0 # a test's simulator exits on its own this long after it started (xyf_sim --deadline-s); a
10
+ # sweep's one board ran past 20 s at load 48: that ended a slow run, not a hang (a sim-tier test ends at SIM_TEST_S)
11
+ SIM_CALL_S = 5.0 # one host call to the simulator, wall time (xyf-host --sim, conformance.py --sim)
12
+ SIM_CONNECT_S = 5.0 # finding the simulator's endpoint and its HELLO (xyf-host connect --sim)
13
+ WAIT_S = 10.0 # a test's wait for the simulator to reach a state
14
+ COMPILE_S = 120.0 # one CMake configure or build of a simulator variant (xy_forever/sim.py build())
xy_forever/depth.py ADDED
@@ -0,0 +1,72 @@
1
+ """The depth rule (#124, docs/SAFETY.md): no file more than MAX_FOLDERS folders below /yaffs2.
2
+
3
+ The stock dev-menu MTP walks /yaffs2 with fixed 10-entry stacks (889f1ff6): after it has walked a file 7
4
+ folders deep, the dev menu's Track 5 in that boot hangs and the next boot needs a storage repair (8: it cannot
5
+ read or delete the file; 9: it crashes). XY Forever's file service refuses deeper folders and files
6
+ (target/file_engine.hpp, file_client::rename for a folder moved deeper); the host tools check first so that
7
+ they say why. Reads, listing and removals work at any depth, so an older deep tree can still be deleted.
8
+ """
9
+
10
+ from xy_forever import usb_proto as P
11
+
12
+ MAX_FOLDERS = 6
13
+ TEXT = (
14
+ "more than %d folders below /yaffs2 (deeper hangs the dev menu's MTP, then Track 5: docs/SAFETY.md)" % MAX_FOLDERS
15
+ )
16
+
17
+
18
+ def folders(path, folder=False):
19
+ """The folders below /yaffs2 that a device path sits in (a folder: counting itself)."""
20
+ names = [n for n in path[len('/yaffs2') :].split('/') if n]
21
+ return len(names) - (0 if folder else 1)
22
+
23
+
24
+ def refusal(path, folder=False, below=0):
25
+ """None when path (a folder: with `below` levels of folders inside it) keeps the rule, else the message."""
26
+ if folders(path, folder) + below <= MAX_FOLDERS:
27
+ return None
28
+ return 'refused: %s%s is %s' % (path, ' with the folders inside it' if below else '', TEXT)
29
+
30
+
31
+ def folders_below(list_dir, folder, most=MAX_FOLDERS + 1):
32
+ """Levels of folders inside a device folder (0: none), through list_dir(path) -> (code, [(kind, size, name)]);
33
+ stops counting at most. (code, levels)."""
34
+ code, entries = list_dir(folder)
35
+ if code:
36
+ return code, 0
37
+ deepest = 0
38
+ for kind, _, name in entries:
39
+ if kind == 1 and most > 0:
40
+ code, below = folders_below(list_dir, folder + '/' + name.decode('utf-8'), most - 1)
41
+ if code:
42
+ return code, 0
43
+ deepest = max(deepest, below + 1)
44
+ return 0, min(deepest, most)
45
+
46
+
47
+ def command_refusal(args):
48
+ """xyf_host.py: the message refusing a mkdir, put, put-file, mv or cp whose path breaks the rule, else None."""
49
+ command = args.command
50
+ if command == 'mkdir':
51
+ return refusal(args.path, True)
52
+ if command in ('put', 'put-file'):
53
+ return refusal(args.remote)
54
+ return refusal(args.target.rstrip('/')) if command in ('mv', 'cp') else None
55
+
56
+
57
+ def move_note(code):
58
+ """xyf-host mv: why the device refused a move (the folder walk of file.rename), appended to its result line."""
59
+ if code != P.STATUS_NAMES.index('refused'):
60
+ return ''
61
+ return (
62
+ '\n (a folder moved deeper must keep every folder in it within %d below /yaffs2: docs/SAFETY.md)' % MAX_FOLDERS
63
+ )
64
+
65
+
66
+ def copy_refusal(list_dir, source, target):
67
+ """cp -r: 0 when the folder source, copied to target, keeps the rule; else prints why and returns the exit code."""
68
+ code, below = folders_below(list_dir, source)
69
+ deep = code or refusal(target, True, below)
70
+ if deep:
71
+ print(deep if not code else 'ls %s: %s' % (source, P.status_name(code)))
72
+ return code or (2 if deep else 0)
@@ -0,0 +1,323 @@
1
+ """`xyf dev` (#284): a full firmware image, booted once on the OP-XY as a development library entry.
2
+
3
+ Any os.ldr the device would boot from its library: usually Open-XY's own build (`python sdk.py build --stock-os STOCK
4
+ --out BUILD` writes BUILD/candidate/os.ldr and BUILD/candidate/content/: the catalog it extends and the machines' new
5
+ files), or any other image. Here:
6
+
7
+ check on the computer, before anything is sent, what the device checks of a library image when it boots one
8
+ (file_boot.cpp admit; native/ldr.cpp inspect): an LDR stream within the staging buffer, every write inside
9
+ the cold policy's allowed RAM and outside its protected ranges (target/cold.cpp), entry 0x11a00000 on a
10
+ stored instruction. The manifest's CRC-32 and SHA-256 are computed from the bytes sent
11
+ which "Open-XY build on 1.2.1" when the image is exactly Open-XY's assembly of the stock 1.2.1 image (Open-XY's
12
+ tooling/firmware.py `assemble`, inverted: the stock records plus one module record at the profile's module
13
+ base, every byte outside the profile's edit intervals the stock image's; needs the stock os.ldr and
14
+ Open-XY's profile), else "custom image". Said, never required
15
+ push one package transaction (package_store: staged, read back, published by one rename) of library entry
16
+ xyf-dev. With content: os.ldr, content/... and a manifest marking it an assembled set (generation,
17
+ needs_os, profile), so the content switch installs exactly its content/ files over the official set; its
18
+ content retained as blobs. Without: a plain firmware entry, booted with the official content. Replaced on
19
+ every push; top-level files that did not change are moved over on the device, not sent
20
+ boot menu.converge mode 2 (moddev.py): the base's content set first when it has none (#183's job: an OP-XY
21
+ that never saved mods; [content], once), the content switch, then the boot once; nothing saved changes, and
22
+ the next plain power-on converges back to the saved setup (#204)
23
+
24
+ Every entry goes through the device's own checks too (the content switch's rules, the boot's admission)."""
25
+
26
+ import hashlib
27
+ import json
28
+ import zlib
29
+ from pathlib import Path
30
+
31
+ from . import moddev, package_records, package_store
32
+ from .device_client import SLOTS, current_state
33
+ from .ldr import parse_ldr, validate_memory
34
+ from .xyf_entry import read_files_sha256
35
+
36
+ STOCK_SHA256 = '60358afdaa9b58ed40411602f6d5d4e1e3e02553ff2da7e25038e71dd002b52f' # stock OS 1.2.1 (stock_facts.json)
37
+ STOCK_BYTES = 2373336
38
+ PROFILE = 'opxy-1.2.1' # Open-XY's profile of it: profiles/opxy-1.2.1.json in an Open-XY checkout
39
+ ENTRY = 'xyf-dev'
40
+ NAME = 'Development build (xyf)'
41
+ ENTRY_POINT = 0x11A00000
42
+ STAGING_BYTES = 0x7E0000 # file_boot.hpp staging_bytes: admit takes at most this less 512 bytes
43
+ # target/cold.cpp's cold policy (allowed, protected_ranges) in the product build (XYF_STACK_END: xyf_build.WIDE_STACK_END)
44
+ ALLOWED = ((0x08000000, 0x08040000), (0x11800000, 0x11C00000), (0x80000000, 0x90000000))
45
+ PROTECTED = (
46
+ (0x0803E0C0, 0x0803E142),
47
+ (0x11803000, 0x11804000),
48
+ (0x8803D000, 0x8803D02A),
49
+ (0x88A346A6, 0x88A3481C),
50
+ (0x88A34AEC, 0x88A34D6C),
51
+ (0x8A000000, 0x8A800000),
52
+ (0x8AB00000, 0x8AB84000),
53
+ (0x8B000000, 0x8B800000),
54
+ )
55
+ OPEN_XY, CUSTOM = 'Open-XY build on 1.2.1', 'custom image'
56
+ CONTENT_STATE = '/yaffs2/xy-forever/content-state.txt'
57
+
58
+
59
+ class Refused(Exception):
60
+ """What is given (or the OP-XY's state) is not what xyf dev boots: the message says why, in plain words."""
61
+
62
+
63
+ def sha256(data):
64
+ return hashlib.sha256(data).hexdigest()
65
+
66
+
67
+ # -- on the computer --------------------------------------------------------------------------------------
68
+ def candidate(folder):
69
+ """The candidate folder of an `sdk.py build` output folder (or any folder holding os.ldr)."""
70
+ folder = Path(folder)
71
+ for found in (folder / 'candidate', folder):
72
+ if (found / 'os.ldr').is_file():
73
+ return found
74
+ raise Refused(
75
+ '%s holds no candidate/os.ldr or os.ldr: give the folder `sdk.py build --out FOLDER` wrote, or an os.ldr'
76
+ % folder
77
+ )
78
+
79
+
80
+ def read_build(folder):
81
+ """(os.ldr bytes, {path under content/: bytes}) of a build's candidate folder, or of an os.ldr file (no content)."""
82
+ if Path(folder).is_file():
83
+ return Path(folder).read_bytes(), {}
84
+ found = candidate(folder)
85
+ content = found / 'content'
86
+ others = sorted(p.name for p in found.iterdir() if p.name not in ('os.ldr', 'content'))
87
+ if others:
88
+ raise Refused('%s holds files xyf dev does not know: %s' % (found, ', '.join(others)))
89
+ files = {}
90
+ if content.is_dir():
91
+ files = {p.relative_to(content).as_posix(): p.read_bytes() for p in sorted(content.rglob('*')) if p.is_file()}
92
+ return (found / 'os.ldr').read_bytes(), files
93
+
94
+
95
+ def read_profile(sdk):
96
+ """Open-XY's profile of stock OS 1.2.1 from an Open-XY checkout."""
97
+ path = Path(sdk) / 'profiles' / (PROFILE + '.json')
98
+ try:
99
+ profile = json.loads(path.read_text(encoding='utf-8'))
100
+ except (OSError, ValueError):
101
+ raise Refused('no Open-XY profile at %s: run xyf from your Open-XY checkout or give --sdk DIR' % path) from None
102
+ if profile.get('stock_sha256') != STOCK_SHA256:
103
+ raise Refused('%s is not the profile of stock OS 1.2.1' % path)
104
+ return profile
105
+
106
+
107
+ def read_stock(path):
108
+ """The stock OS 1.2.1 os.ldr at path, checked by size and SHA-256."""
109
+ try:
110
+ stock = Path(path).read_bytes()
111
+ except OSError:
112
+ raise Refused('no stock OS 1.2.1 at %s: run `xyf stock-os` (it copies it from your OP-XY)' % path) from None
113
+ if len(stock) != STOCK_BYTES or sha256(stock) != STOCK_SHA256:
114
+ raise Refused('%s is not the stock OS 1.2.1 os.ldr (size or SHA-256 differs)' % path)
115
+ return stock
116
+
117
+
118
+ def check_image(image):
119
+ """Refused unless the device would admit image from its library (file_boot.cpp admit, native/ldr.cpp inspect)."""
120
+ if not 32 <= len(image) <= STAGING_BYTES - 512:
121
+ raise Refused('the os.ldr is %d bytes: XY Forever boots 32 to %d' % (len(image), STAGING_BYTES - 512))
122
+ try:
123
+ records = parse_ldr(image)
124
+ except ValueError as error:
125
+ raise Refused('the os.ldr is not an OS image (%s)' % error) from None
126
+ if records[-1].target != ENTRY_POINT:
127
+ raise Refused(
128
+ 'the os.ldr starts at %#x: XY Forever boots images that start at %#x' % (records[-1].target, ENTRY_POINT)
129
+ )
130
+ try:
131
+ validate_memory(records, ALLOWED, PROTECTED)
132
+ except ValueError as error:
133
+ raise Refused('the os.ldr writes where XY Forever never loads an image (%s)' % error) from None
134
+
135
+
136
+ def open_xy_build(image, stock, profile):
137
+ """True when image is exactly Open-XY's assembly of stock: the stock records with the profile's edits, plus one
138
+ module record at the profile's module base before FINAL, and nothing else changed."""
139
+ blocks, records = parse_ldr(stock), parse_ldr(image)
140
+ if len(blocks) != profile['stock_records'] or len(records) != len(blocks) + 1:
141
+ return False
142
+ at, module = blocks[-1].offset, records[-2]
143
+ if (
144
+ module.offset != at
145
+ or module.flags != 4
146
+ or module.target != profile['module_base']
147
+ or not 0 < module.count <= profile['reserved_bytes']
148
+ or len(image) != len(stock) + 16 + module.count
149
+ ):
150
+ return False
151
+ restored = bytearray(image[:at] + image[at + 16 + module.count :])
152
+ restored[:16] = stock[:16]
153
+ for patch in profile['patches']:
154
+ offset = int(patch['file_offset'], 16)
155
+ restored[offset : offset + patch['length']] = bytes.fromhex(patch['before'])
156
+ return restored == stock
157
+
158
+
159
+ def which(image, stock_path, sdk):
160
+ """OPEN_XY when image is Open-XY's build on the stock image at stock_path with sdk's profile, else CUSTOM (also
161
+ when either is not there to compare with)."""
162
+ try:
163
+ return OPEN_XY if open_xy_build(image, read_stock(stock_path), read_profile(sdk)) else CUSTOM
164
+ except Refused:
165
+ return CUSTOM
166
+
167
+
168
+ def entry_files(image, content, kind=CUSTOM, needs_os=None):
169
+ """The library entry: os.ldr, content/..., manifest.json and files.sha256. With content, an assembled set (its
170
+ content/ files go over the official set); without, a plain firmware entry (the official content)."""
171
+ digest = sha256(image)
172
+ files = {'os.ldr': image, **{'content/' + rel: data for rel, data in content.items()}}
173
+ fields = dict(
174
+ type='firmware',
175
+ name=NAME,
176
+ kind='open-xy' if kind == OPEN_XY else 'custom',
177
+ bytes=len(image),
178
+ crc32='%08x' % (zlib.crc32(image) & 0xFFFFFFFF),
179
+ sha256=digest,
180
+ )
181
+ if content:
182
+ fields.update(needs_os=needs_os or STOCK_SHA256, generation='dev-' + digest[:12], profile=PROFILE)
183
+ files[package_records.NATIVE] = package_records.document(fields)
184
+ try:
185
+ files['files.sha256'] = package_store.list_text(files)
186
+ package_store.validate(files)
187
+ except ValueError as error: # a path the package rules refuse (ListError, StoreError)
188
+ raise Refused('the build cannot be a library entry: %s' % error) from None
189
+ return files
190
+
191
+
192
+ # -- on the OP-XY -----------------------------------------------------------------------------------------
193
+ def stock_entries(dev, needs_os=None):
194
+ """The library entries whose os.ldr is needs_os (by their manifest's sha256; no assembled set), or Refused."""
195
+ code, entries = dev.list_dir(package_store.LIBRARY)
196
+ if code:
197
+ raise Refused('the library could not be read (%s)' % moddev.plain(code))
198
+ found = []
199
+ for kind, _, raw in entries:
200
+ name = raw.decode('utf-8', 'replace')
201
+ if kind != 1 or name == ENTRY:
202
+ continue
203
+ for record in (package_records.NATIVE, package_records.LEGACY):
204
+ code, data = dev.read_all('%s/%s/%s' % (package_store.LIBRARY, name, record), limit=4096)
205
+ if code:
206
+ continue
207
+ try:
208
+ fields = package_records.parse(data, record)
209
+ except ValueError:
210
+ fields = {}
211
+ if fields.get('sha256') == (needs_os or STOCK_SHA256) and 'generation' not in fields:
212
+ found.append(name)
213
+ break
214
+ if not found:
215
+ raise Refused("the OP-XY's library has no stock OS 1.2.1 (XY Forever adds it on its first start)")
216
+ return found
217
+
218
+
219
+ def preflight(dev, needs_os=None):
220
+ """Refused when xyf-dev is the OP-XY's default. True when the boot once starts with the content set's job: the
221
+ official content and no stock OS 1.2.1 entry with a content list (an OP-XY that never saved mods; #183)."""
222
+ slots = {}
223
+ for path in SLOTS:
224
+ code, body = dev.read_file(path)
225
+ slots[path] = body if code == 0 else None
226
+ state = current_state(slots)
227
+ if state and state[2].get('default') == ENTRY:
228
+ raise Refused('%s is the default on the OP-XY: choose another default first' % ENTRY)
229
+ code, head = dev.read_file(CONTENT_STATE, 0, 256)
230
+ if code == 0 and b'state=official' not in head:
231
+ return False
232
+ return not any(
233
+ dev.read_file('%s/%s/content.sha256' % (package_store.LIBRARY, b), 0, 16)[0] == 0
234
+ for b in stock_entries(dev, needs_os)
235
+ )
236
+
237
+
238
+ def push(dev, files, detail=lambda line: None, kind=CUSTOM):
239
+ """One package transaction: the content retained as blobs, then the entry published. The phase's note."""
240
+ target = '%s/%s' % (package_store.LIBRARY, ENTRY)
241
+ content = [(sha, rel[len('content/') :]) for sha, rel in read_files_sha256(files['files.sha256'])]
242
+ content = [(sha, rel) for sha, rel in content if ('content/' + rel) in files]
243
+ with package_store.Session(dev) as session:
244
+ old = session.read(target + '/files.sha256', optional=True)
245
+ before = {rel: sha for sha, rel in read_files_sha256(old)} if old else {}
246
+ keep = [ # moved over on the device: top-level files only (publish's scratch has no subfolders to move into)
247
+ rel
248
+ for rel, data in files.items()
249
+ if '/' not in rel and rel != 'files.sha256' and before.get(rel) == sha256(data)
250
+ ]
251
+ session.retain(content, {rel: files['content/' + rel] for _, rel in content})
252
+ session.publish(target, files, keep=keep)
253
+ removed = session.collect()
254
+ sent = [rel for rel in files if rel not in keep]
255
+ detail('%s: sent %s; kept %d; blobs collected %d' % (ENTRY, ', '.join(sorted(sent)), len(keep), removed))
256
+ image = 'os.ldr unchanged' if 'os.ldr' in keep else 'os.ldr %d KB' % (len(files['os.ldr']) // 1024)
257
+ total = sum(1 for rel in files if rel.startswith('content/'))
258
+ changed = sum(1 for rel in sent if rel.startswith('content/'))
259
+ content = '%d of %d content files sent' % (changed, total) if total else 'the official content'
260
+ return '%s: %s, %s, %s' % (ENTRY, kind, image, content)
261
+
262
+
263
+ def start(dev):
264
+ """menu.converge mode 2 of the entry: None, or the phase's refusal note."""
265
+ code, _ = moddev.patient(dev, lambda: moddev.converge(dev, moddev.ONCE, ENTRY))
266
+ return 'refused: %s' % moddev.plain(code) if code else None
267
+
268
+
269
+ def content(dev, detail=lambda line: None, poll=0.25):
270
+ """The boot once's first job, the base's content set (#183): (True, note) once it is done, else (False, why)."""
271
+ refused = start(dev)
272
+ if refused:
273
+ return False, refused
274
+ seen, done = None, (True, 'recorded the official 1.2.1 content (once)')
275
+ while True:
276
+ try:
277
+ code, f = moddev.converge(dev, moddev.REPORT)
278
+ except (OSError, TimeoutError): # USB went away: past the content set, the menu closed to start the boot
279
+ return done
280
+ if code:
281
+ return False, moddev.plain(code)
282
+ if f['state'] == moddev.ENDED:
283
+ return False, 'the OP-XY stayed in its menu: %s' % (f['reason'] or 'no reason given')
284
+ if f['state'] == moddev.BOOTING or (seen and f['job'] != seen):
285
+ return done
286
+ if f['job']:
287
+ code, j = moddev.MS.job_status(dev, f['job'])
288
+ if not code and j['detail'].startswith('content '):
289
+ if j['phase'] == moddev.MS.DONE:
290
+ return done
291
+ seen = f['job']
292
+ detail('job %d (content set): %s' % (f['job'], moddev.MS.describe(j)))
293
+ moddev.transport.pause(dev.t, poll)
294
+
295
+
296
+ def boot(dev, detail=lambda line: None, started=False):
297
+ """menu.converge mode 2 of the entry (unless started), followed until USB goes away: (booted, the phase's note)."""
298
+ refused = None if started else start(dev)
299
+ if refused:
300
+ return False, refused
301
+ booted, why = moddev.follow(dev, detail)
302
+ if not booted:
303
+ return False, why
304
+ return True, '%s started once; the next plain start goes back to the saved setup' % ENTRY
305
+
306
+
307
+ def run(dev, files, out=print, detail=lambda line: None, kind=CUSTOM, content_first=False):
308
+ """[push], [content] (content_first: the base's content set, once), [boot], total on a connected, ready OP-XY. The
309
+ exit code: 0 booted, 1 not."""
310
+ phases = moddev.Phases(out)
311
+
312
+ def pushed():
313
+ try:
314
+ return True, push(dev, files, detail, kind)
315
+ except package_store.StoreError as error: # the OP-XY refused a step of the transaction
316
+ return False, 'failed: %s' % error
317
+
318
+ booted = phases.run('push', pushed)
319
+ if booted and content_first:
320
+ booted = phases.run('content', lambda: content(dev, detail))
321
+ booted = booted and phases.run('boot', lambda: boot(dev, detail, started=content_first))
322
+ phases.total()
323
+ return 0 if booted else 1