rebuild iggy's as3vm ecmascript conversions

This commit is contained in:
coah
2026-07-18 07:10:21 -05:00
parent 50b4ac4663
commit 720cde3c34
8 changed files with 2151 additions and 0 deletions

View File

@@ -476,6 +476,26 @@ foreach(platform IN ITEMS durango orbis ps3 vita)
endif()
endforeach()
# as3vm_convert -- AS3 / AVM2 ECMAScript type conversion (4-platform). Imports
# fmod / floor / memcmp, so guard against libcall re-synthesis with -fno-builtin
# (clang/gcc) or /Oi- (MSVC). floor is inlined on orbis and memcmp is inlined
# on durango, matching the per-target lowering recovered from the objects.
foreach(platform IN ITEMS durango orbis ps3 vita)
string(TOUPPER ${platform} platform_upper)
set(target iggy_reconstructed_as3vm_convert_${platform})
add_library(${target} STATIC as3vm_convert.c)
target_compile_definitions(
${target}
PRIVATE IGGY_RECONSTRUCT_AS3VM_CONVERT_${platform_upper}
)
configure_iggy_reconstructed_target(${target} c_std_11)
if(CMAKE_C_COMPILER_ID MATCHES "Clang|GNU")
target_compile_options(${target} PRIVATE -fno-builtin)
elseif(MSVC)
target_compile_options(${target} PRIVATE /Oi-)
endif()
endforeach()
add_library(iggy_reconstructed_win32_rrThreads2_durango STATIC win32_rrThreads2.c)
target_compile_definitions(
iggy_reconstructed_win32_rrThreads2_durango

View File

@@ -454,6 +454,25 @@ size-only difference), and the ps3 build's eight-argument trait-array signature
is expressed through the shared nine-argument form; both are documented in-code.
The value-construction, name-interning, and allocation primitives remain imported.
`as3vm_convert.c` restores the AS3/AVM2 ECMAScript type-conversion layer. Its
four builds (per-platform function counts 16/15/15/16) expose all 15 conversion
entry points with no owned globals — ToNumber, ToString, ToInt32/ToUInt32, the
NaN-failing and direct variants, ToBoolean, ToCharArray, DefaultValue (with the
valueOf/toString hint dispatch), StringToArrayIndex, and array-to-vector. It
reconstructs the exact ECMAScript ToInt32 arithmetic (the 2^32 modulus and the
±(2^32−1) wrap thresholds, floor plus a subtract-2^32 canonicalization that
avoids a 64-bit-conversion libcall on the 32-bit targets), the string-to-number
parser dispatch (decimal/hex/Infinity/whitespace with the exact character sets
recovered from the retail masks), the number-to-string path with its VM-context
interned sentinel-string offsets for null/undefined/NaN/zero/infinities, and the
per-type ToBoolean truthiness — including the retail StringToArrayIndex
multi-digit accumulator quirk and the zero-filled empty-string symbol the
object-coercion path returns (a relocation the decompiler had misrendered as a
literal). The 64-bit and 32-bit value, number-box, and string layouts, the exact
constants, and the per-platform `floor`/`memcmp` inline-versus-call split were
verified against the retail object disassembly on all four builds. The value
boxing, string formatting, and property primitives remain imported.
Configure this directory directly with CMake to build the reconstructed units.
Every added module must compile independently and have behavioral tests before
it is listed in `modules.tsv` as complete.

View File

@@ -0,0 +1,902 @@
/* Reconstructed translation unit for RAD's Iggy AS3 / AVM2 ECMAScript type
* conversion layer. */
/* Source-equivalent recovery of c:\projects\g\src\flash\as3vm_convert.c */
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "as3vm_convert.h"
#if (defined(IGGY_RECONSTRUCT_AS3VM_CONVERT_DURANGO) + \
defined(IGGY_RECONSTRUCT_AS3VM_CONVERT_ORBIS) + \
defined(IGGY_RECONSTRUCT_AS3VM_CONVERT_PS3) + \
defined(IGGY_RECONSTRUCT_AS3VM_CONVERT_VITA)) != 1
#error "select exactly one as3vm_convert target"
#endif
#if defined(__clang__) || defined(__GNUC__)
#define IGGY_USED __attribute__((used))
#else
#define IGGY_USED
#endif
/* durango/orbis are LP64; ps3/vita are ILP32. */
#if defined(IGGY_RECONSTRUCT_AS3VM_CONVERT_DURANGO) || \
defined(IGGY_RECONSTRUCT_AS3VM_CONVERT_ORBIS)
#define IGGY_AS3_64BIT 1
#else
#define IGGY_AS3_64BIT 0
#endif
/* Provenance recorded exactly as the upstream Windows toolchain emitted it. */
static const char IGGY_USED as3vm_convert_source_path[] =
"c:\\projects\\g\\src\\flash\\as3vm_convert.c";
/* ------------------------------------------------------------------ */
/* Recovered external dependencies (the genuine nm ' U ' imports). */
/* ------------------------------------------------------------------ */
/* value / string construction (as3vm_create + the as3vm string module). */
extern void *as3vm_make_number_GC(void *vm, double value);
extern void *as3vm_string_from_number_GC(void *vm, double value);
extern void as3vm_string_from_number_direct(void *vm, double value,
uint16_t *buffer, int capacity,
void *scratch);
/* object primitive coercion (as3vm_interpreter -- unbuilt). */
extern void *as3vm_get_property_qname_GC(void *vm, void *object, void *qname);
extern void as3vm_do_func_call_vv_GC(void *vm, void *result, long callee,
long argptr, int a, int b);
/* ECMAScript number parsing (rr string helpers). */
extern int rr_utf16_read_decimal_ecmascript(const uint16_t *chars,
uint32_t count,
const uint16_t **endptr,
double *out, int flags);
extern int rr_utf16_read_hex_ecmascript(const uint16_t *chars, uint32_t count,
const uint16_t **endptr, double *out,
int flags);
extern int rriswdigit(int ch);
extern size_t rrwcslen(const uint16_t *text);
/* float classification (rrMath). */
extern int rr_isnan(double value);
extern int rr_isnaninf(double value);
/* special-double + sentinel DATA symbols (referenced only by value/address). */
extern double as3vm_NaNd;
extern double as3vm_P_Infinity;
extern double as3vm_N_Infinity;
extern uint8_t as3vm_nullundef_storage[];
extern uint8_t as3vm_truefalse_storage[];
/* libm: fmod is genuinely called on every target (the 2^32 wrap). */
extern double fmod(double x, double y);
/* Per-target libm/libc split recovered from the four objects: floor is a call
* on durango/ps3/vita but inlined on orbis (retail lowers it to roundsd);
* memcmp is a call on orbis/ps3/vita but inlined on durango. */
#if !defined(IGGY_RECONSTRUCT_AS3VM_CONVERT_ORBIS)
extern double floor(double value);
#endif
#if !defined(IGGY_RECONSTRUCT_AS3VM_CONVERT_DURANGO)
extern int memcmp(const void *a, const void *b, size_t n);
#endif
#if defined(__APPLE__)
#pragma weak as3vm_make_number_GC
#pragma weak as3vm_string_from_number_GC
#pragma weak as3vm_string_from_number_direct
#pragma weak as3vm_get_property_qname_GC
#pragma weak as3vm_do_func_call_vv_GC
#pragma weak rr_utf16_read_decimal_ecmascript
#pragma weak rr_utf16_read_hex_ecmascript
#pragma weak rriswdigit
#pragma weak rrwcslen
#pragma weak rr_isnan
#pragma weak rr_isnaninf
#pragma weak as3vm_NaNd
#pragma weak as3vm_P_Infinity
#pragma weak as3vm_N_Infinity
#pragma weak as3vm_nullundef_storage
#pragma weak as3vm_truefalse_storage
#endif
/* ------------------------------------------------------------------ */
/* VM-context byte offsets + node field offsets recovered from raw. */
/* ------------------------------------------------------------------ */
#if IGGY_AS3_64BIT
#define VM_ROOT_STACK 0x6b18 /* raw/durango:19,80,134 */
#define VM_QN_VALUEOF 0xdb0 /* valueOf qname (Number tries first) */
#define VM_QN_TOSTRING 0xdb8 /* toString qname (String tries first) */
#define VM_EXC_FLAG 0x2908 /* pending-exception flag (String path) */
#define VM_EMPTY_CLASS 0x2848 /* -> +0x28 -> empty-string marker */
#define VM_EMPTY_FIELD 0x28
#define VM_NONE_SENTINEL 0x2648 /* class compared by DefaultValue_None */
#define NODE_CLASS_FIELD 0x20
#define WORD 8
#define SRC_BACKING 0x48 /* Array backing pointer (convert_array_to_vector) */
#define DST_ELEMENT 0x1f /* Vector first-element slot */
/* ToString VM-context interned-string offsets (raw/durango:719-745). */
#define STR_UNDEFINED 0x2791
#define STR_NULL 0x27a1
#define STR_TRUE 0x27b1
#define STR_FALSE 0x27c1
#define STR_NAN 0x27d1
#define STR_ZERO 0x27e1
#define STR_PINF 0x27f1
#define STR_NINF 0x2801
#else
#define VM_ROOT_STACK 0x4834
#define VM_QN_VALUEOF 0x914
#define VM_QN_TOSTRING 0x918
#define VM_EXC_FLAG 0x16e8
#define VM_EMPTY_CLASS 0x1688
#define VM_EMPTY_FIELD 0x18
#define VM_NONE_SENTINEL 0x1564
#define NODE_CLASS_FIELD 0x18
#define WORD 4
#define SRC_BACKING 0x28
#define DST_ELEMENT 0x13
/* ToString VM-context interned-string offsets (raw/vita:779-811). */
#define STR_UNDEFINED 0x1609
#define STR_NULL 0x1615
#define STR_TRUE 0x1621
#define STR_FALSE 0x162d
#define STR_NAN 0x1639
#define STR_ZERO 0x1645
#define STR_PINF 0x1651
#define STR_NINF 0x165d
#endif
/* Shared boolean / null sentinels (node+1 tagged pointers). false / true live
* in as3vm_truefalse_storage at +0 / +8; the null value the integer coercions
* short-circuit to 0 lives in as3vm_nullundef_storage (raw ps3/orbis: base+9). */
#define AS3_FALSE ((uintptr_t)&as3vm_truefalse_storage[0] + 1u)
#define AS3_TRUE ((uintptr_t)&as3vm_truefalse_storage[0] + 9u)
#define AS3_NULL_SENTINEL ((uintptr_t)&as3vm_nullundef_storage[0] + 9u)
/* The TypeError / undefined failure marker returned by DefaultValue. */
#define AS3_SEVEN ((uintptr_t)7)
/* ------------------------------------------------------------------ */
/* Static UTF-16 literals (durango 'R' rodata -- neither exports nor */
/* owned globals; the retail objects carry the identical strings). */
/* ------------------------------------------------------------------ */
/* s_infinity is "+Infinity"; s_infinity+1 is the bare "Infinity" the number
* parser matches, and ToCharArray returns s_infinity+1 for +Infinity. */
static const uint16_t s_infinity[] = {'+', 'I', 'n', 'f', 'i',
'n', 'i', 't', 'y', 0};
static const uint16_t s_neginfinity[] = {'-', 'I', 'n', 'f', 'i',
'n', 'i', 't', 'y', 0};
static const uint16_t AS3S_undefined[] = {'u', 'n', 'd', 'e', 'f',
'i', 'n', 'e', 'd', 0};
static const uint16_t AS3S_null[] = {'n', 'u', 'l', 'l', 0};
static const uint16_t AS3S_true[] = {'t', 'r', 'u', 'e', 0};
static const uint16_t AS3S_false[] = {'f', 'a', 'l', 's', 'e', 0};
static const uint16_t AS3S_NaN[] = {'N', 'a', 'N', 0};
static const uint16_t AS3S_zero[] = {'0', 0};
/* AS3S__nul is the retail zero-filled empty UTF-16 string returned by
* ToCharArray when DefaultValue yields the VM's empty-string marker. It is a
* single zero unit in .bss (durango/orbis/ps3) / .data (vita); a local symbol,
* so it does not touch the owned-global surface. IGGY_USED keeps it retained
* exactly as the retail `b AS3S__nul` local symbol. */
static uint16_t IGGY_USED AS3S__nul[1];
/* ------------------------------------------------------------------ */
/* Small helpers. */
/* ------------------------------------------------------------------ */
static uint8_t node_kind(uintptr_t w) { return ((const uint8_t *)w)[-1]; }
static double node_number(uintptr_t w) {
return *(const double *)((const uint8_t *)w + 7);
}
/* Reinterpret a 64-bit pattern as a double without pulling in memcpy. */
static double bits_to_double(uint64_t bits) {
union {
uint64_t u;
double d;
} value;
value.u = bits;
return value.d;
}
/* ECMAScript WhiteSpace + LineTerminator predicate (raw/durango:882 as the
* file-static is_as3_white; orbis/ps3 inline the identical membership). The
* retail masks lower to a comparison tree on the 32-bit targets, so the set is
* spelled out here to avoid a 64-bit variable shift libcall. */
static int is_as3_white(int c) {
if (c >= 0x2000 && c <= 0x200a) {
return 1;
}
if (c >= 0x09 && c <= 0x0d) {
return 1;
}
if (c == 0x20 || c == 0xa0) {
return 1;
}
if (c == 0x1680 || c == 0x180e) {
return 1;
}
if (c == 0x2028 || c == 0x2029 || c == 0x202f || c == 0x205f) {
return 1;
}
if (c == 0x3000) {
return 1;
}
return 0;
}
/* Leading character of a decimal number literal: '.', '0'-'9', '+', '-'. */
static int is_decimal_lead(uint16_t c) {
return c == 0x2e || (c >= 0x30 && c <= 0x39) || c == 0x2b || c == 0x2d;
}
/* UTF-16 unit-range equality. durango inlines the scan (no memcmp import);
* orbis/ps3/vita lower it to a memcmp call. */
static int units_equal(const uint16_t *a, const uint16_t *b, int units) {
#if defined(IGGY_RECONSTRUCT_AS3VM_CONVERT_DURANGO)
for (int i = 0; i < units; ++i) {
if (a[i] != b[i]) {
return 0;
}
}
return 1;
#else
return memcmp(a, b, (size_t)units * 2) == 0;
#endif
}
/* floor of a non-negative finite double. durango/ps3/vita call libm; orbis
* inlines an IEEE-754 bit-manipulation floor (retail uses roundsd). */
static double floor_nonneg(double value) {
#if defined(IGGY_RECONSTRUCT_AS3VM_CONVERT_ORBIS)
union {
double d;
uint64_t u;
} bits;
int exponent;
uint64_t fraction;
bits.d = value;
exponent = (int)((bits.u >> 52) & 0x7ff) - 1023;
if (exponent < 0) {
return 0.0; /* 0 <= value < 1 */
}
if (exponent >= 52) {
return value; /* already integral */
}
fraction = 0x000fffffffffffffULL >> exponent;
bits.u &= ~fraction; /* clear the fractional bits (truncate == floor >= 0) */
return bits.d;
#else
return floor(value);
#endif
}
/* ECMAScript ToInt32 final step: canonicalize a non-negative integral double
* in [0, 2^32) to its uint32 bit pattern without a 64-bit conversion libcall
* on the 32-bit targets. */
static uint32_t to_uint32_bits(double value) {
if (value >= 2147483648.0) {
return (uint32_t)(int32_t)(value - 4294967296.0);
}
return (uint32_t)(int32_t)value;
}
/* ------------------------------------------------------------------ */
/* as3vm_NumberToInt32 -- raw ECMAScript ToInt32 arithmetic. */
/* ------------------------------------------------------------------ */
int64_t as3vm_NumberToInt32(double value) {
/* 2^32, and the largest double strictly below 2^32 used as the wrap
* threshold (raw __real_41f0000000000000 / __real_41efffffffe00000). */
const double two32 = bits_to_double(0x41f0000000000000ULL);
const double pos_threshold = bits_to_double(0x41efffffffe00000ULL);
const double neg_threshold = bits_to_double(0xc1efffffffe00000ULL);
double d;
if (rr_isnaninf(value) != 0) {
return 0;
}
if (value == 0.0) {
return 0;
}
if (value < 0.0) {
d = -floor_nonneg(-value);
if (d < neg_threshold) {
d = fmod(d, two32);
}
if (d < 0.0) {
d = d + two32;
}
} else {
d = floor_nonneg(value);
if (pos_threshold < d) {
d = fmod(d, two32);
}
}
return (int64_t)to_uint32_bits(d);
}
/* ------------------------------------------------------------------ */
/* ECMAScript numeric-string parse (shared by ToNumber / ToNumberDirect). */
/* ------------------------------------------------------------------ */
/* Parse the trimmed UTF-16 range [chars, chars+len). Returns 0 when the range
* is empty after skipping whitespace (the numeric result is +0), otherwise 1
* with *out set (NaN sentinel on a malformed body). */
static int parse_ecma_number(const uint16_t *chars, int len, double *out) {
const uint16_t *p = chars;
const uint16_t *end = chars + len;
const uint16_t *scan;
double parsed;
uint16_t c;
while (p < end && is_as3_white(*p) != 0) {
++p;
}
if (p == end) {
*out = 0.0;
return 0;
}
c = *p;
/* Hex integer: 0x / 0X prefix. */
if (c == 0x30 && (uint16_t)(p[1] | 0x20) == 0x78) {
if (rr_utf16_read_hex_ecmascript(p, (uint32_t)(end - p), &scan, &parsed,
0) != 0) {
*out = parsed;
return 1;
}
*out = as3vm_NaNd;
return 1;
}
/* "Infinity" or "+Infinity" -> +Infinity when only whitespace trails. */
if (units_equal(p, s_infinity + 1, 8) != 0 ||
(c == 0x2b && units_equal(p + 1, s_infinity + 1, 8) != 0)) {
const uint16_t *q = p + (c == 0x2b ? 1 : 0) + 8;
if (q <= end) {
while (q < end && is_as3_white(*q) != 0) {
++q;
}
if (q == end) {
*out = as3vm_P_Infinity;
return 1;
}
}
*out = as3vm_NaNd;
return 1;
}
/* "-Infinity" -> -Infinity when only whitespace trails. */
if (c == 0x2d && units_equal(p + 1, s_infinity + 1, 8) != 0) {
const uint16_t *q = p + 9;
if (q <= end) {
while (q < end && is_as3_white(*q) != 0) {
++q;
}
if (q == end) {
*out = as3vm_N_Infinity;
return 1;
}
}
*out = as3vm_NaNd;
return 1;
}
/* Decimal (with optional sign / fraction / exponent). */
if (is_decimal_lead(c) != 0) {
if (rr_utf16_read_decimal_ecmascript(p, (uint32_t)(end - p), &scan, &parsed,
0) != 0) {
*out = parsed;
return 1;
}
}
*out = as3vm_NaNd;
return 1;
}
/* Descriptor accessors for a heap-string value word. */
static const uint16_t *string_units(uintptr_t w) {
return (const uint16_t *)(*(const uint8_t *const *)((const uint8_t *)w + 7) +
0xb);
}
static int32_t string_length(uintptr_t w) {
return *(const int32_t *)(*(const uint8_t *const *)((const uint8_t *)w + 7) +
7);
}
/* ------------------------------------------------------------------ */
/* DefaultValue -- valueOf / toString primitive coercion. */
/* ------------------------------------------------------------------ */
static int dv_callable(uintptr_t w) {
return (w & 3) == 1 && (node_kind(w) & 0x10) != 0;
}
static int dv_primitive(uintptr_t w) {
uint8_t kind;
if ((w & 3) != 1) {
return 1;
}
kind = node_kind(w);
return kind < 0x20 && (kind & 0x10) == 0;
}
static void root_push(void *vm, uintptr_t value) {
uintptr_t *top = *(uintptr_t **)((char *)vm + VM_ROOT_STACK);
*top = value;
*(char **)((char *)vm + VM_ROOT_STACK) = (char *)top + WORD;
}
static uintptr_t *root_pop(void *vm) {
char *top = *(char **)((char *)vm + VM_ROOT_STACK) - WORD;
*(char **)((char *)vm + VM_ROOT_STACK) = top;
return (uintptr_t *)top;
}
void *as3vm_DefaultValue_Number_GC(void *vm, void *value) {
uintptr_t receiver = (uintptr_t)value;
uintptr_t result;
uintptr_t *slot;
root_push(vm, receiver);
result = (uintptr_t)as3vm_get_property_qname_GC(
vm, value, *(void **)((char *)vm + VM_QN_VALUEOF));
slot = root_pop(vm);
if (dv_callable(result) != 0) {
root_push(vm, *slot);
as3vm_do_func_call_vv_GC(vm, &result, (long)result, (long)(uintptr_t)slot,
0, 0);
slot = root_pop(vm);
if (dv_primitive(result) != 0) {
return (void *)result;
}
}
root_push(vm, *slot);
result = (uintptr_t)as3vm_get_property_qname_GC(
vm, (void *)*slot, *(void **)((char *)vm + VM_QN_TOSTRING));
slot = root_pop(vm);
if (dv_callable(result) != 0) {
root_push(vm, *slot);
as3vm_do_func_call_vv_GC(vm, &result, (long)result, (long)(uintptr_t)slot,
0, 0);
(void)root_pop(vm);
if (dv_primitive(result) != 0) {
return (void *)result;
}
}
return (void *)AS3_SEVEN;
}
void *as3vm_DefaultValue_String_GC(void *vm, void *value) {
uintptr_t receiver = (uintptr_t)value;
uintptr_t result;
uintptr_t *slot;
uintptr_t empty;
empty = *(uintptr_t *)(*(uintptr_t *)((char *)vm + VM_EMPTY_CLASS) +
VM_EMPTY_FIELD);
root_push(vm, receiver);
result = (uintptr_t)as3vm_get_property_qname_GC(
vm, value, *(void **)((char *)vm + VM_QN_TOSTRING));
slot = root_pop(vm);
if (dv_callable(result) != 0) {
root_push(vm, *slot);
as3vm_do_func_call_vv_GC(vm, &result, (long)result, (long)(uintptr_t)slot,
0, 0);
slot = root_pop(vm);
if (*(uintptr_t *)((char *)vm + VM_EXC_FLAG) != 0) {
return (void *)AS3_SEVEN;
}
if (dv_primitive(result) != 0 || result == empty) {
return (void *)result;
}
}
root_push(vm, *slot);
result = (uintptr_t)as3vm_get_property_qname_GC(
vm, (void *)*slot, *(void **)((char *)vm + VM_QN_VALUEOF));
slot = root_pop(vm);
if (dv_callable(result) != 0) {
root_push(vm, *slot);
as3vm_do_func_call_vv_GC(vm, &result, (long)result, (long)(uintptr_t)slot,
0, 0);
(void)root_pop(vm);
if (*(uintptr_t *)((char *)vm + VM_EXC_FLAG) == 0 &&
dv_primitive(result) != 0) {
return (void *)result;
}
}
return (void *)AS3_SEVEN;
}
void *as3vm_DefaultValue_None_GC(void *vm, void *value) {
uintptr_t klass = *(uintptr_t *)(*(uintptr_t *)((const uint8_t *)value + 7) +
NODE_CLASS_FIELD);
if (klass != *(uintptr_t *)((char *)vm + VM_NONE_SENTINEL)) {
return as3vm_DefaultValue_Number_GC(vm, value);
}
return as3vm_DefaultValue_String_GC(vm, value);
}
/* ------------------------------------------------------------------ */
/* ToNumber / ToNumberDirect. */
/* ------------------------------------------------------------------ */
int as3vm_ToNumberDirect_GC(void *vm, void *value, double *out) {
uintptr_t w = (uintptr_t)value;
for (;;) {
if ((w & 1) == 0) {
*out = (double)(int32_t)((intptr_t)w >> 1);
return 1;
}
switch (node_kind(w)) {
case 4: /* undefined -> NaN */
*out = as3vm_NaNd;
return 1;
case 5: /* null -> 0 */
*out = 0.0;
return 1;
case 6: /* boolean */
*out = (double)(w == AS3_TRUE ? 1 : 0);
return 1;
case 7: /* heap-number */
*out = node_number(w);
return 1;
case 8: /* heap-string */
parse_ecma_number(string_units(w), string_length(w), out);
return 1;
default: /* object -> DefaultValue(Number) then retry */
w = (uintptr_t)as3vm_DefaultValue_Number_GC(vm, (void *)w);
if (w == AS3_SEVEN) {
return 0;
}
break;
}
}
}
void *as3vm_ToNumber_GC(void *vm, void *value) {
uintptr_t w = (uintptr_t)value;
for (;;) {
if ((w & 1) == 0) {
return (void *)w;
}
switch (node_kind(w)) {
case 4: /* undefined -> boxed NaN */
return as3vm_make_number_GC(vm, as3vm_NaNd);
case 5: /* null -> NULL */
return NULL;
case 6: /* boolean -> tagged int 1 / 0 */
return (void *)(uintptr_t)(w == AS3_TRUE ? 2u : 0u);
case 7: /* heap-number identity */
return (void *)w;
case 8: { /* heap-string */
double parsed;
if (parse_ecma_number(string_units(w), string_length(w), &parsed) ==
0) {
return (void *)0; /* trimmed-empty string -> tagged int 0 */
}
return as3vm_make_number_GC(vm, parsed);
}
default: /* object -> DefaultValue(Number) then retry */
w = (uintptr_t)as3vm_DefaultValue_Number_GC(vm, (void *)w);
if (w == AS3_SEVEN) {
return (void *)AS3_SEVEN;
}
break;
}
}
}
/* ------------------------------------------------------------------ */
/* ToInt32 / ToInt32FailNAN / ToUInt32. */
/* ------------------------------------------------------------------ */
int as3vm_ToInt32_GC(void *vm, void *value, int32_t *out) {
uintptr_t w = (uintptr_t)value;
double d;
if ((w & 1) == 0) {
*out = (int32_t)((intptr_t)w >> 1);
return 1;
}
if (w == AS3_NULL_SENTINEL) {
*out = 0;
return 1;
}
if (as3vm_ToNumberDirect_GC(vm, value, &d) == 0) {
return 0;
}
*out = (int32_t)as3vm_NumberToInt32(d);
return 1;
}
int as3vm_ToInt32FailNAN_GC(void *vm, void *value, int32_t *out) {
uintptr_t w = (uintptr_t)value;
double d;
if ((w & 1) == 0) {
*out = (int32_t)((intptr_t)w >> 1);
return 1;
}
if (w == AS3_NULL_SENTINEL) {
*out = 0;
return 1;
}
if (as3vm_ToNumberDirect_GC(vm, value, &d) == 0) {
return 0;
}
if (rr_isnaninf(d) != 0) {
return 0;
}
*out = (int32_t)as3vm_NumberToInt32(d);
return 1;
}
int as3vm_ToUInt32_GC(void *vm, void *value, uint32_t *out) {
uintptr_t w = (uintptr_t)value;
uintptr_t r;
if ((w & 1) == 0) {
*out = (uint32_t)(int32_t)((intptr_t)w >> 1);
return 1;
}
if (w == AS3_NULL_SENTINEL) {
*out = 0;
return 1;
}
r = (uintptr_t)as3vm_ToNumber_GC(vm, value);
if ((r & 1) == 0) {
*out = (uint32_t)(int32_t)((intptr_t)r >> 1);
return 1;
}
if (r == AS3_SEVEN) {
return 0;
}
*out = (uint32_t)as3vm_NumberToInt32(node_number(r));
return 1;
}
/* ------------------------------------------------------------------ */
/* ToString. */
/* ------------------------------------------------------------------ */
void *as3vm_ToString_GC(void *vm, void *value) {
uintptr_t w = (uintptr_t)value;
for (;;) {
if ((w & 1) == 0) {
return as3vm_string_from_number_GC(vm, (double)(int32_t)((intptr_t)w >> 1));
}
switch (node_kind(w)) {
case 4:
return (void *)((uintptr_t)vm + STR_UNDEFINED);
case 5:
return (void *)((uintptr_t)vm + STR_NULL);
case 6:
return (void *)((uintptr_t)vm +
(w == AS3_TRUE ? STR_TRUE : STR_FALSE));
case 7: {
double d = node_number(w);
if (rr_isnaninf(d) != 0) {
if (rr_isnan(d) != 0) {
return (void *)((uintptr_t)vm + STR_NAN);
}
if (d <= 0.0) {
return (void *)((uintptr_t)vm + STR_NINF);
}
return (void *)((uintptr_t)vm + STR_PINF);
}
if (d == 0.0) {
return (void *)((uintptr_t)vm + STR_ZERO);
}
return as3vm_string_from_number_GC(vm, d);
}
case 8:
return (void *)w; /* string identity */
default:
w = (uintptr_t)as3vm_DefaultValue_String_GC(vm, (void *)w);
if (w == AS3_SEVEN) {
return (void *)AS3_SEVEN;
}
break;
}
}
}
/* ------------------------------------------------------------------ */
/* ToCharArray. */
/* ------------------------------------------------------------------ */
void *as3vm_ToCharArray_GC(void *vm, void *value, void *buffer, int *length,
void *scratch) {
uintptr_t w = (uintptr_t)value;
*(void **)scratch = value;
for (;;) {
if ((w & 1) == 0) {
as3vm_string_from_number_direct(vm, (double)(int32_t)((intptr_t)w >> 1),
(uint16_t *)buffer, 0x40, scratch);
*length = (int)rrwcslen((const uint16_t *)buffer);
return buffer;
}
switch (node_kind(w)) {
case 4:
*length = 9;
return (void *)AS3S_undefined;
case 5:
*length = 4;
return (void *)AS3S_null;
case 6:
*length = (w == AS3_FALSE) ? 5 : 4;
return (w == AS3_TRUE) ? (void *)AS3S_true : (void *)AS3S_false;
case 7: {
double d = node_number(w);
if (rr_isnaninf(d) != 0) {
if (rr_isnan(d) != 0) {
*length = 3;
return (void *)AS3S_NaN;
}
if (0.0 < d) {
*length = 8;
return (void *)(s_infinity + 1);
}
*length = 9;
return (void *)s_neginfinity;
}
if (d == 0.0) {
*length = 1;
return (void *)AS3S_zero;
}
as3vm_string_from_number_direct(vm, d, (uint16_t *)buffer, 0x40,
scratch);
*length = (int)rrwcslen((const uint16_t *)buffer);
return buffer;
}
case 8:
*(void **)scratch = value;
*length = string_length(w);
return (void *)string_units(w);
default:
w = (uintptr_t)as3vm_DefaultValue_String_GC(vm, (void *)w);
if (w == AS3_SEVEN) {
return NULL;
}
if (w == *(uintptr_t *)(*(uintptr_t *)((char *)vm + VM_EMPTY_CLASS) +
VM_EMPTY_FIELD)) {
*length = 0;
return (void *)AS3S__nul; /* retail: leaq AS3S__nul(%rip) */
}
*(void **)scratch = (void *)w;
value = (void *)w;
break;
}
}
}
/* ------------------------------------------------------------------ */
/* StringToArrayIndex -- reproduces the retail multi-digit quirk. */
/* ------------------------------------------------------------------ */
int as3vm_StringToArrayIndex(void *value) {
const uint16_t *chars = string_units((uintptr_t)value);
int32_t length = string_length((uintptr_t)value);
int index;
int position;
if (rriswdigit(chars[0]) == 0) {
return -1;
}
index = (int)chars[0] - 0x30;
position = 1;
if (length > 1) {
const uint16_t *p = chars + 1;
do {
if (rriswdigit(*p) == 0) {
return -1;
}
/* RETAIL QUIRK (raw/durango:250, raw/ps3:108): trailing digits are
* accumulated as index*10 + rawCharCode with NO -0x30 subtraction. */
index = (int)(unsigned)*p + index * 10;
if (index < 0) {
return -1;
}
++position;
++p;
} while (position < length);
}
return index;
}
/* ------------------------------------------------------------------ */
/* convert_array_to_vector. */
/* ------------------------------------------------------------------ */
void as3vm_convert_array_to_vector(void *dst, void *src) {
uint8_t *d = (uint8_t *)dst;
uint8_t *s = (uint8_t *)src;
uint8_t *backing = *(uint8_t **)(s + SRC_BACKING);
uintptr_t first = *(uintptr_t *)backing;
*(uint8_t **)(d + 7) = backing;
d[1] = (uint8_t)(d[1] | 1);
*(uintptr_t *)(d + DST_ELEMENT) = first;
}
/* ------------------------------------------------------------------ */
/* ToBoolean. */
/* ------------------------------------------------------------------ */
void *as3vm_to_boolean(void *value) {
uintptr_t w = (uintptr_t)value;
uint8_t kind;
if ((w & 1) == 0) {
return (void *)(((int32_t)((intptr_t)w >> 1) != 0) ? AS3_TRUE : AS3_FALSE);
}
kind = node_kind(w);
if (kind < 4) { /* objects -> true */
return (void *)AS3_TRUE;
}
if (kind < 6) { /* undefined / null -> false */
return (void *)AS3_FALSE;
}
if (kind != 6) {
if (kind == 7) {
double d = node_number(w);
if (d == 0.0) {
return (void *)AS3_FALSE;
}
if (rr_isnan(d) != 0) {
return (void *)AS3_FALSE;
}
} else if (kind == 8 && string_length(w) == 0) {
return (void *)AS3_FALSE;
}
return (void *)AS3_TRUE;
}
return value; /* boolean: identity */
}
bool as3vm_to_boolean_direct(void *value) {
uintptr_t w = (uintptr_t)value;
uint8_t kind;
if ((w & 1) == 0) {
return (int32_t)((intptr_t)w >> 1) != 0;
}
kind = node_kind(w);
if (kind < 4) {
return true;
}
if (kind > 5) {
if (kind == 6) {
return w == AS3_TRUE;
}
if (kind != 7) {
return true;
}
{
double d = node_number(w);
if (d != 0.0 && rr_isnan(d) == 0) {
return true;
}
}
}
return false;
}

View File

@@ -0,0 +1,88 @@
#ifndef IGGY_RECONSTRUCTED_AS3VM_CONVERT_H
#define IGGY_RECONSTRUCTED_AS3VM_CONVERT_H
/*
* Reconstructed public ABI for RAD's as3vm_convert translation unit -- Iggy's
* AS3 / AVM2 ECMAScript type-conversion layer. It coerces tagged AS3 value
* words to Number / String / Int32 / UInt32 / Boolean, drives the valueOf /
* toString primitive coercion (DefaultValue), parses ECMAScript numeric
* strings, and converts an Array's backing store to a Vector.
*
* Source-equivalent recovery of c:\projects\g\src\flash\as3vm_convert.c
*
* The module exports exactly 15 functions on all four platforms and owns NO
* externally named data global: every AS3 value it touches is a tagged word
* owned by the caller / the VM context, and the special doubles / boolean /
* null-undefined sentinels live in imported DATA symbols (as3vm_NaNd,
* as3vm_P_Infinity, as3vm_N_Infinity, as3vm_nullundef_storage,
* as3vm_truefalse_storage). durango and vita carry one extra file-static
* helper (is_as3_white) that orbis and ps3 inline, so the retail
* source_functions count is 16/15/15/16 while the exported ABI stays 15.
*
* VALUE TAGGING: a small integer boxes to (value << 1) with a clear low bit; a
* heap value is (node_pointer + 1) with a set low bit (the node is 16-aligned
* so the +1 tag is unambiguous). node[0] is the kind byte (4 undefined, 5
* null, 6 boolean, 7 heap-number with the double at node+8, 8 heap-string with
* the descriptor pointer at node+8; the descriptor holds an int32 length at
* desc+7 and the UTF-16 units at desc+0xb). The signatures below follow the
* 64-bit DURANGO ABI; ps3/vita are ILP32 (ps3 big-endian) but the exported
* symbol names and argument shapes are invariant across all four targets.
*/
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Raw ECMAScript ToInt32 of a double (NaN/Inf -> 0, else floor + fmod 2^32
* wrap toward zero); returns the canonical uint32 zero-extended into an
* int64. */
int64_t as3vm_NumberToInt32(double value);
/* Value -> Number (boxed): int / heap-number identity, null -> NULL,
* undefined -> boxed NaN, string -> parsed, object -> DefaultValue(Number). */
void *as3vm_ToNumber_GC(void *vm, void *value);
/* Value -> Number (unboxed into *out); returns 1 on success. */
int as3vm_ToNumberDirect_GC(void *vm, void *value, double *out);
/* Value -> ECMAScript Int32 / UInt32 (unboxed into *out); returns 1 on
* success. ToInt32FailNAN additionally fails (returns 0) on NaN / +/-Inf. */
int as3vm_ToInt32_GC(void *vm, void *value, int32_t *out);
int as3vm_ToInt32FailNAN_GC(void *vm, void *value, int32_t *out);
int as3vm_ToUInt32_GC(void *vm, void *value, uint32_t *out);
/* Value -> String: numeric via as3vm_string_from_number_GC, null / undefined /
* NaN / +/-Inf / zero return VM-context interned strings, string identity. */
void *as3vm_ToString_GC(void *vm, void *value);
/* Value -> UTF-16 character array: returns a pointer to the units and stores
* the length in *length (scratch receives the coerced value word). */
void *as3vm_ToCharArray_GC(void *vm, void *value, void *buffer, int *length,
void *scratch);
/* String -> array index (uint32) or -1 if the first unit is not a digit. */
int as3vm_StringToArrayIndex(void *value);
/* Copy an Array's backing store into a Vector node and flag it. */
void as3vm_convert_array_to_vector(void *dst, void *src);
/* ECMAScript ToBoolean: the boxing variant returns the shared true / false
* objects, the direct variant returns the raw truth value. */
void *as3vm_to_boolean(void *value);
bool as3vm_to_boolean_direct(void *value);
/* DefaultValue -- valueOf / toString primitive coercion (hint None / Number /
* String). Returns the primitive value word, or 7 on failure. */
void *as3vm_DefaultValue_None_GC(void *vm, void *value);
void *as3vm_DefaultValue_Number_GC(void *vm, void *value);
void *as3vm_DefaultValue_String_GC(void *vm, void *value);
#ifdef __cplusplus
}
#endif
#endif /* IGGY_RECONSTRUCTED_AS3VM_CONVERT_H */

View File

@@ -80,3 +80,7 @@ as3vm_class 24 7 durango complete
as3vm_class 7 7 orbis complete
as3vm_class 11 7 ps3 complete
as3vm_class 12 7 vita complete
as3vm_convert 16 15 durango complete
as3vm_convert 15 15 orbis complete
as3vm_convert 15 15 ps3 complete
as3vm_convert 16 15 vita complete
1 module source_functions external_functions platforms status
80 as3vm_class 7 7 orbis complete
81 as3vm_class 11 7 ps3 complete
82 as3vm_class 12 7 vita complete
83 as3vm_convert 16 15 durango complete
84 as3vm_convert 15 15 orbis complete
85 as3vm_convert 15 15 ps3 complete
86 as3vm_convert 16 15 vita complete

View File

@@ -0,0 +1,307 @@
/*
* Host harness for the reconstructed as3vm_convert translation unit.
*
* as3vm_convert is Iggy's AS3 / AVM2 ECMAScript type-conversion layer:
* ToNumber / ToNumberDirect / ToString / ToInt32 / ToUInt32 / ToInt32FailNAN /
* NumberToInt32 / ToBoolean, DefaultValue (None/Number/String, the
* valueOf/toString primitive coercion), StringToArrayIndex, ToCharArray, and
* array->vector conversion. It exports EXACTLY 15 entry points on all four
* platforms and -- LIKE the sibling as3vm_create / as3vm_class, UNLIKE as3vm_gc
* -- owns NO externally named data global; every AS3 value it touches is a
* tagged word owned by the caller / the VM context.
*
* VALUE / NUMBER-BOX MODEL (recovered from raw/durango, cross-checked against
* the 32-bit ps3 layout -- offsets below are 64-bit DURANGO; the runtime test
* builds ONLY the durango dylib):
* - A value word is tagged: (word & 1) == 0 is a SMALL INT whose value is
* word>>1 (arithmetic); (word & 1) == 1 is a HEAP pointer whose object node
* starts at word-1, so the 1-byte KIND lives at word[-1] and the payload at
* word+7 (== node+8).
* - KIND bytes: 4 undefined, 5 null, 6 boolean, 7 heap-number
* (double @ node+8, i.e. *(double*)(word+7)), 8 heap-string
* (descriptor ptr @ node+8; descriptor holds int32 length @ desc+7 and
* UTF-16 chars @ desc+0xb).
* - The boolean true/false objects live in as3vm_truefalse_storage and the
* null/undefined sentinels in as3vm_nullundef_storage (both DATA imports on
* all four platforms -- dot-UNprefixed on ps3, confirming DATA not calls).
* - NaN / +Infinity / -Infinity source doubles are the as3vm_NaNd /
* as3vm_P_Infinity / as3vm_N_Infinity DATA globals.
*
* The symbols supplied here are exactly the genuine nm ' U ' imports of the
* retail object. This DURANGO harness models them as functional / recording
* stubs so the durango dylib links and the pure numeric/string paths actually
* run:
* - value / string construction (as3vm_create + as3vm string module):
* as3vm_make_number_GC -> boxes a double into a kind-7 node + records the
* double (drives ToNumber's string / NaN / Infinity results);
* as3vm_string_from_number_GC -> records the double, returns a fake string
* box (drives ToString's numeric path);
* as3vm_string_from_number_direct -> records the double and formats it as
* UTF-16 decimal into the caller buffer (drives ToCharArray).
* - ECMAScript number parsing (rr string helpers): rr_utf16_read_decimal_
* ecmascript / rr_utf16_read_hex_ecmascript -> functional strtod/strtol
* parsers over UTF-16; rriswdigit -> real 0-9 test; rrwcslen -> real UTF-16
* length.
* - float classification (rrMath): rr_isnan -> host isnan; rr_isnaninf ->
* host isnan||isinf.
* - DATA sentinels: as3vm_NaNd / as3vm_P_Infinity / as3vm_N_Infinity (doubles)
* and as3vm_nullundef_storage / as3vm_truefalse_storage (byte storage),
* provided as data referenced by address.
* - object primitive coercion (as3vm_interpreter, unbuilt):
* as3vm_do_func_call_vv_GC / as3vm_get_property_qname_GC -> record-only
* stubs. DefaultValue's live valueOf/toString dispatch is DEFERRED
* (structural only -- see the runtime test docstring); the runtime test
* never drives it, so these are pure linking stubs.
* - libm: floor / fmod resolve against the host and are deliberately NOT
* stubbed (sibling convention) so as3vm_NumberToInt32's real ECMAScript
* ToInt32 arithmetic executes end to end.
*/
#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ---- Recording counters. ---- */
static size_t make_number_count;
static size_t string_from_number_count;
static size_t string_from_number_direct_count;
static size_t get_property_count;
static size_t do_func_call_count;
static size_t isnan_count;
static size_t isnaninf_count;
static size_t decimal_parse_count;
static size_t hex_parse_count;
static double last_make_number_double;
static double last_string_from_number_double;
static double last_string_from_number_direct_double;
/* Bump pool backing the box-allocating stubs. */
static uint8_t box_pool[1 << 20];
static size_t box_used;
static void *box_alloc(size_t size) {
size_t base = (box_used + 15u) & ~(size_t)15u;
if (base + size > sizeof(box_pool)) {
return NULL;
}
box_used = base + size;
return box_pool + base;
}
/* ---- DATA sentinels (genuine imports, all four platforms). ---- */
double as3vm_NaNd;
double as3vm_P_Infinity;
double as3vm_N_Infinity;
uint8_t as3vm_nullundef_storage[64];
uint8_t as3vm_truefalse_storage[64];
void as3vm_convert_test_reset(void) {
make_number_count = 0;
string_from_number_count = 0;
string_from_number_direct_count = 0;
get_property_count = 0;
do_func_call_count = 0;
isnan_count = 0;
isnaninf_count = 0;
decimal_parse_count = 0;
hex_parse_count = 0;
last_make_number_double = 0.0;
last_string_from_number_double = 0.0;
last_string_from_number_direct_double = 0.0;
box_used = 0;
/* The retail globals hold the canonical special doubles; re-stamp them so a
* fresh test always reads correct bit patterns. */
as3vm_NaNd = NAN;
as3vm_P_Infinity = INFINITY;
as3vm_N_Infinity = -INFINITY;
memset(as3vm_nullundef_storage, 0, sizeof(as3vm_nullundef_storage));
memset(as3vm_truefalse_storage, 0, sizeof(as3vm_truefalse_storage));
}
/* ---- Count / last-value accessors. ---- */
size_t as3vm_convert_test_make_number_count(void) { return make_number_count; }
size_t as3vm_convert_test_string_from_number_count(void) {
return string_from_number_count;
}
size_t as3vm_convert_test_string_from_number_direct_count(void) {
return string_from_number_direct_count;
}
size_t as3vm_convert_test_get_property_count(void) { return get_property_count; }
size_t as3vm_convert_test_do_func_call_count(void) { return do_func_call_count; }
size_t as3vm_convert_test_isnan_count(void) { return isnan_count; }
size_t as3vm_convert_test_isnaninf_count(void) { return isnaninf_count; }
size_t as3vm_convert_test_decimal_parse_count(void) { return decimal_parse_count; }
size_t as3vm_convert_test_hex_parse_count(void) { return hex_parse_count; }
double as3vm_convert_test_last_make_number_double(void) {
return last_make_number_double;
}
double as3vm_convert_test_last_string_from_number_double(void) {
return last_string_from_number_double;
}
double as3vm_convert_test_last_string_from_number_direct_double(void) {
return last_string_from_number_direct_double;
}
/* ---- Value / string construction. ---- */
void *as3vm_make_number_GC(void *vm, double value) {
(void)vm;
++make_number_count;
last_make_number_double = value;
uint8_t *node = box_alloc(16u);
if (node == NULL) {
return NULL;
}
node[0] = 7; /* heap-number kind */
memcpy(node + 8, &value, sizeof(value));
return node + 1; /* interior tagged pointer */
}
void *as3vm_string_from_number_GC(void *vm, double value) {
(void)vm;
++string_from_number_count;
last_string_from_number_double = value;
uint8_t *node = box_alloc(16u);
if (node == NULL) {
return NULL;
}
node[0] = 8; /* heap-string kind */
return node + 1;
}
/* Format a double as UTF-16 decimal into buf (host snprintf then widen). */
void as3vm_string_from_number_direct(void *vm, double value, uint16_t *buf,
int capacity, void *scratch) {
(void)vm;
(void)scratch;
++string_from_number_direct_count;
last_string_from_number_direct_double = value;
if (buf == NULL || capacity <= 0) {
return;
}
char ascii[64];
int n;
if (value == (double)(long long)value) {
n = snprintf(ascii, sizeof(ascii), "%lld", (long long)value);
} else {
n = snprintf(ascii, sizeof(ascii), "%g", value);
}
if (n < 0) {
n = 0;
}
int limit = capacity - 1;
int i = 0;
for (; i < n && i < limit; ++i) {
buf[i] = (uint16_t)(unsigned char)ascii[i];
}
buf[i] = 0;
}
/* ---- Object primitive coercion (as3vm_interpreter, unbuilt) -- record. ---- */
void *as3vm_get_property_qname_GC(void *vm, void *object, void *qname) {
(void)vm;
(void)object;
(void)qname;
++get_property_count;
return NULL;
}
void as3vm_do_func_call_vv_GC(void *vm, void *result, long callee, long argptr,
int a, int b) {
(void)vm;
(void)result;
(void)callee;
(void)argptr;
(void)a;
(void)b;
++do_func_call_count;
}
/* ---- Float classification (rrMath). ---- */
int rr_isnan(double value) {
++isnan_count;
return isnan(value) ? 1 : 0;
}
int rr_isnaninf(double value) {
++isnaninf_count;
return (isnan(value) || isinf(value)) ? 1 : 0;
}
/* ---- ECMAScript number parsing (rr string helpers). ---- */
int rriswdigit(int ch) { return (ch >= '0' && ch <= '9') ? 1 : 0; }
size_t rrwcslen(const uint16_t *text) {
size_t length = 0;
if (text != NULL) {
while (text[length] != 0) {
++length;
}
}
return (int)length;
}
static int utf16_to_ascii(const uint16_t *chars, uint32_t count, char *out,
size_t out_size) {
size_t i = 0;
for (; i < count && i + 1 < out_size; ++i) {
uint16_t c = chars[i];
out[i] = (c < 0x80) ? (char)c : '?';
}
out[i] = '\0';
return (int)i;
}
int rr_utf16_read_decimal_ecmascript(const uint16_t *chars, uint32_t count,
const uint16_t **endptr, double *out,
int flags) {
(void)flags;
++decimal_parse_count;
char ascii[128];
int copied = utf16_to_ascii(chars, count, ascii, sizeof(ascii));
char *end = ascii;
double value = strtod(ascii, &end);
if (end == ascii) {
return 0;
}
if (out != NULL) {
*out = value;
}
if (endptr != NULL) {
ptrdiff_t consumed = end - ascii;
if (consumed > copied) {
consumed = copied;
}
*endptr = chars + consumed;
}
return 1;
}
int rr_utf16_read_hex_ecmascript(const uint16_t *chars, uint32_t count,
const uint16_t **endptr, double *out,
int flags) {
(void)flags;
++hex_parse_count;
char ascii[128];
int copied = utf16_to_ascii(chars, count, ascii, sizeof(ascii));
char *end = ascii;
long value = strtol(ascii, &end, 16); /* handles a leading 0x prefix */
if (end == ascii) {
return 0;
}
if (out != NULL) {
*out = (double)value;
}
if (endptr != NULL) {
ptrdiff_t consumed = end - ascii;
if (consumed > copied) {
consumed = copied;
}
*endptr = chars + consumed;
}
return 1;
}

View File

@@ -0,0 +1,471 @@
"""Runtime tests for the reconstructed as3vm_convert translation unit.
RED STATE: as3vm_convert.c / as3vm_convert.h do not exist yet, so setUpClass
raises "missing as3vm_convert runtime inputs". Every assertion below is grounded
in a specific line of iggy-decompiled/raw/durango/as3vm_convert.c (cited inline)
so a faithful DURANGO reconstruction turns these green.
as3vm_convert is Iggy's AS3 / AVM2 ECMAScript type-conversion layer: ToNumber /
ToNumberDirect / ToString / ToInt32 / ToUInt32 / ToInt32FailNAN / NumberToInt32 /
ToBoolean, DefaultValue (valueOf/toString primitive coercion), StringToArrayIndex,
ToCharArray and array->vector conversion. It exports EXACTLY 15 entry points on
all four platforms and -- LIKE the sibling as3vm_create / as3vm_class, UNLIKE
as3vm_gc -- owns NO externally named data global, so there is no owned-globals
runtime test here. This module is MOSTLY PURE numeric/string math, so the pins
below exercise the real ECMAScript arithmetic end to end.
VALUE / NUMBER-BOX MODEL (raw/durango, cross-checked against the 32-bit ps3
layout; offsets here are 64-bit DURANGO -- the runtime test builds ONLY the
durango dylib):
- A value word is tagged: (word & 1) == 0 is a SMALL INT of value word>>1
(arithmetic); (word & 1) == 1 is a HEAP pointer whose node starts at word-1,
so the 1-byte KIND is at word[-1] and the payload at word+7 (node+8).
- KIND bytes: 4 undefined, 5 null, 6 boolean, 7 heap-number (double @ node+8),
8 heap-string (descriptor @ node+8; descriptor holds int32 length @ desc+7,
UTF-16 chars @ desc+0xb).
- The value-tagging is identical to as3vm_create (small int = v<<1, heap =
node+1).
WHAT IS PINNED (real, deterministic DURANGO behavior):
- as3vm_NumberToInt32's full ECMAScript ToInt32 arithmetic (raw:189-224):
NaN/Inf -> 0 (rr_isnaninf), 0.0 -> 0, else floor + fmod 2^32 wrap toward
zero, returning the canonical uint32 as a longlong.
- as3vm_ToInt32_GC / as3vm_ToInt32FailNAN_GC / as3vm_ToUInt32_GC end-to-end
over int-tagged and heap-number inputs (raw:377-399, 346-371, 763-788),
including FailNAN's NaN/Inf -> failure (return 0) contract.
- as3vm_ToNumberDirect_GC's int / heap-number / null / undefined / numeric-
string coercions (raw:407-522).
- as3vm_ToNumber_GC's int / heap-number identity, null -> NULL, undefined ->
make_number(NaN) (raw:530-695).
- as3vm_ToString_GC's int / heap-number -> string_from_number and the
null / undefined / NaN / zero VM-context interned-string returns
(raw:701-757).
- as3vm_ToCharArray_GC's undefined (len 9) / null (len 4) / heap-zero (len 1)
length contract (raw:264-340).
- as3vm_to_boolean / as3vm_to_boolean_direct's ECMAScript ToBoolean over int
and heap-number inputs (raw:810-878).
- as3vm_StringToArrayIndex's single-digit index + non-digit rejection
(raw:230-258).
- as3vm_convert_array_to_vector's pure struct copy (raw:794-804).
DEFERRED (flagged for the impl / review phase, NOT exercised here):
- DefaultValue_None/Number/String_GC's live valueOf/toString dispatch
(raw:6-181) -- deep VM-context + operand-stack + as3vm_do_func_call_vv_GC
driven; pinned STRUCTURALLY ONLY (linking stubs, never invoked).
- StringToArrayIndex's MULTI-DIGIT accumulator: BOTH durango (raw:250) and ps3
independently decompile it as `index = index*10 + rawCharCode` (NO -0x30 on
trailing digits), so multi-digit results are a retail quirk left unpinned
pending impl reconciliation; only the robust single-digit / rejection cases
are asserted.
- The 0x/Infinity/-Infinity string parse branches and ToCharArray's numeric
formatting depend on the harness parser/formatter stubs, so their content is
not pinned (only invocation / length).
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 math
import shutil
from pathlib import Path
import struct
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
RECONSTRUCTED = ROOT / "iggy-decompiled/src/reconstructed"
SOURCE = RECONSTRUCTED / "as3vm_convert.c"
HEADER = RECONSTRUCTED / "as3vm_convert.h"
SUPPORT = ROOT / "tests/support/as3vm_convert_test_support.c"
# AS3 value KIND bytes (node[0], read at tagged word[-1]); raw:288-325.
KIND_UNDEFINED = 4
KIND_NULL = 5
KIND_BOOL = 6
KIND_NUMBER = 7
KIND_STRING = 8
# DURANGO VM-context interned-string offsets returned by ToString (raw:719-745).
STR_UNDEFINED = 0x2791
STR_NULL = 0x27A1
STR_TRUE = 0x27B1
STR_FALSE = 0x27C1
STR_NAN = 0x27D1
STR_ZERO = 0x27E1
STR_PINF = 0x27F1
STR_NINF = 0x2801
MASK64 = (1 << 64) - 1
def _tag_int(value):
# Small-int tagging: value<<1 with low bit clear (raw:422-423 inverse).
return (value << 1) & MASK64
class ReconstructedAs3vmConvertTests(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_convert runtime inputs: " + ", ".join(missing))
cls.temp = tempfile.TemporaryDirectory()
cls.base = Path(cls.temp.name) / "as3vm_convert.dylib"
build = subprocess.run([
"clang", "-dynamiclib", "-std=c11", "-O2", "-Wall", "-Wextra",
"-Werror", "-Wl,-undefined,dynamic_lookup",
"-DIGGY_RECONSTRUCT_AS3VM_CONVERT_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_convert_{self._testMethodName}.dylib")
shutil.copyfile(self.base, unique)
self.lib = ctypes.CDLL(str(unique))
self._bind(self.lib)
self.lib.as3vm_convert_test_reset()
self._keep = []
# A generously sized VM context so the ToString interned-string offsets
# (vm + 0x27xx / 0x28xx) land inside the buffer.
self.vm = self._buffer(0x3000)
def _bind(self, lib):
void_p = ctypes.c_void_p
c_double = ctypes.c_double
c_int = ctypes.c_int
lib.as3vm_convert_test_reset.restype = None
lib.as3vm_convert_test_reset.argtypes = []
for name in ("make_number", "string_from_number",
"string_from_number_direct", "get_property",
"do_func_call", "isnan", "isnaninf", "decimal_parse",
"hex_parse"):
fn = getattr(lib, f"as3vm_convert_test_{name}_count")
fn.restype = ctypes.c_size_t
fn.argtypes = []
for name in ("make_number", "string_from_number",
"string_from_number_direct"):
fn = getattr(lib, f"as3vm_convert_test_last_{name}_double")
fn.restype = c_double
fn.argtypes = []
lib.as3vm_NumberToInt32.restype = ctypes.c_int64
lib.as3vm_NumberToInt32.argtypes = [c_double]
lib.as3vm_to_boolean.restype = void_p
lib.as3vm_to_boolean.argtypes = [void_p]
lib.as3vm_to_boolean_direct.restype = ctypes.c_bool
lib.as3vm_to_boolean_direct.argtypes = [void_p]
lib.as3vm_ToNumberDirect_GC.restype = c_int
lib.as3vm_ToNumberDirect_GC.argtypes = [
void_p, void_p, ctypes.POINTER(c_double)]
lib.as3vm_ToNumber_GC.restype = void_p
lib.as3vm_ToNumber_GC.argtypes = [void_p, void_p]
lib.as3vm_ToInt32_GC.restype = c_int
lib.as3vm_ToInt32_GC.argtypes = [
void_p, void_p, ctypes.POINTER(ctypes.c_int32)]
lib.as3vm_ToInt32FailNAN_GC.restype = c_int
lib.as3vm_ToInt32FailNAN_GC.argtypes = [
void_p, void_p, ctypes.POINTER(ctypes.c_int32)]
lib.as3vm_ToUInt32_GC.restype = c_int
lib.as3vm_ToUInt32_GC.argtypes = [
void_p, void_p, ctypes.POINTER(ctypes.c_uint32)]
lib.as3vm_ToString_GC.restype = void_p
lib.as3vm_ToString_GC.argtypes = [void_p, void_p]
lib.as3vm_ToCharArray_GC.restype = void_p
lib.as3vm_ToCharArray_GC.argtypes = [
void_p, void_p, void_p, ctypes.POINTER(c_int), void_p]
lib.as3vm_StringToArrayIndex.restype = c_int
lib.as3vm_StringToArrayIndex.argtypes = [void_p]
lib.as3vm_convert_array_to_vector.restype = None
lib.as3vm_convert_array_to_vector.argtypes = [void_p, void_p]
# ---- object builders --------------------------------------------------- #
def _buffer(self, size):
buf = (ctypes.c_uint8 * size)()
self._keep.append(buf)
return ctypes.addressof(buf)
def _heap(self, kind, payload=b""):
# node[0] = kind, payload from node+8; tagged word = node+1 (raw:288).
node = self._buffer(max(16, 8 + len(payload)))
ctypes.c_uint8.from_address(node).value = kind
if payload:
ctypes.memmove(node + 8, payload, len(payload))
return node + 1
def _number(self, value):
return self._heap(KIND_NUMBER, struct.pack("<d", value))
def _string(self, text):
# descriptor: int32 length @ +7, UTF-16 chars @ +0xb (raw:239-247).
units = [ord(ch) for ch in text]
desc = self._buffer(0x0B + 2 * (len(units) + 1))
ctypes.c_int32.from_address(desc + 0x07).value = len(units)
for i, unit in enumerate(units):
ctypes.c_uint16.from_address(desc + 0x0B + 2 * i).value = unit
return self._heap(KIND_STRING, struct.pack("<Q", desc))
def _count(self, name):
return getattr(self.lib, f"as3vm_convert_test_{name}_count")()
def _last(self, name):
return getattr(self.lib, f"as3vm_convert_test_last_{name}_double")()
# ---- as3vm_NumberToInt32 ---------------------------------------------- #
def test_number_to_int32_ecmascript_wrap(self):
# raw:189-224 ECMAScript ToInt32 on a raw double: NaN/Inf -> 0, 0 -> 0,
# else floor toward zero then fmod 2^32, returning the canonical uint32.
f = self.lib.as3vm_NumberToInt32
self.assertEqual(f(0.0), 0)
self.assertEqual(f(5.0), 5)
self.assertEqual(f(2.9), 2)
self.assertEqual(f(4294967297.0), 1) # 2^32 + 1 -> 1
self.assertEqual(f(4294967296.0), 0) # 2^32 -> 0
self.assertEqual(f(-1.0), 0xFFFFFFFF) # -1 -> 2^32-1
self.assertEqual(f(-2.5), 0xFFFFFFFE) # floor toward 0 then wrap
self.assertEqual(f(float("nan")), 0)
self.assertEqual(f(float("inf")), 0)
self.assertEqual(f(float("-inf")), 0)
# ---- as3vm_ToInt32_GC / FailNAN / ToUInt32 ---------------------------- #
def test_to_int32_int_and_number(self):
# raw:384-398 int-tagged returns v>>1 directly; heap-number routes
# through ToNumberDirect + NumberToInt32.
out = ctypes.c_int32(0)
self.assertEqual(self.lib.as3vm_ToInt32_GC(
self.vm, _tag_int(5), ctypes.byref(out)), 1)
self.assertEqual(out.value, 5)
self.assertEqual(self.lib.as3vm_ToInt32_GC(
self.vm, _tag_int(-7), ctypes.byref(out)), 1)
self.assertEqual(out.value, -7)
self.assertEqual(self.lib.as3vm_ToInt32_GC(
self.vm, self._number(4294967297.0), ctypes.byref(out)), 1)
self.assertEqual(out.value, 1)
self.assertEqual(self.lib.as3vm_ToInt32_GC(
self.vm, self._number(-1.0), ctypes.byref(out)), 1)
self.assertEqual(out.value & 0xFFFFFFFF, 0xFFFFFFFF) # -1
self.assertEqual(self.lib.as3vm_ToInt32_GC(
self.vm, self._number(float("nan")), ctypes.byref(out)), 1)
self.assertEqual(out.value, 0)
def test_to_int32_failnan_rejects_nan_and_inf(self):
# raw:361-370 the FailNAN variant returns 0 (failure) when ToNumber
# yields NaN or +/-Inf, otherwise behaves like ToInt32.
out = ctypes.c_int32(0x1234)
self.assertEqual(self.lib.as3vm_ToInt32FailNAN_GC(
self.vm, _tag_int(9), ctypes.byref(out)), 1)
self.assertEqual(out.value, 9)
self.assertEqual(self.lib.as3vm_ToInt32FailNAN_GC(
self.vm, self._number(4294967297.0), ctypes.byref(out)), 1)
self.assertEqual(out.value, 1)
self.assertEqual(self.lib.as3vm_ToInt32FailNAN_GC(
self.vm, self._number(float("nan")), ctypes.byref(out)), 0)
self.assertEqual(self.lib.as3vm_ToInt32FailNAN_GC(
self.vm, self._number(float("inf")), ctypes.byref(out)), 0)
def test_to_uint32_int_and_number(self):
# raw:769-787 ToUInt32 stores the low 32 bits of the ECMAScript ToUint32
# of int-tagged and heap-number inputs.
out = ctypes.c_uint32(0)
self.assertEqual(self.lib.as3vm_ToUInt32_GC(
self.vm, _tag_int(5), ctypes.byref(out)), 1)
self.assertEqual(out.value, 5)
self.assertEqual(self.lib.as3vm_ToUInt32_GC(
self.vm, _tag_int(-1), ctypes.byref(out)), 1)
self.assertEqual(out.value, 0xFFFFFFFF)
self.assertEqual(self.lib.as3vm_ToUInt32_GC(
self.vm, self._number(-1.0), ctypes.byref(out)), 1)
self.assertEqual(out.value, 0xFFFFFFFF)
self.assertEqual(self.lib.as3vm_ToUInt32_GC(
self.vm, self._number(4294967297.0), ctypes.byref(out)), 1)
self.assertEqual(out.value, 1)
# ---- as3vm_ToNumberDirect_GC ------------------------------------------ #
def test_to_number_direct_primitives(self):
# raw:422-521 int -> (double)int, heap-number -> its double, null -> 0,
# undefined -> NaN; all return success (1).
out = ctypes.c_double(-123.0)
self.assertEqual(self.lib.as3vm_ToNumberDirect_GC(
self.vm, _tag_int(5), ctypes.byref(out)), 1)
self.assertEqual(out.value, 5.0)
self.assertEqual(self.lib.as3vm_ToNumberDirect_GC(
self.vm, _tag_int(-3), ctypes.byref(out)), 1)
self.assertEqual(out.value, -3.0)
self.assertEqual(self.lib.as3vm_ToNumberDirect_GC(
self.vm, self._number(3.5), ctypes.byref(out)), 1)
self.assertEqual(out.value, 3.5)
self.assertEqual(self.lib.as3vm_ToNumberDirect_GC(
self.vm, self._heap(KIND_NULL), ctypes.byref(out)), 1)
self.assertEqual(out.value, 0.0)
out = ctypes.c_double(0.0)
self.assertEqual(self.lib.as3vm_ToNumberDirect_GC(
self.vm, self._heap(KIND_UNDEFINED), ctypes.byref(out)), 1)
self.assertTrue(math.isnan(out.value))
def test_to_number_direct_numeric_string(self):
# raw:510-521 a decimal-leading string routes through
# rr_utf16_read_decimal_ecmascript, yielding its parsed double.
out = ctypes.c_double(0.0)
self.assertEqual(self.lib.as3vm_ToNumberDirect_GC(
self.vm, self._string("42"), ctypes.byref(out)), 1)
self.assertEqual(out.value, 42.0)
self.assertEqual(self._count("decimal_parse"), 1)
# ---- as3vm_ToNumber_GC ------------------------------------------------ #
def test_to_number_identity_null_and_undefined(self):
# raw:548-694 int / heap-number pass through unchanged; null -> NULL;
# undefined boxes NaN via make_number.
numbox = self._number(2.0)
self.assertEqual(self.lib.as3vm_ToNumber_GC(self.vm, numbox), numbox)
self.assertEqual(
self.lib.as3vm_ToNumber_GC(self.vm, _tag_int(5)), _tag_int(5))
self.assertIsNone(
self.lib.as3vm_ToNumber_GC(self.vm, self._heap(KIND_NULL)))
self.assertIsNotNone(
self.lib.as3vm_ToNumber_GC(self.vm, self._heap(KIND_UNDEFINED)))
self.assertEqual(self._count("make_number"), 1)
self.assertTrue(math.isnan(self._last("make_number")))
# ---- as3vm_ToString_GC ------------------------------------------------ #
def test_to_string_numeric_paths_call_string_from_number(self):
# raw:711-747 int and non-special heap-number stringify via
# as3vm_string_from_number_GC with the exact double.
self.assertIsNotNone(self.lib.as3vm_ToString_GC(self.vm, _tag_int(5)))
self.assertEqual(self._last("string_from_number"), 5.0)
self.assertIsNotNone(
self.lib.as3vm_ToString_GC(self.vm, self._number(3.5)))
self.assertEqual(self._last("string_from_number"), 3.5)
self.assertEqual(self._count("string_from_number"), 2)
def test_to_string_interned_constants(self):
# raw:719-745 undefined / null / NaN / zero return distinct VM-context
# interned-string pointers at fixed offsets.
self.assertEqual(
self.lib.as3vm_ToString_GC(self.vm, self._heap(KIND_UNDEFINED)),
self.vm + STR_UNDEFINED)
self.assertEqual(
self.lib.as3vm_ToString_GC(self.vm, self._heap(KIND_NULL)),
self.vm + STR_NULL)
self.assertEqual(
self.lib.as3vm_ToString_GC(self.vm, self._number(0.0)),
self.vm + STR_ZERO)
self.assertEqual(
self.lib.as3vm_ToString_GC(self.vm, self._number(float("nan"))),
self.vm + STR_NAN)
self.assertEqual(
self.lib.as3vm_ToString_GC(self.vm, self._number(float("inf"))),
self.vm + STR_PINF)
self.assertEqual(
self.lib.as3vm_ToString_GC(self.vm, self._number(float("-inf"))),
self.vm + STR_NINF)
def test_to_string_string_is_identity(self):
# raw:749-750 a heap-string passes straight through.
s = self._string("hello")
self.assertEqual(self.lib.as3vm_ToString_GC(self.vm, s), s)
# ---- as3vm_ToCharArray_GC --------------------------------------------- #
def test_to_char_array_lengths(self):
# raw:288-322 undefined -> len 9, null -> len 4, heap-zero -> len 1.
buf = self._buffer(0x80)
length = ctypes.c_int(-1)
tmp = ctypes.c_void_p(0)
self.assertIsNotNone(self.lib.as3vm_ToCharArray_GC(
self.vm, self._heap(KIND_UNDEFINED), buf, ctypes.byref(length),
ctypes.byref(tmp)))
self.assertEqual(length.value, 9)
self.lib.as3vm_ToCharArray_GC(
self.vm, self._heap(KIND_NULL), buf, ctypes.byref(length),
ctypes.byref(tmp))
self.assertEqual(length.value, 4)
self.lib.as3vm_ToCharArray_GC(
self.vm, self._number(0.0), buf, ctypes.byref(length),
ctypes.byref(tmp))
self.assertEqual(length.value, 1)
# ---- as3vm_to_boolean / as3vm_to_boolean_direct ----------------------- #
def test_to_boolean_direct_int_and_number(self):
# raw:859-877 int-tagged truthiness is (v != 0); heap-number is
# (d != 0 && !isnan).
f = self.lib.as3vm_to_boolean_direct
self.assertFalse(f(_tag_int(0)))
self.assertTrue(f(_tag_int(5)))
self.assertTrue(f(_tag_int(-1)))
self.assertFalse(f(self._number(0.0)))
self.assertTrue(f(self._number(2.0)))
self.assertFalse(f(self._number(float("nan"))))
self.assertTrue(f(self._number(float("inf"))))
def test_to_boolean_returns_stable_distinct_sentinels(self):
# raw:817-846 the boxing variant returns the shared false / true
# objects: zero -> false, non-zero -> true, stable across calls.
r_false = self.lib.as3vm_to_boolean(_tag_int(0))
r_true = self.lib.as3vm_to_boolean(_tag_int(5))
self.assertIsNotNone(r_false)
self.assertIsNotNone(r_true)
self.assertNotEqual(r_false, r_true)
self.assertEqual(self.lib.as3vm_to_boolean(_tag_int(0)), r_false)
self.assertEqual(self.lib.as3vm_to_boolean(_tag_int(7)), r_true)
self.assertEqual(
self.lib.as3vm_to_boolean(self._number(0.0)), r_false)
self.assertEqual(
self.lib.as3vm_to_boolean(self._number(2.0)), r_true)
# ---- as3vm_StringToArrayIndex ----------------------------------------- #
def test_string_to_array_index_single_digit_and_reject(self):
# raw:240-257 a single ASCII digit yields its value; a non-digit lead
# char yields the -1 sentinel. (Multi-digit accumulation is a retail
# quirk left unpinned -- see the module docstring.)
for text, expected in (("0", 0), ("5", 5), ("9", 9)):
self.assertEqual(
self.lib.as3vm_StringToArrayIndex(self._string(text)),
expected, text)
self.assertEqual(
self.lib.as3vm_StringToArrayIndex(self._string("a")), -1)
self.assertEqual(
self.lib.as3vm_StringToArrayIndex(self._string("x9")), -1)
# ---- as3vm_convert_array_to_vector ------------------------------------ #
def test_convert_array_to_vector_copies_backing_and_sets_flag(self):
# raw:799-803 copies the array's +0x48 backing into dst+7, ORs bit 0
# into dst+1, and stores the first element into dst+0x1f.
backing = self._buffer(0x40)
first_element = 0xCAFEBABEDEADBEEF
ctypes.c_uint64.from_address(backing).value = first_element
src = self._buffer(0x60)
ctypes.c_uint64.from_address(src + 0x48).value = backing
dst = self._buffer(0x40)
ctypes.c_uint8.from_address(dst + 1).value = 0x80
self.lib.as3vm_convert_array_to_vector(dst, src)
self.assertEqual(ctypes.c_uint64.from_address(dst + 7).value, backing)
self.assertEqual(ctypes.c_uint8.from_address(dst + 1).value, 0x81)
self.assertEqual(
ctypes.c_uint64.from_address(dst + 0x1F).value, first_element)
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,340 @@
"""Cross-platform contract tests for the reconstructed as3vm_convert module.
Mirrors tests/test_reconstructed_as3vm_class_cross.py /
tests/test_reconstructed_as3vm_create_cross.py /
tests/test_reconstructed_as3vm_gc_cross.py (the freshest 4-platform templates in
the same AS3/AVM2 VM cluster). RED until as3vm_convert.c / as3vm_convert.h (and
their CMake / modules.tsv rows) exist; the retail-evidence assertions run now and
prove the nm/strings parsing.
as3vm_convert is Iggy's AS3 / AVM2 ECMAScript type-conversion layer: ToNumber /
ToString / ToInt32 / ToUInt32 / ToBoolean, DefaultValue (valueOf/toString
coercion), StringToArrayIndex, number<->string and array->vector. It is a
4-PLATFORM module (durango 899 / orbis 975 / ps3 518 / vita 1009 raw lines;
retail source_functions 16 / 15 / 15 / 16 -- durango and vita each carry one
extra file-static helper, is_as3_white, that orbis and ps3 inline).
How EXPECTED_* were derived (all four .obj under
work/iggy-native-decomp/<platform>-objects/as3vm_convert.obj, verified with
/opt/homebrew/opt/llvm/bin/llvm-nm and `nm -g`):
EXPECTED_FUNCTIONS = `llvm-nm --extern-only --defined-only <obj>` T-tagged
names, leading '.' stripped on ps3. IDENTICAL 15-name
set on durango/orbis/ps3/vita -- the exported conversion
ABI is invariant even though the internal helper count
varies (16/15/15/16). The .opd descriptors on ps3
surface each export a second time as 'D'; those normalize
to the exported function names and are NOT separate
globals (same handling as as3vm_create / as3vm_gc).
EXPECTED_GLOBALS = {} -- LIKE as3vm_create / as3vm_class (UNLIKE as3vm_gc),
as3vm_convert owns NO externally named data global; nm
shows no B/D/C data symbol on any of the four objects.
(The durango object carries four 'R' read-only constants
-- the __real@... / __xmm@... ToInt32 float / sign-mask
literals -- which are neither T/D/B/C-extern nor globals
in the reconstruction.)
EXPECTED_IMPORTS = the genuine non-scaffolding references present on ALL
FOUR retail objects (INVARIANT -- verified identical):
- value / string construction (as3vm_create +
as3vm string module, partly unbuilt):
as3vm_make_number_GC, as3vm_string_from_number_GC,
as3vm_string_from_number_direct
- object primitive coercion (as3vm_interpreter,
unbuilt): as3vm_do_func_call_vv_GC,
as3vm_get_property_qname_GC
- ECMAScript number parsing (rr string helpers):
rr_utf16_read_decimal_ecmascript,
rr_utf16_read_hex_ecmascript, rriswdigit, rrwcslen
- float classification (rrMath): rr_isnan, rr_isnaninf
- special-double DATA sentinels (referenced by ADDRESS;
dot-UNprefixed on ps3, confirming DATA not calls):
as3vm_NaNd, as3vm_P_Infinity, as3vm_N_Infinity,
as3vm_nullundef_storage, as3vm_truefalse_storage
- libm: fmod (the 2^32 wrap in NumberToInt32)
This real-Iggy/rr/libm set is INVARIANT across the four
platforms.
PLATFORM_IMPORTS = NON-EMPTY here -- DISCREPANCY-WITH-UNIFORMITY, following
the evidence. Unlike the sibling as3vm_gc / as3vm_class
(whose libc lowering was uniform), as3vm_convert's libm /
libc dependencies DIFFER per target because each toolchain
inlines a different subset:
durango: {floor} -- MSVC target keeps floor as
a call, inlines memcmp
orbis: {memcmp} -- FreeBSD SSE4.1 inlines
floor (roundsd), keeps
memcmp
ps3: {floor, memcmp} -- PowerPC keeps both
vita: {floor, memcmp} -- ARMv7 keeps both
(fmod is genuinely invariant -- present on all four -- so
it lives in EXPECTED_IMPORTS; floor and memcmp are the
per-target split. ps3 is only 518 raw lines yet still
imports the full libm/libc set: the line-count variance is
inlining of file-static helpers, not fewer dependencies.)
RUNTIME_ALLOWLISTS = pure toolchain scaffolding residual after subtracting the
genuine import set, verified exact against retail
`llvm-nm --undefined-only`:
durango: _fltused (double math; NO __chkstk /
__security_cookie here --
this TU takes no address of
a stack buffer that trips
the guard)
orbis: _GLOBAL_OFFSET_TABLE_
ps3: {} (empty)
vita: __aeabi_unwind_cpp_pr0, __aeabi_unwind_cpp_pr1,
__stack_chk_fail, __stack_chk_guard
(vita pulls BOTH pr0 and pr1 personalities here, unlike
as3vm_gc which needed only pr0; follow the evidence.)
PROVENANCE = the canonical Windows source path
c:\\projects\\g\\src\\flash\\as3vm_convert.c is the true
upstream path (orbis preserves it verbatim), so the
reconstruction embeds it and the SOURCE assertion checks
it. In the retail objects the provenance string is NOT
uniform -- follow the evidence per platform (like
as3vm_create, NOT the uniform as3vm_gc / as3vm_class):
durango: only the build path
c:\\projects\\g\\build\\...\\as3vm_convert.obj
(no .c string at all)
orbis: c:\\projects\\g\\src\\flash\\as3vm_convert.c
ps3: bare 'as3vm_convert.c'
vita: bare 'as3vm_convert.c'
Run the full suite with python3.12 (`python3.12 -m unittest discover -s tests`):
the machine python3 is 3.14, which SEGFAULTs on the full suite via an unrelated
CPython ctypes-GC bug. Single-module runs are fine on either interpreter; this
cross test's cross-compile/nm logic is python-version-independent.
"""
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_convert.c"
HEADER = RECONSTRUCTED / "as3vm_convert.h"
LLVM_NM = Path("/opt/homebrew/opt/llvm/bin/llvm-nm")
VARIANTS = {
"durango": ("clang", "x86_64-pc-windows-msvc"),
"orbis": ("clang", "x86_64-unknown-freebsd"),
"vita": ("clang", "armv7a-unknown-linux-gnueabihf"),
}
PS3_CLANG = Path("/opt/homebrew/opt/llvm/bin/clang")
if PS3_CLANG.exists():
VARIANTS["ps3"] = (str(PS3_CLANG), "powerpc-unknown-linux-gnu")
# Invariant 15-name exported conversion ABI (leading '.' stripped on ps3).
EXPECTED_FUNCTIONS = {
"as3vm_DefaultValue_None_GC",
"as3vm_DefaultValue_Number_GC",
"as3vm_DefaultValue_String_GC",
"as3vm_NumberToInt32",
"as3vm_StringToArrayIndex",
"as3vm_ToCharArray_GC",
"as3vm_ToInt32FailNAN_GC",
"as3vm_ToInt32_GC",
"as3vm_ToNumberDirect_GC",
"as3vm_ToNumber_GC",
"as3vm_ToString_GC",
"as3vm_ToUInt32_GC",
"as3vm_convert_array_to_vector",
"as3vm_to_boolean",
"as3vm_to_boolean_direct",
}
# as3vm_convert owns no externally named data global; every value it touches is
# a caller-owned tagged word (durango's R float literals are read-only constants).
EXPECTED_GLOBALS = set()
# Genuine non-scaffolding imports present on all four retail objects (invariant).
EXPECTED_IMPORTS = {
# value / string construction (as3vm_create + as3vm string module).
"as3vm_make_number_GC",
"as3vm_string_from_number_GC",
"as3vm_string_from_number_direct",
# object primitive coercion (as3vm_interpreter -- unbuilt).
"as3vm_do_func_call_vv_GC",
"as3vm_get_property_qname_GC",
# ECMAScript number parsing (rr string helpers).
"rr_utf16_read_decimal_ecmascript",
"rr_utf16_read_hex_ecmascript",
"rriswdigit",
"rrwcslen",
# float classification (rrMath).
"rr_isnan",
"rr_isnaninf",
# special-double DATA sentinels (referenced by address).
"as3vm_NaNd",
"as3vm_P_Infinity",
"as3vm_N_Infinity",
"as3vm_nullundef_storage",
"as3vm_truefalse_storage",
# libm the reconstruction lowers on every target.
"fmod",
}
# The libm/libc lowering DIFFERS per target here (unlike the uniform sibling
# templates): floor is inlined on orbis (SSE4.1 roundsd) but called elsewhere,
# and memcmp is inlined on durango but called elsewhere. Follow the evidence.
PLATFORM_IMPORTS = {
"durango": {"floor"},
"orbis": {"memcmp"},
"ps3": {"floor", "memcmp"},
"vita": {"floor", "memcmp"},
}
RUNTIME_ALLOWLISTS = {
"durango": {"_fltused"},
"orbis": {"_GLOBAL_OFFSET_TABLE_"},
"ps3": set(),
"vita": {"__aeabi_unwind_cpp_pr0", "__aeabi_unwind_cpp_pr1",
"__stack_chk_fail", "__stack_chk_guard"},
}
# The provenance string actually embedded in each retail object differs (see the
# module docstring); assert per-platform evidence rather than a uniform path.
RETAIL_PROVENANCE = {
"durango": r"c:\projects\g\build",
"orbis": r"c:\projects\g\src\flash\as3vm_convert.c",
"ps3": "as3vm_convert.c",
"vita": "as3vm_convert.c",
}
def normalized_symbol(name):
name = name.removeprefix(".")
name = name.removeprefix("__imp_")
if name == "_setjmp":
return "setjmp"
return name
class ReconstructedAs3vmConvertCrossTests(unittest.TestCase):
def test_native_provenance_counts_source_path_and_inventory(self):
# (function count, raw line count) per platform, from
# iggy_<platform>.modules.tsv column 3 and `wc -l` on the raw .c. The
# source_functions DIFFER (16/15/15/16) while the exports stay 15.
expected = {
"durango": (16, 899), "orbis": (15, 975),
"ps3": (15, 518), "vita": (16, 1009),
}
for platform, (functions, lines) in expected.items():
modules = ROOT / (
f"iggy-decompiled/symbols/iggy_{platform}.modules.tsv")
row = next(
line for line in modules.read_text(encoding="utf-8").splitlines()
if line.startswith("as3vm_convert\t"))
self.assertEqual(int(row.split("\t")[2]), functions, platform)
raw = ROOT / f"iggy-decompiled/raw/{platform}/as3vm_convert.c"
self.assertEqual(
len(raw.read_text(encoding="utf-8").splitlines()),
lines, platform)
obj = ROOT / (
f"work/iggy-native-decomp/{platform}-objects/as3vm_convert.obj")
symbols = subprocess.run(
["nm", "-g", str(obj)], capture_output=True, text=True)
self.assertEqual(symbols.returncode, 0, (platform, symbols.stderr))
normalized = symbols.stdout.replace(" .", " ")
for symbol in EXPECTED_FUNCTIONS | EXPECTED_GLOBALS:
self.assertIn(symbol, normalized, (platform, symbol))
strings = subprocess.run(
["strings", str(obj)], capture_output=True, text=True)
self.assertIn(RETAIL_PROVENANCE[platform], strings.stdout, platform)
if SOURCE.exists():
cmake = (RECONSTRUCTED / "CMakeLists.txt").read_text(
encoding="utf-8")
self.assertIn(
"iggy_reconstructed_as3vm_convert_${platform}", cmake)
self.assertIn(
"add_library(${target} STATIC as3vm_convert.c)", cmake)
self.assertIn(
"IGGY_RECONSTRUCT_AS3VM_CONVERT_${platform_upper}", cmake)
inventory = (RECONSTRUCTED / "modules.tsv").read_text(
encoding="utf-8")
# Exports are invariant (15) but retail source_functions vary
# (16/15/15/16), so the inventory uses per-platform rows exactly like
# as3vm_gc / as3vm_class (NOT a single combined as3vm_create row).
for platform, functions in (
("durango", 16), ("orbis", 15),
("ps3", 15), ("vita", 16)):
self.assertIn(
f"as3vm_convert\t{functions}\t15\t{platform}\tcomplete",
inventory)
def test_exact_exports_globals_normalized_imports_and_c_cpp_abi(self):
self.assertTrue(SOURCE.exists(), f"missing {SOURCE}")
self.assertTrue(HEADER.exists(), f"missing {HEADER}")
self.assertIn(r"c:\\projects\\g\\src\\flash\\as3vm_convert.c",
SOURCE.read_text(encoding="utf-8"))
function_pointers = "".join(
f" (GenericFn)&{name},\n" for name in sorted(EXPECTED_FUNCTIONS))
probe_text = (
'#include <stdint.h>\n#include "as3vm_convert.h"\n'
'typedef void (*GenericFn)(void);\n'
'static GenericFn convert_abis[] = {\n' + function_pointers + '};\n'
'int use_abis(void) {\n'
' for (unsigned i = 0; '
'i < sizeof(convert_abis) / sizeof(convert_abis[0]); ++i) {\n'
' if (!convert_abis[i]) return 0;\n'
' }\n'
' return 1;\n'
'}\n')
with tempfile.TemporaryDirectory() as directory:
temporary = Path(directory)
for platform, (compiler, target) in VARIANTS.items():
extra = ["-mthumb"] if platform == "vita" else []
output = temporary / f"as3vm_convert_{platform}.o"
build = subprocess.run([
compiler, "-target", target, "-ffreestanding",
"-fno-builtin",
"-c", "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror",
*extra,
f"-DIGGY_RECONSTRUCT_AS3VM_CONVERT_{platform.upper()}=1",
"-I", str(RECONSTRUCTED), str(SOURCE), "-o", str(output),
], capture_output=True, text=True)
self.assertEqual(build.returncode, 0, (platform, build.stderr))
if LLVM_NM.exists():
defined = subprocess.run([
str(LLVM_NM), "--extern-only", "--defined-only",
str(output),
], capture_output=True, text=True)
undefined = subprocess.run([
str(LLVM_NM), "--undefined-only", str(output),
], capture_output=True, text=True)
names = {normalized_symbol(parts[-1])
for line in defined.stdout.splitlines()
if len(parts := line.split()) >= 2 and
parts[-2].upper() in {"T", "D", "B", "C"}}
imports = {normalized_symbol(line.split()[-1])
for line in undefined.stdout.splitlines()
if line.split()}
self.assertEqual(
names, EXPECTED_FUNCTIONS | EXPECTED_GLOBALS, platform)
expected_imports = (
EXPECTED_IMPORTS | PLATFORM_IMPORTS[platform])
self.assertEqual(
imports - RUNTIME_ALLOWLISTS[platform],
expected_imports, (platform, imports))
for language, standard in (("c", "c11"), ("c++", "c++17")):
suffix = "c" if language == "c" else "cpp"
probe = temporary / f"as3vm_convert_abi_{platform}.{suffix}"
probe.write_text(probe_text, encoding="utf-8")
syntax = subprocess.run([
compiler, "-target", target, "-ffreestanding",
"-fsyntax-only", f"-std={standard}",
"-Wall", "-Wextra", "-Werror", *extra,
f"-DIGGY_RECONSTRUCT_AS3VM_CONVERT_{platform.upper()}=1",
"-I", str(RECONSTRUCTED), str(probe),
], capture_output=True, text=True)
self.assertEqual(syntax.returncode, 0,
(platform, language, syntax.stderr))
if __name__ == "__main__":
unittest.main()