#!/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(" 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("" % (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)))