Files
mandy/tools/abc_file.py
ubiquitarianism 54374cf53e Button prompts that follow a device switch during play
tools/live_prompt_glyphs.py builds ps_live_prompt_glyphs.gfx over the
title's glyph movie on the player's PC: each Main_Button_N sprite holds the
PlayStation and the keyboard picture (the first keyboard piece named k),
and the title's ActionScript block gets three static Number slots on Main
(lnLo, lnFamily, lnHi, the outer two sentinels), four static methods that
show the pad or the keyboard pieces when a prompt is made and on each frame
while it is on the stage, and a call from SpriteAsset's constructor, the
base of exactly the 38 symbol classes. Everything added is in try blocks.
tools/abc_file.py reads and writes ABC byte for byte. Both sets and the
code fit the 28,148 bytes with 1,057 to spare on the user's movie.

leonida-hle serves the live movie for a PlayStation pad or the keyboard
(unless LEONIDA_PROMPTS forces a family; LEONIDA_PROMPTS_LIVE=0 restores
one family's movie, LEONIDA_PROMPTS_PAD=xbox keeps a keyboard start on the
keyboard movie), with lnFamily's default set to the family in use, then a
below-normal thread finds the slots by their sentinels through
ReadProcessMemory and writes each change of the active family.

prompt_glyph_movies.py builds the live movie too (only over the title's).
Tested: the added code checked path by path and run in an interpreter over
fake display objects, the sentinel scan and writes on a fake heap. Not yet
run in the title.
2026-11-29 22:24:55 -05:00

384 lines
15 KiB
Python

#!/usr/bin/env python3
"""Reads and writes ActionScript 3 byte code files (ABC, the body of a SWF/GFX DoABC tag). Standard library only.
`parse(data)` gives an `Abc` whose constant pool, methods, metadata, classes, scripts and method bodies are plain
lists; `Abc.serialize()` writes it back byte for byte (`parse(data).serialize() == data` for a file written with the
shortest variable-length numbers, as compilers write them). Entries added at the end of a list keep every index the
file already uses, which is how tools/live_prompt_glyphs.py adds code to a movie built on the player's PC.
Only the layout is handled here (AVM2 overview, chapter 4); instructions are bytes the caller writes. `describe`
prints names and counts only, never code, for a look at a movie that stays on the player's PC.
"""
import struct
import sys
# Multiname kinds and the u30 fields each one has.
MULTINAME_FIELDS = {
0x07: 2, 0x0D: 2, # QName(A): namespace, name
0x0F: 1, 0x10: 1, # RTQName(A): name
0x11: 0, 0x12: 0, # RTQNameL(A)
0x09: 2, 0x0E: 2, # Multiname(A): name, namespace set
0x1B: 1, 0x1C: 1, # MultinameL(A): namespace set
}
TYPENAME = 0x1D # a parameterised type: name, count, parameters
HAS_OPTIONAL = 0x08
HAS_PARAM_NAMES = 0x80
NEED_ACTIVATION = 0x02
INSTANCE_PROTECTED_NS = 0x08
ATTR_METADATA = 0x4
TRAIT_SLOT, TRAIT_METHOD, TRAIT_GETTER, TRAIT_SETTER, TRAIT_CLASS, TRAIT_FUNCTION, TRAIT_CONST = 0, 1, 2, 3, 4, 5, 6
# Constant kinds (a slot's default value).
CONST_INT, CONST_UINT, CONST_DOUBLE, CONST_UTF8 = 0x03, 0x04, 0x06, 0x01
CONST_TRUE, CONST_FALSE, CONST_NULL, CONST_UNDEFINED = 0x0B, 0x0A, 0x0C, 0x00
# Namespace kinds.
NS_PACKAGE, NS_PRIVATE = 0x16, 0x05
def u30(v):
"""A variable-length unsigned number (u30, also u32 and the bits of an s32), shortest form."""
if v < 0:
v &= 0xFFFFFFFF
out = bytearray()
while True:
byte = v & 0x7F
v >>= 7
if v:
out.append(byte | 0x80)
else:
out.append(byte)
return bytes(out)
class Reader:
def __init__(self, data, at=0):
self.data = data
self.at = at
def u8(self):
self.at += 1
return self.data[self.at - 1]
def u16(self):
self.at += 2
return struct.unpack_from("<H", self.data, self.at - 2)[0]
def u30(self):
value = shift = 0
for _ in range(5):
byte = self.u8()
value |= (byte & 0x7F) << shift
shift += 7
if not byte & 0x80:
return value
return value
def raw(self, n):
if self.at + n > len(self.data):
raise ValueError("ABC: %d bytes asked for at %d, past the end (%d)" % (n, self.at, len(self.data)))
self.at += n
return bytes(self.data[self.at - n:self.at])
def u30s(self, n):
return [self.u30() for _ in range(n)]
class Trait:
"""One trait: `name` (multiname), `kind` (low 4 bits), `attrs` (high 4), `data` (the kind's u30 fields, and for
a slot or constant with a value its value kind as the last entry), `metadata` (indices)."""
def __init__(self, name, kind, data, attrs=0, metadata=()):
self.name, self.kind, self.data, self.attrs, self.metadata = name, kind, list(data), attrs, list(metadata)
@classmethod
def read(cls, r):
name = r.u30()
byte = r.u8()
kind, attrs = byte & 0x0F, byte >> 4
if kind in (TRAIT_SLOT, TRAIT_CONST):
data = r.u30s(3) # slot id, type name, value index
if data[2]:
data.append(r.u8())
elif kind in (TRAIT_METHOD, TRAIT_GETTER, TRAIT_SETTER, TRAIT_CLASS, TRAIT_FUNCTION):
data = r.u30s(2) # slot or dispatch id, class or method index
else:
raise ValueError("ABC: trait kind %d" % kind)
metadata = r.u30s(r.u30()) if attrs & ATTR_METADATA else []
return cls(name, kind, data, attrs, metadata)
def write(self):
out = bytearray(u30(self.name) + bytes([self.kind | self.attrs << 4]))
if self.kind in (TRAIT_SLOT, TRAIT_CONST):
out += b"".join(u30(v) for v in self.data[:3])
if self.data[2]:
out.append(self.data[3])
else:
out += b"".join(u30(v) for v in self.data)
if self.attrs & ATTR_METADATA:
out += u30(len(self.metadata)) + b"".join(u30(v) for v in self.metadata)
return bytes(out)
def read_traits(r):
return [Trait.read(r) for _ in range(r.u30())]
def write_traits(traits):
return u30(len(traits)) + b"".join(t.write() for t in traits)
class Method:
def __init__(self, params, returns, name, flags, options=(), param_names=()):
self.params, self.returns, self.name, self.flags = list(params), returns, name, flags
self.options, self.param_names = list(options), list(param_names)
@classmethod
def read(cls, r):
count = r.u30()
returns = r.u30()
params = r.u30s(count)
name = r.u30()
flags = r.u8()
options = [(r.u30(), r.u8()) for _ in range(r.u30())] if flags & HAS_OPTIONAL else []
names = r.u30s(count) if flags & HAS_PARAM_NAMES else []
return cls(params, returns, name, flags, options, names)
def write(self):
out = bytearray(u30(len(self.params)) + u30(self.returns) + b"".join(u30(p) for p in self.params))
out += u30(self.name) + bytes([self.flags])
if self.flags & HAS_OPTIONAL:
out += u30(len(self.options)) + b"".join(u30(v) + bytes([k]) for v, k in self.options)
if self.flags & HAS_PARAM_NAMES:
out += b"".join(u30(n) for n in self.param_names)
return bytes(out)
class Instance:
def __init__(self, name, super_name, flags, protected_ns, interfaces, iinit, traits):
self.name, self.super_name, self.flags, self.protected_ns = name, super_name, flags, protected_ns
self.interfaces, self.iinit, self.traits = list(interfaces), iinit, list(traits)
@classmethod
def read(cls, r):
name, super_name, flags = r.u30(), r.u30(), r.u8()
protected_ns = r.u30() if flags & INSTANCE_PROTECTED_NS else 0
interfaces = r.u30s(r.u30())
return cls(name, super_name, flags, protected_ns, interfaces, r.u30(), read_traits(r))
def write(self):
out = bytearray(u30(self.name) + u30(self.super_name) + bytes([self.flags]))
if self.flags & INSTANCE_PROTECTED_NS:
out += u30(self.protected_ns)
out += u30(len(self.interfaces)) + b"".join(u30(i) for i in self.interfaces)
return bytes(out + u30(self.iinit) + write_traits(self.traits))
class Body:
def __init__(self, method, max_stack, locals_, init_scope, max_scope, code, exceptions=(), traits=()):
self.method, self.max_stack, self.locals, self.init_scope, self.max_scope = (
method, max_stack, locals_, init_scope, max_scope)
self.code, self.exceptions, self.traits = bytes(code), list(exceptions), list(traits)
@classmethod
def read(cls, r):
head = r.u30s(5)
code = r.raw(r.u30())
exceptions = [tuple(r.u30s(5)) for _ in range(r.u30())]
return cls(*head, code, exceptions, read_traits(r))
def write(self):
out = bytearray(b"".join(u30(v) for v in (self.method, self.max_stack, self.locals, self.init_scope,
self.max_scope)))
out += u30(len(self.code)) + self.code
out += u30(len(self.exceptions)) + b"".join(b"".join(u30(v) for v in e) for e in self.exceptions)
return bytes(out + write_traits(self.traits))
class Abc:
"""An ABC file. Pool lists hold entry 0 too (the implicit "none" every pool starts with), so a list index is the
index the code uses: `ints`, `uints` (the encoded bytes of each), `doubles` (8 raw bytes each), `strings` (bytes),
`namespaces` ((kind, string)), `nssets` ([namespace, ...]), `multinames` ((kind, field, ...))."""
def __init__(self):
self.minor, self.major = 16, 46
self.ints, self.uints, self.doubles = [None], [None], [None]
self.strings, self.namespaces, self.nssets, self.multinames = [None], [None], [None], [None]
self.methods, self.metadata, self.instances, self.classes, self.scripts, self.bodies = [], [], [], [], [], []
self.empty_as_one = set() # pools with no entries whose count the file wrote as 1, not 0
# ---- reading
@classmethod
def parse(cls, data):
abc, r = cls(), Reader(data)
abc.minor, abc.major = r.u16(), r.u16()
def pool(key, read):
n = r.u30()
if n == 1:
abc.empty_as_one.add(key)
return [None] + [read() for _ in range(max(n - 1, 0))]
def number():
start = r.at
r.u30()
return bytes(data[start:r.at])
abc.ints = pool("ints", number)
abc.uints = pool("uints", number)
abc.doubles = pool("doubles", lambda: r.raw(8))
abc.strings = pool("strings", lambda: r.raw(r.u30()))
abc.namespaces = pool("namespaces", lambda: (r.u8(), r.u30()))
abc.nssets = pool("nssets", lambda: r.u30s(r.u30()))
def multiname():
kind = r.u8()
if kind == TYPENAME:
name, count = r.u30(), r.u30()
return (kind, name, count) + tuple(r.u30s(count))
if kind not in MULTINAME_FIELDS:
raise ValueError("ABC: multiname kind %#x" % kind)
return (kind,) + tuple(r.u30s(MULTINAME_FIELDS[kind]))
abc.multinames = pool("multinames", multiname)
abc.methods = [Method.read(r) for _ in range(r.u30())]
abc.metadata = []
for _ in range(r.u30()):
name, count = r.u30(), r.u30()
abc.metadata.append((name, r.u30s(count), r.u30s(count)))
count = r.u30()
abc.instances = [Instance.read(r) for _ in range(count)]
abc.classes = [(r.u30(), read_traits(r)) for _ in range(count)]
abc.scripts = [(r.u30(), read_traits(r)) for _ in range(r.u30())]
abc.bodies = [Body.read(r) for _ in range(r.u30())]
if r.at != len(data):
raise ValueError("ABC: %d bytes after the method bodies" % (len(data) - r.at))
return abc
# ---- writing
def serialize(self):
out = bytearray(struct.pack("<HH", self.minor, self.major))
def pool(items, write, key):
nonlocal out
rest = items[1:]
out += u30(len(rest) + 1 if rest or key in self.empty_as_one else 0)
for item in rest:
out += write(item)
pool(self.ints, key='ints', write=lambda b: b)
pool(self.uints, key='uints', write=lambda b: b)
pool(self.doubles, key='doubles', write=lambda b: b)
pool(self.strings, key='strings', write=lambda s: u30(len(s)) + s)
pool(self.namespaces, key='namespaces', write=lambda ns: bytes([ns[0]]) + u30(ns[1]))
pool(self.nssets, key='nssets', write=lambda s: u30(len(s)) + b"".join(u30(v) for v in s))
def multiname(m):
if m[0] == TYPENAME:
return bytes([m[0]]) + b"".join(u30(v) for v in m[1:])
return bytes([m[0]]) + b"".join(u30(v) for v in m[1:])
pool(self.multinames, key='multinames', write=multiname)
out += u30(len(self.methods)) + b"".join(m.write() for m in self.methods)
out += u30(len(self.metadata))
for name, keys, values in self.metadata:
out += u30(name) + u30(len(keys)) + b"".join(u30(k) for k in keys) + b"".join(u30(v) for v in values)
out += u30(len(self.instances)) + b"".join(i.write() for i in self.instances)
out += b"".join(u30(cinit) + write_traits(traits) for cinit, traits in self.classes)
out += u30(len(self.scripts)) + b"".join(u30(init) + write_traits(traits) for init, traits in self.scripts)
out += u30(len(self.bodies)) + b"".join(b.write() for b in self.bodies)
return bytes(out)
# ---- adding (at the end of each list, so the indices already used stay)
def string(self, text):
raw = text.encode("utf-8") if isinstance(text, str) else bytes(text)
if raw in self.strings[1:]:
return self.strings.index(raw, 1)
self.strings.append(raw)
return len(self.strings) - 1
def namespace(self, kind, name):
entry = (kind, self.string(name))
if kind != NS_PRIVATE and entry in self.namespaces[1:]: # each private namespace is its own
return self.namespaces.index(entry, 1)
self.namespaces.append(entry)
return len(self.namespaces) - 1
def qname(self, ns, name):
entry = (0x07, ns, self.string(name))
if entry in self.multinames[1:]:
return self.multinames.index(entry, 1)
self.multinames.append(entry)
return len(self.multinames) - 1
def double(self, value, unique=False):
raw = struct.pack("<d", value)
if not unique and raw in self.doubles[1:]:
return self.doubles.index(raw, 1)
self.doubles.append(raw)
return len(self.doubles) - 1
def method(self, params=0, name=0, flags=0):
self.methods.append(Method([0] * params, 0, name, flags))
return len(self.methods) - 1
def body_of(self, method):
for body in self.bodies:
if body.method == method:
return body
raise KeyError("no body for method %d" % method)
# ---- names
def text(self, index):
return self.strings[index].decode("utf-8", "replace") if index else "*"
def name(self, multiname):
"""`package:name` of a QName, the name alone for the others."""
if not multiname:
return "*"
m = self.multinames[multiname]
if m[0] in (0x07, 0x0D):
ns = self.text(self.namespaces[m[1]][1]) if m[1] else ""
return "%s:%s" % (ns, self.text(m[2])) if ns else self.text(m[2])
if m[0] in (0x09, 0x0E, 0x0F, 0x10):
return self.text(m[1])
if m[0] == TYPENAME:
return "%s.<%s>" % (self.name(m[1]), ",".join(self.name(p) for p in m[3:]))
return "?"
def find_class(self, name):
"""The class index of a class named `name` (`package:Class`, or the bare class name)."""
for i, inst in enumerate(self.instances):
full = self.name(inst.name)
if full == name or full.split(":")[-1] == name:
return i
raise KeyError(name)
def parse(data):
return Abc.parse(data)
def describe(abc, out=sys.stdout):
"""Counts and the names of classes, their bases and traits: no code, no strings beyond names."""
out.write("ABC %d.%d: %d ints, %d uints, %d doubles, %d strings, %d namespaces, %d multinames\n" % (
abc.major, abc.minor, len(abc.ints) - 1, len(abc.uints) - 1, len(abc.doubles) - 1, len(abc.strings) - 1,
len(abc.namespaces) - 1, len(abc.multinames) - 1))
out.write("%d methods, %d bodies (%d bytes of code), %d classes, %d scripts\n" % (
len(abc.methods), len(abc.bodies), sum(len(b.code) for b in abc.bodies), len(abc.instances),
len(abc.scripts)))
for i, inst in enumerate(abc.instances):
body = abc.body_of(inst.iinit)
out.write("class %d %s : %s iinit %d (%d bytes) %d instance traits, %d class traits\n" % (
i, abc.name(inst.name), abc.name(inst.super_name), inst.iinit, len(body.code), len(inst.traits),
len(abc.classes[i][1])))
for i, (init, traits) in enumerate(abc.scripts):
out.write("script %d init %d: %s\n" % (i, init, ", ".join(abc.name(t.name) for t in traits)))