Files
neoLegacy-mac/tests/test_reconstructed_swf_as3_bitmap_data.py
2026-07-19 03:20:22 -05:00

409 lines
20 KiB
Python

"""Runtime tests for the reconstructed swf_as3_bitmap_data translation unit.
RED STATE: swf_as3_bitmap_data.c / swf_as3_bitmap_data.h do not exist yet, so
setUpClass raises "missing swf_as3_bitmap_data runtime inputs". Every assertion
below is grounded in a specific line of
iggy-decompiled/raw/durango/swf_as3_bitmap_data.c (cited inline) so a faithful
DURANGO reconstruction turns these green.
swf_as3_bitmap_data is Iggy's AS3 / AVM2 flash.display.BitmapData class. It
exports EXACTLY 34 entry points on all four platforms and owns NO externally
named data global (the two durango 'R' ??_C@ COMDATs are the "dd?bu" parse
format literal and the __FILE__ path -- MSVC read-only artifacts).
BODY CLASSIFICATION -- the 34 methods are a MIX, not uniform:
SIX real bodies: __construct, __finalize, clone, get_width, get_height,
get_transparent.
TWENTY-EIGHT stubs (each raises as3vm_exception_GC(vm, 0x74) and nothing else):
get_rect, getPixel, getPixel32, getPixels, setPixel,
setPixel32, setPixels, fillRect, floodFill, copyPixels,
copyChannel, colorTransform, draw, dispose, lock, unlock,
applyFilter, compare, hitTest, merge, noise, paletteMap,
perlinNoise, pixelDissolve, scroll, threshold,
generateFilterRect, getColorBoundsRect.
dispose / lock / unlock / get_rect are STUBS, NOT accessors.
BitmapData object field map (durango 64-bit byte offsets; 32-bit ps3/vita in
parens):
0x27 (0x17) source SWF image ptr (0 => module owns the pixel buffer)
0x2f (0x1b) width (int32)
0x33 (0x1f) height (int32)
0x37 (0x23) pixel buffer ptr
0x3f (0x27) transparent / opaque byte
CALL-FRAME MODEL (durango 64-bit; the runtime test builds ONLY the durango
dylib so the 64-bit layout is authoritative, cross-checked vs the 32-bit vita
raw): frame[0]=vm, frame[1]=&result slot, frame[2]=argc, frame[3]=&this-slot
(which holds the RAW object pointer -- a getter reads (*this_slot)+offset, with
NO node+1 tag).
WHAT IS PINNED (real, deterministic DURANGO behavior):
- get_width / get_height box (field << 1) into *frame[1] (raw:273, 312).
- get_transparent stores one of two DISTINCT, STABLE singleton pointers inside
the imported as3vm_truefalse_storage block, keyed on the byte at obj+0x3f
(raw:297-301).
- __construct with a zeroed source-image chain allocates a w*h*4 buffer via
iggy_malloc_fileline and floods every pixel with the fill colour, writing
width/height/transparent (raw:47-60); bad args raise exception 0x78
(raw:29-64).
- __finalize frees the pixel buffer via iggy_free_alloc iff it is non-null
(raw:76-79).
- clone allocates a destination via as3vm_make_object_no_constructor_GC, copies
the fields, and (source==0) mallocs + memcpys the pixel buffer (raw:105-119).
- all 28 stubs raise exception 0x74 and touch nothing else (raw:90 et al).
DEFERRED (flagged structural, NOT exercised): __construct's source-image
adoption branch (the vm->loader graph walk raw:37-45); the reconstruction's
exact choice of 0x37-vs-0x38 for the __finalize buffer probe (a one-byte
decompiler skew -- pinned only as "non-null buffer => free").
Full-suite runs use python3.12 (`python3.12 -u -m unittest discover -s tests -p
'test_*.py' -v`): the machine python3 is 3.14, which SEGFAULTs at teardown on the
full suite via an unrelated CPython ctypes-GC bug (exit 139 AFTER the last "ok"
with 0 fail/err is a teardown artifact, not a failure). Single-module runs are
fine on either interpreter.
"""
import ctypes
import shutil
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
RECONSTRUCTED = ROOT / "iggy-decompiled/src/reconstructed"
SOURCE = RECONSTRUCTED / "swf_as3_bitmap_data.c"
HEADER = RECONSTRUCTED / "swf_as3_bitmap_data.h"
SUPPORT = ROOT / "tests/support/swf_as3_bitmap_data_test_support.c"
MASK64 = (1 << 64) - 1
# BitmapData object field byte offsets (durango 64-bit; cited per test).
OBJ_SOURCE = 0x27 # source SWF image ptr; 0 => owned buffer (raw:47/107).
OBJ_WIDTH = 0x2F # width int32 (raw:31/273/312).
OBJ_HEIGHT = 0x33 # height int32 (raw:32/273).
OBJ_BUFFER = 0x37 # pixel buffer ptr (raw:51/56).
OBJ_TRANSPARENT = 0x3F # transparent / opaque byte (raw:33/298).
# The 28 "unsupported" stub exports -- each raises exception 0x74 (raw:90 et al).
STUB_METHODS = (
"get_rect", "getPixel", "getPixel32", "getPixels", "setPixel", "setPixel32",
"setPixels", "fillRect", "floodFill", "copyPixels", "copyChannel",
"colorTransform", "draw", "dispose", "lock", "unlock", "applyFilter",
"compare", "hitTest", "merge", "noise", "paletteMap", "perlinNoise",
"pixelDissolve", "scroll", "threshold", "generateFilterRect",
"getColorBoundsRect",
)
class ReconstructedSwfAs3BitmapDataTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
missing = [str(path) for path in (SOURCE, HEADER, SUPPORT)
if not path.exists()]
if missing:
raise AssertionError(
"missing swf_as3_bitmap_data runtime inputs: "
+ ", ".join(missing))
cls.temp = tempfile.TemporaryDirectory()
cls.base = Path(cls.temp.name) / "swf_as3_bitmap_data.dylib"
build = subprocess.run([
"clang", "-dynamiclib", "-std=c11", "-O2", "-Wall", "-Wextra",
"-Werror", "-Wl,-undefined,dynamic_lookup",
"-DIGGY_RECONSTRUCT_SWF_AS3_BITMAP_DATA_DURANGO=1",
"-I", str(RECONSTRUCTED),
str(SOURCE), str(SUPPORT), "-o", str(cls.base),
], capture_output=True, text=True)
if build.returncode:
raise AssertionError(build.stdout + build.stderr)
@classmethod
def tearDownClass(cls):
cls.temp.cleanup()
def setUp(self):
unique = (Path(self.temp.name) /
f"swf_as3_bitmap_data_{self._testMethodName}.dylib")
shutil.copyfile(self.base, unique)
self.lib = ctypes.CDLL(str(unique))
self._bind(self.lib)
self.lib.swf_as3_bitmap_data_test_reset()
self._keep = []
def _bind(self, lib):
void_p = ctypes.c_void_p
lib.swf_as3_bitmap_data_test_reset.restype = None
lib.swf_as3_bitmap_data_test_reset.argtypes = []
for name in ("exception", "malloc", "free", "make_object"):
fn = getattr(lib, f"swf_as3_bitmap_data_test_{name}_count")
fn.restype = ctypes.c_size_t
fn.argtypes = []
lib.swf_as3_bitmap_data_test_last_exception_code.restype = ctypes.c_int32
lib.swf_as3_bitmap_data_test_last_exception_code.argtypes = []
lib.swf_as3_bitmap_data_test_last_malloc_size.restype = ctypes.c_size_t
lib.swf_as3_bitmap_data_test_last_malloc_size.argtypes = []
for name in ("last_object", "last_free_ptr", "truefalse_base"):
fn = getattr(lib, f"swf_as3_bitmap_data_test_{name}")
fn.restype = void_p
fn.argtypes = []
lib.swf_as3_bitmap_data_test_set_parse_ret.restype = None
lib.swf_as3_bitmap_data_test_set_parse_ret.argtypes = [ctypes.c_int]
lib.swf_as3_bitmap_data_test_set_parse_values.restype = None
lib.swf_as3_bitmap_data_test_set_parse_values.argtypes = [
ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int]
# Real bodies + the 28 stubs all take the frame word (void*); __finalize
# additionally takes the object pointer. __construct/__finalize keep the
# class name directly concatenated (as3vm_BitmapData__construct, two
# underscores, no separator) -- so they are bound explicitly rather than
# through the "as3vm_BitmapData_<name>" separator form the loop uses.
for name in ("clone", "get_width", "get_height",
"get_transparent") + STUB_METHODS:
fn = getattr(lib, f"as3vm_BitmapData_{name}")
fn.restype = None
fn.argtypes = [void_p]
lib.as3vm_BitmapData__construct.restype = None
lib.as3vm_BitmapData__construct.argtypes = [void_p]
lib.as3vm_BitmapData__finalize.restype = None
lib.as3vm_BitmapData__finalize.argtypes = [void_p, void_p]
# --- buffer helpers ------------------------------------------------ #
def _buf(self, size):
buf = (ctypes.c_uint8 * size)()
self._keep.append(buf)
return buf
def _addr(self, buf):
return ctypes.addressof(buf)
def _poke_u64(self, buf, offset, value):
ctypes.c_uint64.from_buffer(buf, offset).value = value & MASK64
def _peek_u64(self, buf, offset):
return ctypes.c_uint64.from_buffer(buf, offset).value
def _frame(self, vm=0, result=0, this_slot=0, argc=0):
# durango 64-bit: +0x00 vm, +0x08 &result, +0x10 argc, +0x18 &this-slot.
frame = self._buf(0x28)
self._poke_u64(frame, 0x00, vm)
self._poke_u64(frame, 0x08, result)
ctypes.c_int32.from_buffer(frame, 0x10).value = argc
self._poke_u64(frame, 0x18, this_slot)
return frame
def _this_slot(self, obj_addr):
# frame[3] points to a word holding the RAW object pointer (no +1 tag);
# a getter reads (*this_slot) + offset (raw:273, 312).
slot = self._buf(8)
self._poke_u64(slot, 0, obj_addr)
return slot
# ------------------------------------------------------------------ #
# Accessors -- get_width / get_height box (field << 1).
# ------------------------------------------------------------------ #
def test_get_width_boxes_width_times_two(self):
# raw:312 result := *(int*)(obj+0x2f) << 1.
obj = self._buf(0x80)
ctypes.c_int32.from_buffer(obj, OBJ_WIDTH).value = 640
result = self._buf(8)
frame = self._frame(result=self._addr(result),
this_slot=self._addr(self._this_slot(self._addr(obj))))
self.lib.as3vm_BitmapData_get_width(ctypes.c_void_p(self._addr(frame)))
self.assertEqual(self._peek_u64(result, 0), 640 * 2)
def test_get_height_boxes_height_times_two(self):
# raw:273 result := *(int*)(obj+0x33) << 1.
obj = self._buf(0x80)
ctypes.c_int32.from_buffer(obj, OBJ_HEIGHT).value = 480
result = self._buf(8)
frame = self._frame(result=self._addr(result),
this_slot=self._addr(self._this_slot(self._addr(obj))))
self.lib.as3vm_BitmapData_get_height(ctypes.c_void_p(self._addr(frame)))
self.assertEqual(self._peek_u64(result, 0), 480 * 2)
def test_get_transparent_selects_two_stable_singletons(self):
# raw:297-301 transparent byte != 0 -> singleton A, == 0 -> singleton B;
# both are DISTINCT, STABLE pointers inside as3vm_truefalse_storage.
base = self.lib.swf_as3_bitmap_data_test_truefalse_base()
def call(byte):
obj = self._buf(0x80)
obj[OBJ_TRANSPARENT] = byte
result = self._buf(8)
frame = self._frame(
result=self._addr(result),
this_slot=self._addr(self._this_slot(self._addr(obj))))
self.lib.as3vm_BitmapData_get_transparent(
ctypes.c_void_p(self._addr(frame)))
return self._peek_u64(result, 0)
opaque_ptr = call(1)
transp_ptr = call(0)
self.assertNotEqual(opaque_ptr, transp_ptr)
# Stable across repeated calls (same byte -> same singleton).
self.assertEqual(call(1), opaque_ptr)
self.assertEqual(call(0), transp_ptr)
# Both land inside the 64-byte truefalse storage block.
for ptr in (opaque_ptr, transp_ptr):
self.assertGreaterEqual(ptr, base)
self.assertLess(ptr, base + 64)
# ------------------------------------------------------------------ #
# __construct -- fresh-allocation happy path + bad-args exception.
# ------------------------------------------------------------------ #
def _construct_frame(self, obj):
# __construct reads the source-image chain
# *(*(*(*obj_slot + 7) + 0x20) + 0x20) (raw:37);
# zero the tail so the walk yields 0 and takes the fresh-alloc branch.
region_b = self._buf(0x40) # *(region_b + 0x20) == 0 -> source 0.
region_a = self._buf(0x40)
self._poke_u64(region_a, 0x20, self._addr(region_b))
self._poke_u64(obj, 0x07, self._addr(region_a))
vm = self._buf(0x2600)
this_slot = self._this_slot(self._addr(obj))
frame = self._frame(vm=self._addr(vm), this_slot=self._addr(this_slot))
return frame
def test_construct_fresh_alloc_fills_buffer_and_sets_dimensions(self):
# raw:47-60 source chain == 0 -> malloc w*h*4, flood with fill colour,
# store width @0x2f, height @0x33.
self.lib.swf_as3_bitmap_data_test_set_parse_values(2, 3, 1, 0x12345678)
obj = self._buf(0x80)
frame = self._construct_frame(obj)
self.lib.as3vm_BitmapData__construct(ctypes.c_void_p(self._addr(frame)))
self.assertEqual(self.lib.swf_as3_bitmap_data_test_malloc_count(), 1)
self.assertEqual(self.lib.swf_as3_bitmap_data_test_last_malloc_size(),
2 * 3 * 4)
self.assertEqual(self.lib.swf_as3_bitmap_data_test_exception_count(), 0)
self.assertEqual(ctypes.c_int32.from_buffer(obj, OBJ_WIDTH).value, 2)
self.assertEqual(ctypes.c_int32.from_buffer(obj, OBJ_HEIGHT).value, 3)
# Every one of the 6 pixels was flooded with the fill colour.
buffer_addr = self._peek_u64(obj, OBJ_BUFFER)
self.assertNotEqual(buffer_addr, 0)
pixels = (ctypes.c_uint32 * 6).from_address(buffer_addr)
self.assertEqual(list(pixels), [0x12345678] * 6)
def test_construct_bad_arguments_raise_0x78(self):
# raw:29-64 a width past the 0xf00 clamp fails validation -> exception
# 0x78 and NO allocation.
self.lib.swf_as3_bitmap_data_test_set_parse_values(0x2000, 3, 1, 0)
obj = self._buf(0x80)
frame = self._construct_frame(obj)
self.lib.as3vm_BitmapData__construct(ctypes.c_void_p(self._addr(frame)))
self.assertEqual(self.lib.swf_as3_bitmap_data_test_exception_count(), 1)
self.assertEqual(
self.lib.swf_as3_bitmap_data_test_last_exception_code(), 0x78)
self.assertEqual(self.lib.swf_as3_bitmap_data_test_malloc_count(), 0)
def test_construct_parse_failure_raises_0x78(self):
# raw:63-64 a nonzero parser return short-circuits straight to 0x78.
self.lib.swf_as3_bitmap_data_test_set_parse_ret(1)
self.lib.swf_as3_bitmap_data_test_set_parse_values(2, 3, 1, 0)
obj = self._buf(0x80)
frame = self._construct_frame(obj)
self.lib.as3vm_BitmapData__construct(ctypes.c_void_p(self._addr(frame)))
self.assertEqual(self.lib.swf_as3_bitmap_data_test_exception_count(), 1)
self.assertEqual(
self.lib.swf_as3_bitmap_data_test_last_exception_code(), 0x78)
self.assertEqual(self.lib.swf_as3_bitmap_data_test_malloc_count(), 0)
# ------------------------------------------------------------------ #
# __finalize -- frees the owned buffer iff non-null.
# ------------------------------------------------------------------ #
def test_finalize_frees_when_buffer_present(self):
# raw:76-79 a non-null pixel buffer -> exactly one iggy_free_alloc.
obj = self._buf(0x80)
# Fill the whole 0x30..0x40 window so both the 0x37 and 0x38 decompiler
# readings of the buffer field see non-null.
for off in range(0x30, 0x40):
obj[off] = 0xFF
vm = self._buf(0x40)
self.lib.as3vm_BitmapData__finalize(
ctypes.c_void_p(self._addr(vm)), ctypes.c_void_p(self._addr(obj)))
self.assertEqual(self.lib.swf_as3_bitmap_data_test_free_count(), 1)
def test_finalize_skips_free_when_buffer_null(self):
# raw:76 a zeroed buffer field -> no free.
obj = self._buf(0x80) # already zero.
vm = self._buf(0x40)
self.lib.as3vm_BitmapData__finalize(
ctypes.c_void_p(self._addr(vm)), ctypes.c_void_p(self._addr(obj)))
self.assertEqual(self.lib.swf_as3_bitmap_data_test_free_count(), 0)
# ------------------------------------------------------------------ #
# clone -- make_object + field copy + buffer malloc/memcpy.
# ------------------------------------------------------------------ #
def test_clone_copies_dimensions_and_pixel_buffer(self):
# raw:105-119 make_object_no_constructor_GC, copy width/height/source/
# transparent, and (source==0) malloc + memcpy the 2x2 pixel buffer.
src_pixels = self._buf(0x10)
pattern = [0x0A0B0C0D, 0x11223344, 0x55667788, 0x99AABBCC]
for i, value in enumerate(pattern):
ctypes.c_uint32.from_buffer(src_pixels, i * 4).value = value
obj = self._buf(0x80)
ctypes.c_int32.from_buffer(obj, OBJ_WIDTH).value = 2
ctypes.c_int32.from_buffer(obj, OBJ_HEIGHT).value = 2
self._poke_u64(obj, OBJ_SOURCE, 0) # owned buffer path.
self._poke_u64(obj, OBJ_BUFFER, self._addr(src_pixels))
vm = self._buf(0x2600) # vm+0x25f0 == class ptr.
self._poke_u64(vm, 0x25F0, 0xC1A55)
result = self._buf(8)
frame = self._frame(vm=self._addr(vm), result=self._addr(result),
this_slot=self._addr(self._this_slot(self._addr(obj))))
self.lib.as3vm_BitmapData_clone(ctypes.c_void_p(self._addr(frame)))
self.assertEqual(self.lib.swf_as3_bitmap_data_test_make_object_count(), 1)
self.assertEqual(self.lib.swf_as3_bitmap_data_test_malloc_count(), 1)
self.assertEqual(self.lib.swf_as3_bitmap_data_test_last_malloc_size(),
2 * 2 * 4)
new_obj = self.lib.swf_as3_bitmap_data_test_last_object()
# The new object is published into the result slot (raw:119).
self.assertEqual(self._peek_u64(result, 0), new_obj & MASK64)
dst = ctypes.cast(new_obj, ctypes.POINTER(ctypes.c_uint8))
self.assertEqual(
ctypes.c_int32.from_address(new_obj + OBJ_WIDTH).value, 2)
self.assertEqual(
ctypes.c_int32.from_address(new_obj + OBJ_HEIGHT).value, 2)
dst_buffer = ctypes.c_uint64.from_address(new_obj + OBJ_BUFFER).value
self.assertNotEqual(dst_buffer, 0)
self.assertNotEqual(dst_buffer, self._addr(src_pixels)) # a real copy.
copied = (ctypes.c_uint32 * 4).from_address(dst_buffer)
self.assertEqual(list(copied), pattern)
del dst
# ------------------------------------------------------------------ #
# The 28 "unsupported" stubs -- each raises exception 0x74, nothing else.
# ------------------------------------------------------------------ #
def test_all_stub_methods_raise_0x74(self):
# raw:90 et al every stub is `as3vm_exception_GC(vm, 0x74); return;`.
self.assertEqual(len(STUB_METHODS), 28)
for name in STUB_METHODS:
self.lib.swf_as3_bitmap_data_test_reset()
vm = self._buf(0x40)
frame = self._frame(vm=self._addr(vm))
getattr(self.lib, f"as3vm_BitmapData_{name}")(
ctypes.c_void_p(self._addr(frame)))
self.assertEqual(
self.lib.swf_as3_bitmap_data_test_exception_count(), 1, name)
self.assertEqual(
self.lib.swf_as3_bitmap_data_test_last_exception_code(),
0x74, name)
self.assertEqual(
self.lib.swf_as3_bitmap_data_test_malloc_count(), 0, name)
if __name__ == "__main__":
unittest.main()