Files
neoLegacy-mac/tests/test_reconstructed_as3vm_imp_string.py
2026-07-18 17:34:31 -05:00

712 lines
33 KiB
Python

"""Runtime tests for the reconstructed as3vm_imp_string translation unit.
RED STATE: as3vm_imp_string.c / as3vm_imp_string.h do not exist yet, so
setUpClass raises "missing as3vm_imp_string runtime inputs". Every assertion
below is grounded in a specific line of
iggy-decompiled/raw/durango/as3vm_imp_string.c (cited inline) so a faithful
DURANGO reconstruction turns these green.
as3vm_imp_string is Iggy's AS3 / AVM2 String class: charAt / charCodeAt /
concat / fromCharCode / indexOf / lastIndexOf / localeCompare / match / replace
/ search / slice / split / substr / substring / toLocaleLowerCase /
toLocaleUpperCase / toString / valueOf / get_length / __construct, plus the
file-level export as3vm_stringdata_compare_caseinsensitive. It exports EXACTLY
21 entry points on all four platforms and -- LIKE as3vm_convert / as3vm_imp_math
/ as3vm_imp_array but UNLIKE as3vm_gc / as3vm_property -- OWNS NO externally
named data global (the durango ??_C@ symbols are MSVC rodata format-string
COMDATs, not owned data).
STRING OBJECT / STRINGDATA MODEL (raw/durango, offsets 64-bit; the runtime test
builds ONLY the durango dylib so the 64-bit layout is correct. The stringdata
internal layout is INVARIANT across word sizes -- the 32-bit vita raw keeps
length at stringdata+7 and code units at stringdata+0xb, only the
object->stringdata pointer width changes (8 vs 4 bytes) and the interned
empty-string slot moves from vm+0xe18 on durango to vm+0x948 on vita):
- an as3value is a tagged word: (v & 3) is the tag. Tag 1 == heap cell,
carrying a 1-byte type at v[-1] (0x08 == '\b' marks a String object).
- a String object (tag-1, type 0x08 at obj[-1]) holds its stringdata pointer
at obj+7 (raw:25-37, 133-137).
- a stringdata holds length (int32) at stringdata+7 and a dense array of UTF-16
code units at stringdata+0xb; code unit [i] at stringdata+0xb+i*2
(raw:33-37, 62-68). get_length returns length<<1; charCodeAt returns
codeunit<<1.
- the method thunk receives a four-word call frame: frame[0]=vm,
frame[1]=&result slot, frame[2]=argc (int32 at +0x10), frame[3]=&this-slot
(points at [this, arg0, arg1, ...]) (raw:6-42, 133-137).
- the interned empty string lives at vm+0xe18; the GC operand-stack top pointer
at vm+0x6b18 (raw:42, 104-125).
WHAT IS PINNED (real, deterministic DURANGO behavior):
- __construct raises exception 0x74 unconditionally (raw:9).
- get_length writes length<<1 (raw:136-137).
- charAt: an in-bounds index boxes a fresh 1-char String whose code unit equals
source[index]; an out-of-range index or a wrong-type `this` returns the
interned empty string at vm+0xe18; a nonzero parse raises 0x78 (raw:25-43).
- charCodeAt: an in-bounds index returns codeunit<<1; a nonzero parse raises
0x78 (raw:57-72). (The out-of-range NaN return targets an internal &DAT
sentinel and is left structural.)
- fromCharCode boxes a String of `argc` code units, each the low 16 bits of the
corresponding as3vm_ToInt32_GC result (raw:104-125).
- concat delegates to as3vm_array_join and boxes its result (raw:84-86).
- indexOf / lastIndexOf: substring search honouring fromIndex; a hit boxes
pos<<1, a miss boxes -1 (tagged -2), an empty needle clamps to the fromIndex
(indexOf) / length (lastIndexOf) (raw:159-192, 211-251).
- localeCompare returns 0 when equal, -2 when `this` < arg, 2 when `this` > arg,
comparing UTF-16 code units then length (raw:271-311).
- slice / substr / substring index clamping -- the three genuinely differ and
each is reproduced exactly: slice(3,1) is empty, substring(3,1) swaps to
(1,3), substr's second arg is a length (raw:504-542, 694-728, 748-788).
- match raises 0x78 unconditionally (the RegExp path is unbuilt) (raw:321).
- replace: an empty needle returns the interned empty string; a no-match
returns `this` unchanged (raw:357-358, 422).
- split: a limit < 1 boxes an empty array; an undefined separator boxes a
single-element array holding `this` (raw:577-591).
- search: an empty needle returns 0; a multi-char needle returns pos<<1 on a hit
and -2 on a miss (raw:452-485).
- toString / valueOf box `this` unchanged (raw:820-831).
- toLocaleLowerCase / toLocaleUpperCase tail-call the already-built
as3vm_String_toLowerCase / as3vm_String_toUpperCase (iggy_unicode) with the
same frame (raw:798, 809).
- stringdata_compare_caseinsensitive forwards (a+0xb, a_len, b+0xb, b_len) to
rrCompareInsensitiveUTF16toUTF16 and returns its result (raw:842-843).
DEFERRED (flagged for the impl / review phase, NOT exercised here):
- the RegExp-backed match / search-with-RegExp and the replace
match-and-rebuild path (ToString / do_func_call_vv / make_string,
raw:360-421).
- split's empty-separator char split and non-empty-separator scan
(raw:593-674) -- reach as3vm_array_push_GC / make_substring_GC.
- charCodeAt / split's undefined-value &DAT NaN sentinel returns (an internal
read-only address, not a controllable VM slot).
- the single-char search scan wart (raw:466-483) which over-reports on a
length-1 needle.
Full-suite runs use python3.12 (the machine python3 is 3.14, which SEGFAULTs on
the full suite via an unrelated CPython ctypes-GC bug); single-module runs of
this file 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 / "as3vm_imp_string.c"
HEADER = RECONSTRUCTED / "as3vm_imp_string.h"
SUPPORT = ROOT / "tests/support/as3vm_imp_string_test_support.c"
MASK64 = (1 << 64) - 1
# 64-bit DURANGO value / struct constants (cited per test).
TAG_STRING = 1 # (v & 3) tag of a heap String cell.
TYPE_STRING = 0x08 # String object type byte at obj[-1] (raw:26).
OFF_OBJ_SD = 7 # String object -> stringdata pointer (raw:33).
OFF_SD_LENGTH = 7 # stringdata length (int32, raw:33).
OFF_SD_CHARS = 0x0B # stringdata UTF-16 code units (raw:37).
OFF_VM_EMPTY = 0xE18 # vm -> interned empty string (raw:42).
OFF_VM_GC_STACK = 0x6B18 # vm -> GC operand-stack top pointer (raw:106).
OFF_ARR_ARRAYDATA = 0x2F # split array object -> arraydata (raw:585).
OFF_AD_ELEMS = 0x1F # arraydata dense elements (raw:590).
NOT_FOUND = -2 # boxed -1 (0xffff_ffff_ffff_fffe, raw:181/246).
EMPTY_MARKER = 0x00E0DEAD0BEEF018 # sentinel stored at vm+0xe18.
class ReconstructedAs3vmImpStringTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
missing = [str(path) for path in (SOURCE, HEADER, SUPPORT)
if not path.exists()]
if missing:
raise AssertionError(
"missing as3vm_imp_string runtime inputs: " + ", ".join(missing))
cls.temp = tempfile.TemporaryDirectory()
cls.base = Path(cls.temp.name) / "as3vm_imp_string.dylib"
build = subprocess.run([
"clang", "-dynamiclib", "-std=c11", "-O2", "-Wall", "-Wextra",
"-Werror", "-Wl,-undefined,dynamic_lookup",
"-DIGGY_RECONSTRUCT_AS3VM_IMP_STRING_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"as3vm_imp_string_{self._testMethodName}.dylib")
shutil.copyfile(self.base, unique)
self.lib = ctypes.CDLL(str(unique))
self._bind(self.lib)
self.lib.as3vm_imp_string_test_reset()
self._keep = []
def _bind(self, lib):
void_p = ctypes.c_void_p
lib.as3vm_imp_string_test_reset.restype = None
lib.as3vm_imp_string_test_reset.argtypes = []
for name in ("exception", "write_barrier", "make_string", "make_array",
"toint32", "parse_args", "array_join", "array_push",
"do_func_call", "tolowercase", "touppercase",
"compare_ci"):
fn = getattr(lib, f"as3vm_imp_string_test_{name}_count")
fn.restype = ctypes.c_size_t
fn.argtypes = []
lib.as3vm_imp_string_test_last_exception_code.restype = ctypes.c_int32
lib.as3vm_imp_string_test_last_exception_code.argtypes = []
for name in ("last_string", "last_array", "last_lower_frame",
"last_upper_frame", "compare_ci_a", "compare_ci_b",
"global_nan_addr", "nullundef_addr"):
fn = getattr(lib, f"as3vm_imp_string_test_{name}")
fn.restype = ctypes.c_void_p
fn.argtypes = []
for name in ("compare_ci_a_len", "compare_ci_b_len"):
fn = getattr(lib, f"as3vm_imp_string_test_{name}")
fn.restype = ctypes.c_uint32
fn.argtypes = []
lib.as3vm_imp_string_test_set_parse_status.restype = None
lib.as3vm_imp_string_test_set_parse_status.argtypes = [ctypes.c_int]
lib.as3vm_imp_string_test_set_parse_ptr.restype = None
lib.as3vm_imp_string_test_set_parse_ptr.argtypes = [
ctypes.c_int, void_p]
lib.as3vm_imp_string_test_set_parse_int.restype = None
lib.as3vm_imp_string_test_set_parse_int.argtypes = [
ctypes.c_int, ctypes.c_int32]
lib.as3vm_imp_string_test_set_toint32.restype = None
lib.as3vm_imp_string_test_set_toint32.argtypes = [
ctypes.c_int, ctypes.c_int32]
lib.as3vm_imp_string_test_set_array_join_result.restype = None
lib.as3vm_imp_string_test_set_array_join_result.argtypes = [void_p]
lib.as3vm_imp_string_test_set_compare_ci_result.restype = None
lib.as3vm_imp_string_test_set_compare_ci_result.argtypes = [
ctypes.c_int32]
# Module exports under test (durango 64-bit ABI). Every method thunk
# takes the four-word frame; stringdata_compare takes two stringdata
# pointers and returns the rr comparison.
for name in (
"as3vm_String__construct", "as3vm_String_charAt",
"as3vm_String_charCodeAt", "as3vm_String_concat",
"as3vm_String_fromCharCode", "as3vm_String_get_length",
"as3vm_String_indexOf", "as3vm_String_lastIndexOf",
"as3vm_String_localeCompare", "as3vm_String_match",
"as3vm_String_replace", "as3vm_String_search",
"as3vm_String_slice", "as3vm_String_split", "as3vm_String_substr",
"as3vm_String_substring", "as3vm_String_toLocaleLowerCase",
"as3vm_String_toLocaleUpperCase", "as3vm_String_toString",
"as3vm_String_valueOf",
):
fn = getattr(lib, name)
fn.restype = None
fn.argtypes = [void_p]
lib.as3vm_stringdata_compare_caseinsensitive.restype = ctypes.c_int32
lib.as3vm_stringdata_compare_caseinsensitive.argtypes = [
void_p, void_p]
def _count(self, name):
return getattr(self.lib, f"as3vm_imp_string_test_{name}_count")()
def _buffer(self, size):
buf = (ctypes.c_uint8 * size)()
self._keep.append(buf)
return ctypes.addressof(buf)
# ---- Builders. ---- #
def _vm(self):
# A vm buffer large enough for the GC-stack top pointer (vm+0x6b18) and
# the interned empty-string slot (vm+0xe18).
vm = self._buffer(OFF_VM_GC_STACK + 0x400)
ctypes.c_uint64.from_address(vm + OFF_VM_EMPTY).value = EMPTY_MARKER
return vm
def _install_gc_stack(self, vm):
# Point vm+0x6b18 at a scratch operand stack for the push/pop dance in
# fromCharCode / split / make_substring (raw:106-124).
stack = self._buffer(0x800)
ctypes.c_uint64.from_address(vm + OFF_VM_GC_STACK).value = stack
def _stringdata(self, text):
# A stringdata: length int32 at +7, UTF-16 code units at +0xb.
units = [ord(ch) for ch in text]
sd = self._buffer(OFF_SD_CHARS + (len(units) + 4) * 2)
ctypes.c_int32.from_address(sd + OFF_SD_LENGTH).value = len(units)
for i, unit in enumerate(units):
ctypes.c_uint16.from_address(sd + OFF_SD_CHARS + i * 2).value = unit
return sd
def _string(self, text):
# A tag-1 String cell: obj = cell + 1, type 0x08 at obj[-1], stringdata
# pointer at obj+7 (raw:25-37).
sd = self._stringdata(text)
cell = self._buffer(0x40)
ctypes.c_uint8.from_address(cell).value = TYPE_STRING
obj = cell + 1
ctypes.c_uint64.from_address(obj + OFF_OBJ_SD).value = sd
return obj
def _frame(self, vm, this_value, argc, args=()):
# frame[0]=vm, frame[1]=&result, frame[2]=argc, frame[3]=&this-slot;
# the this-slot holds [this, arg0, arg1, ...] (raw:6-42).
result = self._buffer(8)
slot = self._buffer(8 * (1 + len(args)))
ctypes.c_uint64.from_address(slot).value = this_value & MASK64
for i, value in enumerate(args):
ctypes.c_uint64.from_address(slot + (i + 1) * 8).value = (
value & MASK64)
frame = self._buffer(0x20)
ctypes.c_uint64.from_address(frame + 0x00).value = vm
ctypes.c_uint64.from_address(frame + 0x08).value = result
ctypes.c_int32.from_address(frame + 0x10).value = argc
ctypes.c_uint64.from_address(frame + 0x18).value = slot
return frame, result
def _result(self, result):
return ctypes.c_int64.from_address(result).value
def _uresult(self, result):
return ctypes.c_uint64.from_address(result).value
def _read_string(self, word):
# Decode a boxed String result word into (length, [code units]).
sd = ctypes.c_uint64.from_address(word + OFF_OBJ_SD).value
length = ctypes.c_int32.from_address(sd + OFF_SD_LENGTH).value
units = [ctypes.c_uint16.from_address(sd + OFF_SD_CHARS + i * 2).value
for i in range(length)]
return length, units
def _set_parse(self, ptrs=(), ints=()):
for i, value in enumerate(ptrs):
self.lib.as3vm_imp_string_test_set_parse_ptr(
i, ctypes.c_void_p(value))
for i, value in enumerate(ints):
self.lib.as3vm_imp_string_test_set_parse_int(i, value)
# ------------------------------------------------------------------ #
# __construct -- always throws.
# ------------------------------------------------------------------ #
def test_construct_raises_0x74(self):
# raw:9 the String class constructor unconditionally raises 0x74.
vm = self._vm()
frame, _ = self._frame(vm, self._string(""), argc=0)
self.lib.as3vm_String__construct(frame)
self.assertEqual(self._count("exception"), 1)
self.assertEqual(
self.lib.as3vm_imp_string_test_last_exception_code(), 0x74)
# ------------------------------------------------------------------ #
# get_length -- length<<1.
# ------------------------------------------------------------------ #
def test_get_length_returns_tagged_length(self):
# raw:136-137 get_length boxes length<<1.
vm = self._vm()
frame, result = self._frame(vm, self._string("hello"), argc=0)
self.lib.as3vm_String_get_length(frame)
self.assertEqual(self._result(result), 5 * 2)
# ------------------------------------------------------------------ #
# charAt -- new 1-char string / empty-string sentinel / parse guard.
# ------------------------------------------------------------------ #
def test_charat_in_bounds_boxes_single_char_string(self):
# raw:32-38 an in-bounds index makes a fresh 1-char String holding
# source[index].
vm = self._vm()
frame, result = self._frame(vm, self._string("hello"), argc=1, args=(0,))
self._set_parse(ints=(1,))
self.lib.as3vm_String_charAt(frame)
self.assertEqual(self._count("make_string"), 1)
length, units = self._read_string(self._uresult(result))
self.assertEqual(length, 1)
self.assertEqual(units, [ord("e")])
def test_charat_out_of_range_returns_empty(self):
# raw:42 an out-of-range index returns the interned empty string.
vm = self._vm()
frame, result = self._frame(vm, self._string("hi"), argc=1, args=(0,))
self._set_parse(ints=(9,))
self.lib.as3vm_String_charAt(frame)
self.assertEqual(self._uresult(result), EMPTY_MARKER)
self.assertEqual(self._count("make_string"), 0)
def test_charat_wrong_type_returns_empty(self):
# raw:25/42 a `this` that is not a tag-1 type-0x08 String skips the body
# and returns the interned empty string.
vm = self._vm()
frame, result = self._frame(vm, 0x2, argc=1, args=(0,)) # tag-2 word
self._set_parse(ints=(0,))
self.lib.as3vm_String_charAt(frame)
self.assertEqual(self._uresult(result), EMPTY_MARKER)
self.assertEqual(self._count("parse_args"), 0)
def test_charat_parse_failure_raises_0x78(self):
# raw:28-30 a nonzero parse over a valid String `this` raises 0x78.
vm = self._vm()
frame, _ = self._frame(vm, self._string("hi"), argc=1, args=(0,))
self.lib.as3vm_imp_string_test_set_parse_status(1)
self.lib.as3vm_String_charAt(frame)
self.assertEqual(self._count("exception"), 1)
self.assertEqual(
self.lib.as3vm_imp_string_test_last_exception_code(), 0x78)
# ------------------------------------------------------------------ #
# charCodeAt -- codeunit<<1 / parse guard.
# ------------------------------------------------------------------ #
def test_charcodeat_in_bounds_returns_tagged_code_unit(self):
# raw:64-68 an in-bounds index returns codeunit<<1.
vm = self._vm()
frame, result = self._frame(vm, self._string("ABC"), argc=1, args=(0,))
self._set_parse(ints=(2,))
self.lib.as3vm_String_charCodeAt(frame)
self.assertEqual(self._result(result), ord("C") * 2)
def test_charcodeat_parse_failure_raises_0x78(self):
# raw:58-60 a nonzero parse raises 0x78.
vm = self._vm()
frame, _ = self._frame(vm, self._string("ABC"), argc=1, args=(0,))
self.lib.as3vm_imp_string_test_set_parse_status(1)
self.lib.as3vm_String_charCodeAt(frame)
self.assertEqual(
self.lib.as3vm_imp_string_test_last_exception_code(), 0x78)
# ------------------------------------------------------------------ #
# fromCharCode -- varargs -> UTF-16 string.
# ------------------------------------------------------------------ #
def test_fromcharcode_builds_string_from_toint32_results(self):
# raw:104-125 boxes a String of argc code units, each the low 16 bits of
# the corresponding as3vm_ToInt32_GC result.
vm = self._vm()
self._install_gc_stack(vm)
frame, result = self._frame(vm, self._string(""), argc=3,
args=(0, 0, 0))
for i, code in enumerate((72, 105, 33)): # 'H', 'i', '!'
self.lib.as3vm_imp_string_test_set_toint32(i, code)
self.lib.as3vm_String_fromCharCode(frame)
self.assertEqual(self._count("toint32"), 3)
length, units = self._read_string(self._uresult(result))
self.assertEqual(length, 3)
self.assertEqual(units, [72, 105, 33])
# ------------------------------------------------------------------ #
# concat -- delegates to as3vm_array_join.
# ------------------------------------------------------------------ #
def test_concat_delegates_to_array_join(self):
# raw:84-86 concat boxes the as3vm_array_join return.
vm = self._vm()
sentinel = self._buffer(0x20)
self.lib.as3vm_imp_string_test_set_array_join_result(
ctypes.c_void_p(sentinel))
frame, result = self._frame(vm, self._string("ab"), argc=1,
args=(self._string("cd"),))
self.lib.as3vm_String_concat(frame)
self.assertEqual(self._count("array_join"), 1)
self.assertEqual(self._uresult(result), sentinel)
# ------------------------------------------------------------------ #
# indexOf / lastIndexOf -- substring search + fromIndex.
# ------------------------------------------------------------------ #
def _call_search(self, fn, haystack, needle, from_index):
vm = self._vm()
needle_obj = self._string(needle)
frame, result = self._frame(
vm, self._string(haystack), argc=2, args=(needle_obj, 0))
self._set_parse(ptrs=(needle_obj,), ints=(from_index,))
fn(frame)
return self._result(result)
def test_indexof_hit_miss_and_empty_needle(self):
# raw:172-192 a hit boxes pos<<1, a miss boxes -1 (-2), and an empty
# needle at fromIndex k <= len boxes k<<1.
self.assertEqual(
self._call_search(self.lib.as3vm_String_indexOf, "hello", "ll", 0),
2 * 2)
self.assertEqual(
self._call_search(self.lib.as3vm_String_indexOf, "hello", "l", 0),
2 * 2)
self.assertEqual(
self._call_search(self.lib.as3vm_String_indexOf, "hello", "z", 0),
NOT_FOUND)
self.assertEqual(
self._call_search(self.lib.as3vm_String_indexOf, "hello", "", 2),
2 * 2)
def test_indexof_needle_longer_than_haystack_misses(self):
# raw:168/189 a needle longer than the haystack boxes -2.
self.assertEqual(
self._call_search(
self.lib.as3vm_String_indexOf, "hi", "hello", 0),
NOT_FOUND)
def test_lastindexof_finds_last_occurrence(self):
# raw:231-246 the backward scan boxes the last hit position<<1.
self.assertEqual(
self._call_search(
self.lib.as3vm_String_lastIndexOf, "hello", "l", 0x7FFFFFFF),
3 * 2)
def test_lastindexof_respects_from_index(self):
# raw:234-244 a fromIndex clamps the backward scan start.
self.assertEqual(
self._call_search(
self.lib.as3vm_String_lastIndexOf, "hello", "l", 2),
2 * 2)
# ------------------------------------------------------------------ #
# localeCompare -- 0 / -2 / 2.
# ------------------------------------------------------------------ #
def _call_locale(self, this_text, arg_text):
vm = self._vm()
arg_obj = self._string(arg_text)
frame, result = self._frame(
vm, self._string(this_text), argc=1, args=(arg_obj,))
self._set_parse(ptrs=(arg_obj,))
self.lib.as3vm_String_localeCompare(frame)
return self._result(result)
def test_locale_compare_orderings(self):
# raw:300-310 equal -> 0, this<arg -> -2, this>arg -> 2, with a shorter
# prefix ordering less-than.
self.assertEqual(self._call_locale("abc", "abc"), 0)
self.assertEqual(self._call_locale("abc", "abd"), NOT_FOUND)
self.assertEqual(self._call_locale("abd", "abc"), 2)
self.assertEqual(self._call_locale("ab", "abc"), NOT_FOUND)
self.assertEqual(self._call_locale("abc", "ab"), 2)
# ------------------------------------------------------------------ #
# slice / substr / substring -- the three clamping rules genuinely differ.
# ------------------------------------------------------------------ #
def _call_clamp(self, fn, text, a, b):
vm = self._vm()
self._install_gc_stack(vm)
frame, result = self._frame(
vm, self._string(text), argc=2, args=(0, 0))
self._set_parse(ints=(a, b))
fn(frame)
return result
def test_slice_clamping(self):
# raw:510-542 slice: negatives fold from the end, start>=end is empty.
result = self._call_clamp(self.lib.as3vm_String_slice, "hello", 1, 3)
self.assertEqual(self._read_string(self._uresult(result))[1],
[ord("e"), ord("l")])
result = self._call_clamp(
self.lib.as3vm_String_slice, "hello", -2, 0x7FFFFFFF)
self.assertEqual(self._read_string(self._uresult(result))[1],
[ord("l"), ord("o")])
# start >= end -> the interned empty string, NOT a swap (contrast
# substring below).
result = self._call_clamp(self.lib.as3vm_String_slice, "hello", 3, 1)
self.assertEqual(self._uresult(result), EMPTY_MARKER)
def test_substr_second_arg_is_a_length(self):
# raw:703-724 substr's second argument is a LENGTH, not an end index.
result = self._call_clamp(self.lib.as3vm_String_substr, "hello", 1, 2)
self.assertEqual(self._read_string(self._uresult(result))[1],
[ord("e"), ord("l")])
# a negative start folds from the end.
result = self._call_clamp(
self.lib.as3vm_String_substr, "hello", -2, 0x7FFFFFFF)
self.assertEqual(self._read_string(self._uresult(result))[1],
[ord("l"), ord("o")])
# a zero length is empty.
result = self._call_clamp(self.lib.as3vm_String_substr, "hello", 2, 0)
self.assertEqual(self._uresult(result), EMPTY_MARKER)
def test_substring_swaps_when_start_exceeds_end(self):
# raw:770-784 substring clamps both to [0,len] then SWAPS start/end, so
# (3,1) yields the same window as (1,3) -- unlike slice.
result = self._call_clamp(
self.lib.as3vm_String_substring, "hello", 1, 3)
self.assertEqual(self._read_string(self._uresult(result))[1],
[ord("e"), ord("l")])
result = self._call_clamp(
self.lib.as3vm_String_substring, "hello", 3, 1)
self.assertEqual(self._read_string(self._uresult(result))[1],
[ord("e"), ord("l")])
# a negative index clamps to 0.
result = self._call_clamp(
self.lib.as3vm_String_substring, "hello", -5, 2)
self.assertEqual(self._read_string(self._uresult(result))[1],
[ord("h"), ord("e")])
# ------------------------------------------------------------------ #
# match -- unconditionally throws (RegExp path unbuilt).
# ------------------------------------------------------------------ #
def test_match_raises_0x78(self):
# raw:321 match unconditionally raises 0x78.
vm = self._vm()
frame, _ = self._frame(vm, self._string("hello"), argc=1, args=(0,))
self.lib.as3vm_String_match(frame)
self.assertEqual(
self.lib.as3vm_imp_string_test_last_exception_code(), 0x78)
# ------------------------------------------------------------------ #
# replace -- shallow shapes (empty needle / no match).
# ------------------------------------------------------------------ #
def test_replace_empty_needle_returns_empty(self):
# raw:357-358 an empty needle returns the interned empty string.
vm = self._vm()
self._install_gc_stack(vm)
needle = self._string("")
replacement = self._string("X")
frame, result = self._frame(
vm, self._string("hello"), argc=2, args=(needle, replacement))
self._set_parse(ptrs=(needle, replacement))
self.lib.as3vm_String_replace(frame)
self.assertEqual(self._uresult(result), EMPTY_MARKER)
def test_replace_no_match_returns_this_string(self):
# raw:353/422 when the needle is not found the source `this` object
# (lVar2 = *param_1[3]) is boxed unchanged.
vm = self._vm()
self._install_gc_stack(vm)
this_obj = self._string("hello")
needle = self._string("z")
replacement = self._string("X")
frame, result = self._frame(
vm, this_obj, argc=2, args=(needle, replacement))
self._set_parse(ptrs=(needle, replacement))
self.lib.as3vm_String_replace(frame)
self.assertEqual(self._uresult(result), this_obj)
self.assertEqual(self._count("do_func_call"), 0)
# ------------------------------------------------------------------ #
# split -- shallow shapes (limit<1 / undefined separator).
# ------------------------------------------------------------------ #
def test_split_limit_below_one_boxes_empty_array(self):
# raw:577-580 a limit < 1 boxes a fresh empty array.
vm = self._vm()
self._install_gc_stack(vm)
sep = self._string(",")
frame, result = self._frame(
vm, self._string("a,b"), argc=2, args=(sep, 0))
self._set_parse(ptrs=(sep,), ints=(0,))
self.lib.as3vm_String_split(frame)
self.assertEqual(self._count("make_array"), 1)
self.assertEqual(
self._uresult(result),
self.lib.as3vm_imp_string_test_last_array())
def test_split_undefined_separator_boxes_single_element_array(self):
# raw:582-591 an undefined separator (the &as3vm_nullundef_storage
# default, left in place by the parser -- durango/vita object relocs show
# split loads &nullundef_storage here, not &global_nan) boxes a 1-element
# array holding `this`.
vm = self._vm()
self._install_gc_stack(vm)
this_obj = self._string("hello")
undef = self.lib.as3vm_imp_string_test_nullundef_addr()
frame, result = self._frame(vm, this_obj, argc=1, args=(0,))
self._set_parse(ints=(0x7FFFFFFF,))
self.lib.as3vm_imp_string_test_set_parse_ptr(0, ctypes.c_void_p(undef))
self.lib.as3vm_String_split(frame)
self.assertEqual(self._count("make_array"), 1)
array_obj = self.lib.as3vm_imp_string_test_last_array()
arraydata = ctypes.c_uint64.from_address(
array_obj + OFF_ARR_ARRAYDATA).value
self.assertEqual(
ctypes.c_uint64.from_address(arraydata + OFF_AD_ELEMS).value,
this_obj)
# ------------------------------------------------------------------ #
# search -- empty needle / multi-char hit + miss.
# ------------------------------------------------------------------ #
def _call_search_method(self, haystack, needle):
vm = self._vm()
needle_obj = self._string(needle)
frame, result = self._frame(
vm, self._string(haystack), argc=1, args=(needle_obj,))
self._set_parse(ptrs=(needle_obj,))
self.lib.as3vm_String_search(frame)
return self._result(result)
def test_search_empty_needle_returns_zero(self):
# raw:453-454 an empty needle boxes 0.
self.assertEqual(self._call_search_method("hello", ""), 0)
def test_search_multi_char_hit_and_miss(self):
# raw:466-485 a multi-char needle boxes pos<<1 on a hit, -2 on a miss.
self.assertEqual(self._call_search_method("abcabc", "bc"), 1 * 2)
self.assertEqual(self._call_search_method("abcdef", "xy"), NOT_FOUND)
# ------------------------------------------------------------------ #
# toString / valueOf -- box `this`.
# ------------------------------------------------------------------ #
def test_tostring_and_valueof_box_this(self):
# raw:820/831 both box `this` unchanged.
for fn in (self.lib.as3vm_String_toString, self.lib.as3vm_String_valueOf):
vm = self._vm()
this_obj = self._string("hello")
frame, result = self._frame(vm, this_obj, argc=0)
fn(frame)
self.assertEqual(self._uresult(result), this_obj)
# ------------------------------------------------------------------ #
# toLocaleLowerCase / toLocaleUpperCase -- delegate to the plain-case
# siblings already reconstructed in iggy_unicode.
# ------------------------------------------------------------------ #
def test_tolocale_lower_upper_delegate_with_same_frame(self):
# raw:798/809 each tail-calls the plain-case sibling with the frame.
vm = self._vm()
frame, _ = self._frame(vm, self._string("Hi"), argc=0)
self.lib.as3vm_String_toLocaleLowerCase(frame)
self.assertEqual(self._count("tolowercase"), 1)
self.assertEqual(
self.lib.as3vm_imp_string_test_last_lower_frame(), frame)
frame2, _ = self._frame(vm, self._string("Hi"), argc=0)
self.lib.as3vm_String_toLocaleUpperCase(frame2)
self.assertEqual(self._count("touppercase"), 1)
self.assertEqual(
self.lib.as3vm_imp_string_test_last_upper_frame(), frame2)
# ------------------------------------------------------------------ #
# stringdata_compare_caseinsensitive -- forwards to rr with +0xb / +7.
# ------------------------------------------------------------------ #
def test_stringdata_compare_forwards_to_rr(self):
# raw:842-843 forwards (a+0xb, a_len, b+0xb, b_len) to
# rrCompareInsensitiveUTF16toUTF16 and returns its result.
sd_a = self._stringdata("hello")
sd_b = self._stringdata("worlds")
self.lib.as3vm_imp_string_test_set_compare_ci_result(7)
got = self.lib.as3vm_stringdata_compare_caseinsensitive(
ctypes.c_void_p(sd_a), ctypes.c_void_p(sd_b))
self.assertEqual(self._count("compare_ci"), 1)
self.assertEqual(got, 7)
self.assertEqual(
self.lib.as3vm_imp_string_test_compare_ci_a(), sd_a + OFF_SD_CHARS)
self.assertEqual(
self.lib.as3vm_imp_string_test_compare_ci_a_len(), 5)
self.assertEqual(
self.lib.as3vm_imp_string_test_compare_ci_b(), sd_b + OFF_SD_CHARS)
self.assertEqual(
self.lib.as3vm_imp_string_test_compare_ci_b_len(), 6)
if __name__ == "__main__":
unittest.main()