From b5775fdb3badba84c145ce7d0b8580fef8e455bb Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Sun, 19 Jul 2026 01:37:59 -0500 Subject: [PATCH] rebuild iggy's native david gay dtoa float conversion --- .../src/reconstructed/CMakeLists.txt | 24 + iggy-decompiled/src/reconstructed/README.md | 21 + iggy-decompiled/src/reconstructed/dtoa.c | 217 +++++ iggy-decompiled/src/reconstructed/dtoa.h | 45 + .../src/reconstructed/dtoa_bigcomp.inc | 320 +++++++ .../src/reconstructed/dtoa_bigint.inc | 725 +++++++++++++++ .../src/reconstructed/dtoa_dtoa.inc | 731 +++++++++++++++ .../src/reconstructed/dtoa_parse.inc | 210 +++++ .../src/reconstructed/dtoa_strtod.inc | 874 ++++++++++++++++++ .../src/reconstructed/dtoa_tables.inc | 34 + iggy-decompiled/src/reconstructed/modules.tsv | 4 + tests/support/dtoa_test_support.c | 101 ++ tests/test_reconstructed_dtoa.py | 245 +++++ tests/test_reconstructed_dtoa_cross.py | 404 ++++++++ 14 files changed, 3955 insertions(+) create mode 100644 iggy-decompiled/src/reconstructed/dtoa.c create mode 100644 iggy-decompiled/src/reconstructed/dtoa.h create mode 100644 iggy-decompiled/src/reconstructed/dtoa_bigcomp.inc create mode 100644 iggy-decompiled/src/reconstructed/dtoa_bigint.inc create mode 100644 iggy-decompiled/src/reconstructed/dtoa_dtoa.inc create mode 100644 iggy-decompiled/src/reconstructed/dtoa_parse.inc create mode 100644 iggy-decompiled/src/reconstructed/dtoa_strtod.inc create mode 100644 iggy-decompiled/src/reconstructed/dtoa_tables.inc create mode 100644 tests/support/dtoa_test_support.c create mode 100644 tests/test_reconstructed_dtoa.py create mode 100644 tests/test_reconstructed_dtoa_cross.py diff --git a/iggy-decompiled/src/reconstructed/CMakeLists.txt b/iggy-decompiled/src/reconstructed/CMakeLists.txt index c5f23dd..dd5cab9 100644 --- a/iggy-decompiled/src/reconstructed/CMakeLists.txt +++ b/iggy-decompiled/src/reconstructed/CMakeLists.txt @@ -802,3 +802,27 @@ foreach(platform IN ITEMS durango orbis ps3 vita) target_compile_options(${target} PRIVATE /Oi-) endif() endforeach() + +# dtoa -- Iggy's port of David M. Gay's correctly-rounded float <-> decimal +# string conversion (netlib dtoa.c / strtod; 4-platform, 3 exports). Owns no +# exported data global (the tens / bigtens / tinytens tables are file-static). +# Imports per-platform libc: durango / ps3 lower free + memcpy + memset; orbis / +# vita additionally pull the CRT rounding-mode query _Fltrounds under +# Honor_FLT_ROUNDS; vita additionally pulls the armv7 soft 32-bit unsigned +# divide (__udivsi3) for the Bigint quotient. Guard against libcall +# re-synthesis with -fno-builtin (clang/gcc) or /Oi- (MSVC). +foreach(platform IN ITEMS durango orbis ps3 vita) + string(TOUPPER ${platform} platform_upper) + set(target iggy_reconstructed_dtoa_${platform}) + add_library(${target} STATIC dtoa.c) + target_compile_definitions( + ${target} + PRIVATE IGGY_RECONSTRUCT_DTOA_${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() diff --git a/iggy-decompiled/src/reconstructed/README.md b/iggy-decompiled/src/reconstructed/README.md index 65197e1..89beeb2 100644 --- a/iggy-decompiled/src/reconstructed/README.md +++ b/iggy-decompiled/src/reconstructed/README.md @@ -734,6 +734,27 @@ little-endian so it is correct on big-endian PS3, and the decoder struct copy is open-coded on durango/vita where retail unrolls it and lowered to `memcpy` on orbis/ps3 to match each object. Only the STBM allocator is imported. +`dtoa.c` restores Iggy's copy of David Gay's arbitrary-precision floating-point +conversion behind its three exports: `rr_strtod` (decimal string to correctly +rounded double), `rr_dtoa` (double to shortest or fixed decimal digits with the +decimal-point, sign, and end-pointer out-params), and `iggy_freedtoa` (a no-op, +since the result lives in a static cache). The full algorithm is reconstructed — +the Bigint core (Balloc/Bfree over the freelist and private arena, multadd, +mult, pow5mult, lshift, compare, difference, and the correct-rounding quorem long +division), the strtod fast and bignum-correction paths, and the dtoa mode +dispatch with its leftright digit generation. The three constant tables +(`tens`, `bigtens`, `tinytens`, including the scaled `2^106·1e-256` fifth +tiny-power entry) are byte-exact against the retail objects; the Bigint limb +layout is 32-bit-gated for ps3/vita and the double word-extraction macros select +big-endian order on PS3. The build matches each platform's actual configuration: +the hex-float parse path is compiled out everywhere (no platform's object carries +it), hex-NaN parsing is kept, and the `hexdig` lookup is a static constant on +orbis but a runtime-initialised table on durango, ps3, and vita — with durango's +initializer kept out of line as its object has it. The rounding-mode query +(`_Fltrounds` on orbis and vita) and the ARM Bigint divide helper (`__udivsi3` on +vita) are reproduced at their exact sites; only the C runtime's free, memcpy, and +memset are otherwise 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. diff --git a/iggy-decompiled/src/reconstructed/dtoa.c b/iggy-decompiled/src/reconstructed/dtoa.c new file mode 100644 index 0000000..0dbba58 --- /dev/null +++ b/iggy-decompiled/src/reconstructed/dtoa.c @@ -0,0 +1,217 @@ +/* + * dtoa.c -- Iggy's port of David M. Gay's correctly-rounded float <-> decimal + * string conversion (the classic public-domain netlib dtoa.c / strtod). + * + * Provenance (canonical, embedded on the orbis retail object): + * c:\projects\g\src\flash\dtoa.c + * (durango embeds the build-temp .obj path; ps3 / vita a bare "dtoa.c".) + * + * It exports EXACTLY THREE entry points on all four platforms: + * rr_strtod -- decimal / hex-float string -> correctly-rounded double. + * rr_dtoa -- double -> shortest (mode 0) / fixed decimal digit string. + * iggy_freedtoa-- retail NO-OP ({ return; }); the dtoa result lives in the + * module-static dtoa_result cache, so nothing is freed. + * + * OWNED DATA = three file-static (nm lowercase 'r') David-Gay constant tables: + * tens[23] = { 1e0 .. 1e22 } + * bigtens[5] = { 1e16, 1e32, 1e64, 1e128, 1e256 } + * tinytens[5] = { 1e-16, 1e-32, 1e-64, 1e-128, + * 9007199254740992.*9007199254740992.e-256 } (= 2^106 * 1e-256, + * bit pattern 0x1168062864ac6f43 -- the scaled fifth entry that + * dodges spurious underflow). See dtoa_tables.inc. + * They are `static const double`, so no data symbol is exported (durango MSVC's + * per-constant __real@ rodata COMDATs are a compiler artifact); the ps3 + * big-endian (IEEE_MC68k) byte order is emitted automatically per target. + * + * The Bigint arbitrary-precision core (Balloc/Bfree over a freelist + a private + * arena, multadd / mult / pow5mult / lshift / diff / quorem long division / + * d2b / b2d), the strtod fast + bignum correct-rounding loops (incl. bigcomp), + * and the dtoa digit generation (Steele & White leftright rounding) are all + * reconstructed faithfully, not stubbed. + * + * 32/64-bit Bigint layout: ULong is a 32-bit limb on every platform (durango / + * orbis 64-bit LE, ps3 32-bit BE, vita 32-bit LE); 64-bit intermediates use + * ULLong. On vita (armv7, no hardware divide) the quotient estimate pulls the + * soft 32-bit unsigned-division helper (__udivsi3); on orbis / vita the + * Honor_FLT_ROUNDS path queries the CRT rounding mode (_Fltrounds). + */ + +/* --- per-platform gate: byte order + FLT_ROUNDS honoring, from the module + * macro the build passes (IGGY_RECONSTRUCT_DTOA_). --- */ +#if defined(IGGY_RECONSTRUCT_DTOA_DURANGO) +/* x86_64 LE (IEEE_8087); MSVC __ImageBase / _fltused are toolchain artifacts. */ +#elif defined(IGGY_RECONSTRUCT_DTOA_ORBIS) +/* x86_64 LE (IEEE_8087); Honor_FLT_ROUNDS -> _Fltrounds. Alone among the four, + * orbis emits hexdig[] as a static const (read-only) table, no runtime init. */ +#define IGGY_DTOA_HONOR_ROUNDS 1 +#define IGGY_DTOA_STATIC_HEXDIG 1 +#elif defined(IGGY_RECONSTRUCT_DTOA_PS3) +/* PPC 32-bit BIG-endian (IEEE_MC68k): word0 is the high double word. */ +#define IGGY_DTOA_BIG_ENDIAN 1 +#elif defined(IGGY_RECONSTRUCT_DTOA_VITA) +/* armv7 32-bit LE (IEEE_8087); Honor_FLT_ROUNDS -> _Fltrounds; soft divide. */ +#define IGGY_DTOA_HONOR_ROUNDS 1 +#else +#error "define one of IGGY_RECONSTRUCT_DTOA_{DURANGO,ORBIS,PS3,VITA}" +#endif + +#include +#include +#include /* freestanding-provided: DBL_DIG / DBL_MAX_10_EXP / ... */ + +#include "dtoa.h" + +/* libc lowerings the reconstruction relies on (declared here, freestanding). */ +void *memcpy(void *dest, const void *src, size_t n); +void *memset(void *s, int c, size_t n); +void free(void *p); +#ifdef IGGY_DTOA_HONOR_ROUNDS +/* CRT rounding-mode query used under Honor_FLT_ROUNDS (orbis / vita). */ +extern int _Fltrounds(void); +#endif + +/* Canonical build-time source path, kept as a C literal so the escaped + * provenance survives in the translation-unit text (and, via `used`, in the + * emitted rodata -- mirroring the retail objects' embedded path string). */ +static const char dtoa_source_file[] __attribute__((used)) = + "c:\\projects\\g\\src\\flash\\dtoa.c"; + +#ifndef Long +#define Long int +#endif +#ifndef ULong +typedef unsigned Long ULong; +#endif +#define assert(x) /*nothing*/ +#define Debug(x) /*nothing*/ + +static void *iggy_dtoa_nomalloc(size_t n) { (void)n; return 0; } +#define MALLOC(n) iggy_dtoa_nomalloc(n) +#define FREE free +#define NO_ERRNO +#define Set_errno(x) /*nothing*/ + +#ifndef PRIVATE_MEM +#define PRIVATE_MEM 2304 +#endif +#define PRIVATE_mem ((PRIVATE_MEM + sizeof(double) - 1) / sizeof(double)) +static double private_mem[PRIVATE_mem], *pmem_next = private_mem; + +#define IEEE_Arith +#define INFNAN_CHECK +#define Avoid_Underflow +#define ULLong unsigned long long + +typedef union { double d; ULong L[2]; } U; + +#if defined(IGGY_DTOA_BIG_ENDIAN) +#define word0(x) (x)->L[0] +#define word1(x) (x)->L[1] +#else +#define word0(x) (x)->L[1] +#define word1(x) (x)->L[0] +#endif +#define dval(x) (x)->d + +#define STRTOD_DIGLIM 40 +#define strtod_diglim STRTOD_DIGLIM +#define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \ + ((unsigned short *)a)[0] = (unsigned short)c, a++) + +#define Exp_shift 20 +#define Exp_shift1 20 +#define Exp_msk1 0x100000 +#define Exp_msk11 0x100000 +#define Exp_mask 0x7ff00000 +#define P 53 +#define Nbits 53 +#define Bias 1023 +#define Emax 1023 +#define Emin (-1022) +#define Exp_1 0x3ff00000 +#define Exp_11 0x3ff00000 +#define Ebits 11 +#define Frac_mask 0xfffff +#define Frac_mask1 0xfffff +#define Ten_pmax 22 +#define Bletch 0x10 +#define Bndry_mask 0xfffff +#define Bndry_mask1 0xfffff +#define LSB 1 +#define Sign_bit 0x80000000 +#define Log2P 1 +#define Tiny0 0 +#define Tiny1 1 +#define Quick_max 14 +#define Int_max 14 + +#ifdef IGGY_DTOA_HONOR_ROUNDS +#define Honor_FLT_ROUNDS +#define Trust_FLT_ROUNDS +#define Flt_Rounds _Fltrounds() +#else +#define Flt_Rounds 1 +#endif +#ifdef Honor_FLT_ROUNDS +#undef Check_FLT_ROUNDS +#define Check_FLT_ROUNDS +#else +#define Rounding Flt_Rounds +#endif + +#define rounded_product(a,b) a *= b +#define rounded_quotient(a,b) a /= b +#define Big0 (Frac_mask1 | Exp_msk1 * (DBL_MAX_EXP + Bias - 1)) +#define Big1 0xffffffff +#define Pack_32 + +typedef struct BCinfo BCinfo; +struct BCinfo { + int dp0, dp1, dplen, dsign, e0, inexact, nd, nd0, rounding, scale, uflchk; + }; + +#define FFFFFFFF 0xffffffffUL +#define MTa /*nothing*/ +#define MTb /*nothing*/ +#define MTd /*nothing*/ +#define Kmax 7 + +#if defined(IGGY_RECONSTRUCT_DTOA_VITA) +/* armv7 has no hardware integer divide: the Bigint quotient pulls the soft + 32-bit unsigned-division helper (retail vita imports __udivsi3). */ +extern unsigned int __udivsi3(unsigned int, unsigned int); +#define IGGY_UDIV(a, b) __udivsi3((unsigned int)(a), (unsigned int)(b)) +#else +#define IGGY_UDIV(a, b) ((a) / (b)) +#endif + + +struct Bigint { + struct Bigint *next; + int k, maxwds, sign, wds; + ULong x[1]; + }; +typedef struct Bigint Bigint; +typedef struct ThInfo { Bigint *Freelist[Kmax+1]; Bigint *P5s; } ThInfo; +static ThInfo TI0; +#define freelist TI0.Freelist +#define p5s TI0.P5s + +/* ---- the David-Gay core, split by concern (each < ~900 lines) ---- */ +#include "dtoa_bigint.inc" /* Balloc/Bfree/multadd/mult/pow5mult/lshift/d2b/b2d */ +#include "dtoa_tables.inc" /* tens / bigtens / tinytens (owned static data) */ +#include "dtoa_parse.inc" /* hexdig / match / hexnan / increment (NO_HEX_FP) */ +#include "dtoa_bigcomp.inc" /* dshift / quorem / sulp / bigcomp */ +#include "dtoa_strtod.inc" /* strtod (fast path + bignum correct rounding) */ +#include "dtoa_dtoa.inc" /* rv_alloc / nrv_alloc / dtoa_r / dtoa */ + +/* ---- exported ABI: three entry points, thin wrappers over the static core. */ +double rr_strtod(char *s, char **se) { return strtod((const char *)s, se); } + +char *rr_dtoa(double d, unsigned mode, int ndigits, + int *decpt, int *sign, char **rve) { + return dtoa(d, (int)mode, ndigits, decpt, sign, rve); + } + +/* Retail no-op: the digit string lives in the static dtoa_result cache. */ +void iggy_freedtoa(char *s) { (void)s; } diff --git a/iggy-decompiled/src/reconstructed/dtoa.h b/iggy-decompiled/src/reconstructed/dtoa.h new file mode 100644 index 0000000..3be4f1f --- /dev/null +++ b/iggy-decompiled/src/reconstructed/dtoa.h @@ -0,0 +1,45 @@ +/* + * dtoa.h -- public ABI for Iggy's float <-> decimal string conversion. + * + * dtoa is Iggy's port of David M. Gay's arbitrary-precision, correctly-rounded + * floating <-> string conversion (the classic public-domain netlib dtoa.c). It + * exports EXACTLY THREE entry points on all four platforms (durango / orbis / + * ps3 / vita). Provenance: c:\projects\g\src\flash\dtoa.c. + * + * The header is deliberately platform-agnostic and both C11 and C++17 + * includable (extern "C" so the exported ABI keeps C linkage under C++). The + * arbitrary-precision Bigint machinery and the three David-Gay constant tables + * (tens / bigtens / tinytens) are file-static in the translation unit. + */ +#ifndef IGGY_RECONSTRUCTED_DTOA_H +#define IGGY_RECONSTRUCTED_DTOA_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* David Gay strtod: parse the decimal (or C99 hex-float / Infinity / NaN) + * string s to the correctly-rounded nearest double, and -- through *se -- + * report the first unconsumed character so the caller can measure how far the + * scan ran. Overflow saturates to +/-Inf, underflow to +/-0. */ +double rr_strtod(char *s, char **se); + +/* David Gay dtoa: convert d to its shortest (mode 0) or fixed decimal digit + * string, writing the decimal-point position through *decpt, the sign through + * *sign, and (through *rve) a pointer to the terminating NUL of the returned + * digit string. The result points into the module-static dtoa_result cache + * (NOT a fresh allocation), which is why iggy_freedtoa is a no-op. */ +char *rr_dtoa(double d, unsigned mode, int ndigits, int *decpt, int *sign, + char **rve); + +/* Retail NO-OP ({ return; } on all four platforms): the dtoa result lives in + * the static dtoa_result buffer, so there is nothing to release. */ +void iggy_freedtoa(char *s); + +#ifdef __cplusplus +} +#endif + +#endif /* IGGY_RECONSTRUCTED_DTOA_H */ diff --git a/iggy-decompiled/src/reconstructed/dtoa_bigcomp.inc b/iggy-decompiled/src/reconstructed/dtoa_bigcomp.inc new file mode 100644 index 0000000..307c314 --- /dev/null +++ b/iggy-decompiled/src/reconstructed/dtoa_bigcomp.inc @@ -0,0 +1,320 @@ +/* + * dtoa_bigcomp.inc -- dshift / quorem long division / sulp / bigcomp comparison. + * + * Part of dtoa.c (Iggy's David-Gay float<->string port); #included there, not + * compiled standalone -- it relies on the config macros in dtoa.c. + */ + + static int +dshift(Bigint *b, int p2) +{ + int rv = hi0bits(b->x[b->wds-1]) - 4; + if (p2 > 0) + rv -= p2; + return rv & kmask; + } + + static int +quorem(Bigint *b, Bigint *S) +{ + int n; + ULong *bx, *bxe, q, *sx, *sxe; +#ifdef ULLong + ULLong borrow, carry, y, ys; +#else + ULong borrow, carry, y, ys; +#ifdef Pack_32 + ULong si, z, zs; +#endif +#endif + + n = S->wds; + if (b->wds < n) + return 0; + sx = S->x; + sxe = sx + --n; + bx = b->x; + bxe = bx + n; + q = IGGY_UDIV(*bxe, *sxe + 1); /* ensure q <= true quotient */ + if (q) { + borrow = 0; + carry = 0; + do { +#ifdef ULLong + ys = *sx++ * (ULLong)q + carry; + carry = ys >> 32; + y = *bx - (ys & FFFFFFFF) - borrow; + borrow = y >> 32 & (ULong)1; + *bx++ = y & FFFFFFFF; +#else +#ifdef Pack_32 + si = *sx++; + ys = (si & 0xffff) * q + carry; + zs = (si >> 16) * q + (ys >> 16); + carry = zs >> 16; + y = (*bx & 0xffff) - (ys & 0xffff) - borrow; + borrow = (y & 0x10000) >> 16; + z = (*bx >> 16) - (zs & 0xffff) - borrow; + borrow = (z & 0x10000) >> 16; + Storeinc(bx, z, y); +#else + ys = *sx++ * q + carry; + carry = ys >> 16; + y = *bx - (ys & 0xffff) - borrow; + borrow = (y & 0x10000) >> 16; + *bx++ = y & 0xffff; +#endif +#endif + } + while(sx <= sxe); + if (!*bxe) { + bx = b->x; + while(--bxe > bx && !*bxe) + --n; + b->wds = n; + } + } + if (cmp(b, S) >= 0) { + q++; + borrow = 0; + carry = 0; + bx = b->x; + sx = S->x; + do { +#ifdef ULLong + ys = *sx++ + carry; + carry = ys >> 32; + y = *bx - (ys & FFFFFFFF) - borrow; + borrow = y >> 32 & (ULong)1; + *bx++ = y & FFFFFFFF; +#else +#ifdef Pack_32 + si = *sx++; + ys = (si & 0xffff) + carry; + zs = (si >> 16) + (ys >> 16); + carry = zs >> 16; + y = (*bx & 0xffff) - (ys & 0xffff) - borrow; + borrow = (y & 0x10000) >> 16; + z = (*bx >> 16) - (zs & 0xffff) - borrow; + borrow = (z & 0x10000) >> 16; + Storeinc(bx, z, y); +#else + ys = *sx++ + carry; + carry = ys >> 16; + y = *bx - (ys & 0xffff) - borrow; + borrow = (y & 0x10000) >> 16; + *bx++ = y & 0xffff; +#endif +#endif + } + while(sx <= sxe); + bx = b->x; + bxe = bx + n; + if (!*bxe) { + while(--bxe > bx && !*bxe) + --n; + b->wds = n; + } + } + return q; + } + + static double +sulp(U *x, BCinfo *bc) +{ + U u; + double rv; + int i; + + rv = ulp(x); + if (!bc->scale || (i = 2*P + 1 - ((word0(x) & Exp_mask) >> Exp_shift)) <= 0) + return rv; /* Is there an example where i <= 0 ? */ + word0(&u) = Exp_1 + (i << Exp_shift); + word1(&u) = 0; + return rv * u.d; + } + + static void +bigcomp(U *rv, const char *s0, BCinfo *bc MTd) +{ + Bigint *b, *d; + int b2, bbits, d2, dd, dig, dsign, i, j, nd, nd0, p2, p5, speccase; + + dsign = bc->dsign; + nd = bc->nd; + nd0 = bc->nd0; + p5 = nd + bc->e0 - 1; + speccase = 0; + if (rv->d == 0.) { /* special case: value near underflow-to-zero */ + /* threshold was rounded to zero */ + b = i2b(1 MTa); + p2 = Emin - P + 1; + bbits = 1; +#ifdef Avoid_Underflow + word0(rv) = (P+2) << Exp_shift; +#else + word1(rv) = 1; +#endif + i = 0; +#ifdef Honor_FLT_ROUNDS + if (bc->rounding == 1) +#endif + { + speccase = 1; + --p2; + dsign = 0; + goto have_i; + } + } + else + b = d2b(rv, &p2, &bbits MTa); +#ifdef Avoid_Underflow + p2 -= bc->scale; +#endif + /* floor(log2(rv)) == bbits - 1 + p2 */ + /* Check for denormal case. */ + i = P - bbits; + if (i > (j = P - Emin - 1 + p2)) { + i = j; + } +#ifdef Honor_FLT_ROUNDS + if (bc->rounding != 1) { + if (i > 0) + b = lshift(b, i MTa); + if (dsign) + b = increment(b MTa); + } + else +#endif + { + b = lshift(b, ++i MTa); + b->x[0] |= 1; + } + have_i: + p2 -= p5 + i; + d = i2b(1 MTa); + /* Arrange for convenient computation of quotients: + * shift left if necessary so divisor has 4 leading 0 bits. + */ + if (p5 > 0) + d = pow5mult(d, p5 MTa); + else if (p5 < 0) + b = pow5mult(b, -p5 MTa); + if (p2 > 0) { + b2 = p2; + d2 = 0; + } + else { + b2 = 0; + d2 = -p2; + } + i = dshift(d, d2); + if ((b2 += i) > 0) + b = lshift(b, b2 MTa); + if ((d2 += i) > 0) + d = lshift(d, d2 MTa); + + /* Now b/d = exactly half-way between the two floating-point values */ + /* on either side of the input string. Compute first digit of b/d. */ + + if (!(dig = quorem(b,d))) { + b = multadd(b, 10, 0 MTa); /* very unlikely */ + dig = quorem(b,d); + } + + /* Compare b/d with s0 */ + + for(i = 0; i < nd0; ) { + if ((dd = s0[i++] - '0' - dig)) + goto ret; + if (!b->x[0] && b->wds == 1) { + if (i < nd) + dd = 1; + goto ret; + } + b = multadd(b, 10, 0 MTa); + dig = quorem(b,d); + } + for(j = bc->dp1; i++ < nd;) { + if ((dd = s0[j++] - '0' - dig)) + goto ret; + if (!b->x[0] && b->wds == 1) { + if (i < nd) + dd = 1; + goto ret; + } + b = multadd(b, 10, 0 MTa); + dig = quorem(b,d); + } + if (dig > 0 || b->x[0] || b->wds > 1) + dd = -1; + ret: + Bfree(b MTa); + Bfree(d MTa); +#ifdef Honor_FLT_ROUNDS + if (bc->rounding != 1) { + if (dd < 0) { + if (bc->rounding == 0) { + if (!dsign) + goto retlow1; + } + else if (dsign) + goto rethi1; + } + else if (dd > 0) { + if (bc->rounding == 0) { + if (dsign) + goto rethi1; + goto ret1; + } + if (!dsign) + goto rethi1; + dval(rv) += 2.*sulp(rv,bc); + } + else { + bc->inexact = 0; + if (dsign) + goto rethi1; + } + } + else +#endif + if (speccase) { + if (dd <= 0) + rv->d = 0.; + } + else if (dd < 0) { + if (!dsign) /* does not happen for round-near */ +retlow1: + dval(rv) -= sulp(rv,bc); + } + else if (dd > 0) { + if (dsign) { + rethi1: + dval(rv) += sulp(rv,bc); + } + } + else { + /* Exact half-way case: apply round-even rule. */ + if ((j = ((word0(rv) & Exp_mask) >> Exp_shift) - bc->scale) <= 0) { + i = 1 - j; + if (i <= 31) { + if (word1(rv) & (0x1 << i)) + goto odd; + } + else if (word0(rv) & (0x1 << (i-32))) + goto odd; + } + else if (word1(rv) & 1) { + odd: + if (dsign) + goto rethi1; + goto retlow1; + } + } + +#ifdef Honor_FLT_ROUNDS + ret1: +#endif + return; + } diff --git a/iggy-decompiled/src/reconstructed/dtoa_bigint.inc b/iggy-decompiled/src/reconstructed/dtoa_bigint.inc new file mode 100644 index 0000000..c474d05 --- /dev/null +++ b/iggy-decompiled/src/reconstructed/dtoa_bigint.inc @@ -0,0 +1,725 @@ +/* + * dtoa_bigint.inc -- Bigint arbitrary-precision core (freelist + private arena). + * + * Part of dtoa.c (Iggy's David-Gay float<->string port); #included there, not + * compiled standalone -- it relies on the config macros in dtoa.c. + */ + + static Bigint * +Balloc(int k MTd) +{ + int x; + Bigint *rv; + unsigned int len; + /* The k > Kmax case does not need ACQUIRE_DTOA_LOCK(0), */ + /* but this case seems very unlikely. */ + if (k <= Kmax && (rv = freelist[k])) + freelist[k] = rv->next; + else { + x = 1 << k; + len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1) + /sizeof(double); + if (k <= Kmax && pmem_next - private_mem + (Long)len <= (Long)PRIVATE_mem + ) { + rv = (Bigint*)pmem_next; + pmem_next += len; + } + else + rv = (Bigint*)MALLOC(len*sizeof(double)); + rv->k = k; + rv->maxwds = x; + } + rv->sign = rv->wds = 0; + return rv; + } + + static void +Bfree(Bigint *v MTd) +{ + if (v) { + if (v->k > Kmax) + FREE((void*)v); + else { + v->next = freelist[v->k]; + freelist[v->k] = v; + } + } + } + +#define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \ +y->wds*sizeof(Long) + 2*sizeof(int)) + + static Bigint * +multadd(Bigint *b, int m, int a MTd) /* multiply by m and add a */ +{ + int i, wds; +#ifdef ULLong + ULong *x; + ULLong carry, y; +#else + ULong carry, *x, y; +#ifdef Pack_32 + ULong xi, z; +#endif +#endif + Bigint *b1; + + wds = b->wds; + x = b->x; + i = 0; + carry = a; + do { +#ifdef ULLong + y = *x * (ULLong)m + carry; + carry = y >> 32; + *x++ = y & FFFFFFFF; +#else +#ifdef Pack_32 + xi = *x; + y = (xi & 0xffff) * m + carry; + z = (xi >> 16) * m + (y >> 16); + carry = z >> 16; + *x++ = (z << 16) + (y & 0xffff); +#else + y = *x * m + carry; + carry = y >> 16; + *x++ = y & 0xffff; +#endif +#endif + } + while(++i < wds); + if (carry) { + if (wds >= b->maxwds) { + b1 = Balloc(b->k+1 MTa); + Bcopy(b1, b); + Bfree(b MTa); + b = b1; + } + b->x[wds++] = carry; + b->wds = wds; + } + return b; + } + + static Bigint * +s2b(const char *s, int nd0, int nd, ULong y9, int dplen MTd) +{ + Bigint *b; + int i, k; + Long x, y; + + x = (nd + 8) / 9; + for(k = 0, y = 1; x > y; y <<= 1, k++) ; +#ifdef Pack_32 + b = Balloc(k MTa); + b->x[0] = y9; + b->wds = 1; +#else + b = Balloc(k+1 MTa); + b->x[0] = y9 & 0xffff; + b->wds = (b->x[1] = y9 >> 16) ? 2 : 1; +#endif + + i = 9; + if (9 < nd0) { + s += 9; + do b = multadd(b, 10, *s++ - '0' MTa); + while(++i < nd0); + s += dplen; + } + else + s += dplen + 9; + for(; i < nd; i++) + b = multadd(b, 10, *s++ - '0' MTa); + return b; + } + + static int +hi0bits(ULong x) +{ + int k = 0; + + if (!(x & 0xffff0000)) { + k = 16; + x <<= 16; + } + if (!(x & 0xff000000)) { + k += 8; + x <<= 8; + } + if (!(x & 0xf0000000)) { + k += 4; + x <<= 4; + } + if (!(x & 0xc0000000)) { + k += 2; + x <<= 2; + } + if (!(x & 0x80000000)) { + k++; + if (!(x & 0x40000000)) + return 32; + } + return k; + } + + static int +lo0bits(ULong *y) +{ + int k; + ULong x = *y; + + if (x & 7) { + if (x & 1) + return 0; + if (x & 2) { + *y = x >> 1; + return 1; + } + *y = x >> 2; + return 2; + } + k = 0; + if (!(x & 0xffff)) { + k = 16; + x >>= 16; + } + if (!(x & 0xff)) { + k += 8; + x >>= 8; + } + if (!(x & 0xf)) { + k += 4; + x >>= 4; + } + if (!(x & 0x3)) { + k += 2; + x >>= 2; + } + if (!(x & 1)) { + k++; + x >>= 1; + if (!x) + return 32; + } + *y = x; + return k; + } + + static Bigint * +i2b(int i MTd) +{ + Bigint *b; + + b = Balloc(1 MTa); + b->x[0] = i; + b->wds = 1; + return b; + } + + static Bigint * +mult(Bigint *a, Bigint *b MTd) +{ + Bigint *c; + int k, wa, wb, wc; + ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0; + ULong y; +#ifdef ULLong + ULLong carry, z; +#else + ULong carry, z; +#ifdef Pack_32 + ULong z2; +#endif +#endif + + if (a->wds < b->wds) { + c = a; + a = b; + b = c; + } + k = a->k; + wa = a->wds; + wb = b->wds; + wc = wa + wb; + if (wc > a->maxwds) + k++; + c = Balloc(k MTa); + memset(c->x, 0, wc * sizeof(ULong)); + xa = a->x; + xae = xa + wa; + xb = b->x; + xbe = xb + wb; + xc0 = c->x; +#ifdef ULLong + for(; xb < xbe; xc0++) { + if ((y = *xb++)) { + x = xa; + xc = xc0; + carry = 0; + do { + z = *x++ * (ULLong)y + *xc + carry; + carry = z >> 32; + *xc++ = z & FFFFFFFF; + } + while(x < xae); + *xc = carry; + } + } +#else +#ifdef Pack_32 + for(; xb < xbe; xb++, xc0++) { + if ((y = *xb & 0xffff)) { + x = xa; + xc = xc0; + carry = 0; + do { + z = (*x & 0xffff) * y + (*xc & 0xffff) + carry; + carry = z >> 16; + z2 = (*x++ >> 16) * y + (*xc >> 16) + carry; + carry = z2 >> 16; + Storeinc(xc, z2, z); + } + while(x < xae); + *xc = carry; + } + if ((y = *xb >> 16)) { + x = xa; + xc = xc0; + carry = 0; + z2 = *xc; + do { + z = (*x & 0xffff) * y + (*xc >> 16) + carry; + carry = z >> 16; + Storeinc(xc, z, z2); + z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry; + carry = z2 >> 16; + } + while(x < xae); + *xc = z2; + } + } +#else + for(; xb < xbe; xc0++) { + if (y = *xb++) { + x = xa; + xc = xc0; + carry = 0; + do { + z = *x++ * y + *xc + carry; + carry = z >> 16; + *xc++ = z & 0xffff; + } + while(x < xae); + *xc = carry; + } + } +#endif +#endif + for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ; + c->wds = wc; + return c; + } + + static Bigint * +pow5mult(Bigint *b, int k MTd) +{ + Bigint *b1, *p5, *p51; + int i; + static int p05[3] = { 5, 25, 125 }; + + if ((i = k & 3)) + b = multadd(b, p05[i-1], 0 MTa); + + if (!(k >>= 2)) + return b; + if (!(p5 = p5s)) { + /* first time */ + p5 = p5s = i2b(625 MTa); + p5->next = 0; + } + for(;;) { + if (k & 1) { + b1 = mult(b, p5 MTa); + Bfree(b MTa); + b = b1; + } + if (!(k >>= 1)) + break; + if (!(p51 = p5->next)) { + p51 = p5->next = mult(p5,p5); + p51->next = 0; + } + p5 = p51; + } + return b; + } + + static Bigint * +lshift(Bigint *b, int k MTd) +{ + int i, k1, n, n1; + Bigint *b1; + ULong *x, *x1, *xe, z; + +#ifdef Pack_32 + n = k >> 5; +#else + n = k >> 4; +#endif + k1 = b->k; + n1 = n + b->wds + 1; + for(i = b->maxwds; n1 > i; i <<= 1) + k1++; + b1 = Balloc(k1 MTa); + x1 = b1->x; + for(i = 0; i < n; i++) + *x1++ = 0; + x = b->x; + xe = x + b->wds; +#ifdef Pack_32 + if (k &= 0x1f) { + k1 = 32 - k; + z = 0; + do { + *x1++ = *x << k | z; + z = *x++ >> k1; + } + while(x < xe); + if ((*x1 = z)) + ++n1; + } +#else + if (k &= 0xf) { + k1 = 16 - k; + z = 0; + do { + *x1++ = *x << k & 0xffff | z; + z = *x++ >> k1; + } + while(x < xe); + if (*x1 = z) + ++n1; + } +#endif + else do + *x1++ = *x++; + while(x < xe); + b1->wds = n1 - 1; + Bfree(b MTa); + return b1; + } + + static int +cmp(Bigint *a, Bigint *b) +{ + ULong *xa, *xa0, *xb, *xb0; + int i, j; + + i = a->wds; + j = b->wds; + if (i -= j) + return i; + xa0 = a->x; + xa = xa0 + j; + xb0 = b->x; + xb = xb0 + j; + for(;;) { + if (*--xa != *--xb) + return *xa < *xb ? -1 : 1; + if (xa <= xa0) + break; + } + return 0; + } + + static Bigint * +diff(Bigint *a, Bigint *b MTd) +{ + Bigint *c; + int i, wa, wb; + ULong *xa, *xae, *xb, *xbe, *xc; +#ifdef ULLong + ULLong borrow, y; +#else + ULong borrow, y; +#ifdef Pack_32 + ULong z; +#endif +#endif + + i = cmp(a,b); + if (!i) { + c = Balloc(0 MTa); + c->wds = 1; + c->x[0] = 0; + return c; + } + if (i < 0) { + c = a; + a = b; + b = c; + i = 1; + } + else + i = 0; + c = Balloc(a->k MTa); + c->sign = i; + wa = a->wds; + xa = a->x; + xae = xa + wa; + wb = b->wds; + xb = b->x; + xbe = xb + wb; + xc = c->x; + borrow = 0; +#ifdef ULLong + do { + y = (ULLong)*xa++ - *xb++ - borrow; + borrow = y >> 32 & (ULong)1; + *xc++ = y & FFFFFFFF; + } + while(xb < xbe); + while(xa < xae) { + y = *xa++ - borrow; + borrow = y >> 32 & (ULong)1; + *xc++ = y & FFFFFFFF; + } +#else +#ifdef Pack_32 + do { + y = (*xa & 0xffff) - (*xb & 0xffff) - borrow; + borrow = (y & 0x10000) >> 16; + z = (*xa++ >> 16) - (*xb++ >> 16) - borrow; + borrow = (z & 0x10000) >> 16; + Storeinc(xc, z, y); + } + while(xb < xbe); + while(xa < xae) { + y = (*xa & 0xffff) - borrow; + borrow = (y & 0x10000) >> 16; + z = (*xa++ >> 16) - borrow; + borrow = (z & 0x10000) >> 16; + Storeinc(xc, z, y); + } +#else + do { + y = *xa++ - *xb++ - borrow; + borrow = (y & 0x10000) >> 16; + *xc++ = y & 0xffff; + } + while(xb < xbe); + while(xa < xae) { + y = *xa++ - borrow; + borrow = (y & 0x10000) >> 16; + *xc++ = y & 0xffff; + } +#endif +#endif + while(!*--xc) + wa--; + c->wds = wa; + return c; + } + + static double +ulp(U *x) +{ + Long L; + U u; + + L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1; +#ifndef Avoid_Underflow + if (L > 0) { +#endif + word0(&u) = L; + word1(&u) = 0; +#ifndef Avoid_Underflow + } + else { + L = -L >> Exp_shift; + if (L < Exp_shift) { + word0(&u) = 0x80000 >> L; + word1(&u) = 0; + } + else { + word0(&u) = 0; + L -= Exp_shift; + word1(&u) = L >= 31 ? 1 : 1 << 31 - L; + } + } +#endif + return dval(&u); + } + + static double +b2d(Bigint *a, int *e) +{ + ULong *xa, *xa0, w, y, z; + int k; + U d; +#define d0 word0(&d) +#define d1 word1(&d) + + xa0 = a->x; + xa = xa0 + a->wds; + y = *--xa; + k = hi0bits(y); + *e = 32 - k; +#ifdef Pack_32 + if (k < Ebits) { + d0 = Exp_1 | y >> (Ebits - k); + w = xa > xa0 ? *--xa : 0; + d1 = y << ((32-Ebits) + k) | w >> (Ebits - k); + goto ret_d; + } + z = xa > xa0 ? *--xa : 0; + if (k -= Ebits) { + d0 = Exp_1 | y << k | z >> (32 - k); + y = xa > xa0 ? *--xa : 0; + d1 = z << k | y >> (32 - k); + } + else { + d0 = Exp_1 | y; + d1 = z; + } +#else + if (k < Ebits + 16) { + z = xa > xa0 ? *--xa : 0; + d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k; + w = xa > xa0 ? *--xa : 0; + y = xa > xa0 ? *--xa : 0; + d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k; + goto ret_d; + } + z = xa > xa0 ? *--xa : 0; + w = xa > xa0 ? *--xa : 0; + k -= Ebits + 16; + d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k; + y = xa > xa0 ? *--xa : 0; + d1 = w << k + 16 | y << k; +#endif + ret_d: +#undef d0 +#undef d1 + return dval(&d); + } + + static Bigint * +d2b(U *d, int *e, int *bits MTd) +{ + Bigint *b; + int de, k; + ULong *x, y, z; + int i; +#define d0 word0(d) +#define d1 word1(d) + +#ifdef Pack_32 + b = Balloc(1 MTa); +#else + b = Balloc(2 MTa); +#endif + x = b->x; + + z = d0 & Frac_mask; + d0 &= 0x7fffffff; /* clear sign bit, which we ignore */ + if ((de = (int)(d0 >> Exp_shift))) + z |= Exp_msk1; +#ifdef Pack_32 + if ((y = d1)) { + if ((k = lo0bits(&y))) { + x[0] = y | z << (32 - k); + z >>= k; + } + else + x[0] = y; + i = + b->wds = (x[1] = z) ? 2 : 1; + } + else { + k = lo0bits(&z); + x[0] = z; + i = + b->wds = 1; + k += 32; + } +#else + if (y = d1) { + if (k = lo0bits(&y)) + if (k >= 16) { + x[0] = y | z << 32 - k & 0xffff; + x[1] = z >> k - 16 & 0xffff; + x[2] = z >> k; + i = 2; + } + else { + x[0] = y & 0xffff; + x[1] = y >> 16 | z << 16 - k & 0xffff; + x[2] = z >> k & 0xffff; + x[3] = z >> k+16; + i = 3; + } + else { + x[0] = y & 0xffff; + x[1] = y >> 16; + x[2] = z & 0xffff; + x[3] = z >> 16; + i = 3; + } + } + else { + k = lo0bits(&z); + if (k >= 16) { + x[0] = z; + i = 0; + } + else { + x[0] = z & 0xffff; + x[1] = z >> 16; + i = 1; + } + k += 32; + } + while(!x[i]) + --i; + b->wds = i + 1; +#endif + if (de) { + *e = de - Bias - (P-1) + k; + *bits = P - k; + } + else { + *e = de - Bias - (P-1) + 1 + k; +#ifdef Pack_32 + *bits = 32*i - hi0bits(x[i-1]); +#else + *bits = (i+2)*16 - hi0bits(x[i]); +#endif + } + return b; + } +#undef d0 +#undef d1 + + static double +ratio(Bigint *a, Bigint *b) +{ + U da, db; + int k, ka, kb; + + dval(&da) = b2d(a, &ka); + dval(&db) = b2d(b, &kb); +#ifdef Pack_32 + k = ka - kb + 32*(a->wds - b->wds); +#else + k = ka - kb + 16*(a->wds - b->wds); +#endif + if (k > 0) + word0(&da) += k*Exp_msk1; + else { + k = -k; + word0(&db) += k*Exp_msk1; + } + return dval(&da) / dval(&db); + } diff --git a/iggy-decompiled/src/reconstructed/dtoa_dtoa.inc b/iggy-decompiled/src/reconstructed/dtoa_dtoa.inc new file mode 100644 index 0000000..2f03a7f --- /dev/null +++ b/iggy-decompiled/src/reconstructed/dtoa_dtoa.inc @@ -0,0 +1,731 @@ +/* + * dtoa_dtoa.inc -- rr_dtoa core: rv_alloc / nrv_alloc / dtoa_r digit generation. + * + * Part of dtoa.c (Iggy's David-Gay float<->string port); #included there, not + * compiled standalone -- it relies on the config macros in dtoa.c. + */ + + static char * +rv_alloc(int i MTd) +{ + int j, k, *r; + + j = sizeof(ULong); + for(k = 0; + sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= (size_t)i; + j <<= 1) + k++; + r = (int*)Balloc(k MTa); + *r = k; + return + dtoa_result = + (char *)(r+1); + } + + static char * +nrv_alloc(const char *s, char *s0, size_t s0len, char **rve, int n MTd) +{ + char *rv, *t; + + if (!s0) + s0 = rv_alloc(n MTa); + else if (s0len <= (size_t)n) { + rv = 0; + t = rv + n; + goto rve_chk; + } + t = rv = s0; + while((*t = *s++)) + ++t; + rve_chk: + if (rve) + *rve = t; + return rv; + } + + + +/* dtoa for IEEE arithmetic (dmg): convert double to ASCII string. + * + * Inspired by "How to Print Floating-Point Numbers Accurately" by + * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126]. + * + * Modifications: + * 1. Rather than iterating, we use a simple numeric overestimate + * to determine k = floor(log10(d)). We scale relevant + * quantities using O(log2(k)) rather than O(k) multiplications. + * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't + * try to generate digits strictly left to right. Instead, we + * compute with fewer bits and propagate the carry if necessary + * when rounding the final digit up. This is often faster. + * 3. Under the assumption that input will be rounded nearest, + * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22. + * That is, we allow equality in stopping tests when the + * round-nearest rule will give the same floating-point value + * as would satisfaction of the stopping test with strict + * inequality. + * 4. We remove common factors of powers of 2 from relevant + * quantities. + * 5. When converting floating-point integers less than 1e16, + * we use floating-point arithmetic rather than resorting + * to multiple-precision integers. + * 6. When asked to produce fewer than 15 digits, we first try + * to get by with floating-point arithmetic; we resort to + * multiple-precision integer arithmetic only if we cannot + * guarantee that the floating-point calculation has given + * the correctly rounded result. For k requested digits and + * "uniformly" distributed input, the probability is + * something like 10^(k-15) that we must resort to the Long + * calculation. + */ + +static char * +dtoa_r(double dd, int mode, int ndigits, int *decpt, int *sign, char **rve, char *buf, size_t blen) +{ + /* Arguments ndigits, decpt, sign are similar to those + of ecvt and fcvt; trailing zeros are suppressed from + the returned string. If not null, *rve is set to point + to the end of the return value. If d is +-Infinity or NaN, + then *decpt is set to 9999. + + mode: + 0 ==> shortest string that yields d when read in + and rounded to nearest. + 1 ==> like 0, but with Steele & White stopping rule; + e.g. with IEEE P754 arithmetic , mode 0 gives + 1e23 whereas mode 1 gives 9.999999999999999e22. + 2 ==> max(1,ndigits) significant digits. This gives a + return value similar to that of ecvt, except + that trailing zeros are suppressed. + 3 ==> through ndigits past the decimal point. This + gives a return value similar to that from fcvt, + except that trailing zeros are suppressed, and + ndigits can be negative. + 4,5 ==> similar to 2 and 3, respectively, but (in + round-nearest mode) with the tests of mode 0 to + possibly return a shorter string that rounds to d. + With IEEE arithmetic and compilation with + -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same + as modes 2 and 3 when FLT_ROUNDS != 1. + 6-9 ==> Debugging modes similar to mode - 4: don't try + fast floating-point estimate (if applicable). + + Values of mode other than 0-9 are treated as mode 0. + + When not NULL, buf is an output buffer of length blen, which must + be large enough to accommodate suppressed trailing zeros and a trailing + null byte. If blen is too small, rv = NULL is returned, in which case + if rve is not NULL, a subsequent call with blen >= (*rve - rv) + 1 + should succeed in returning buf. + + When buf is NULL, sufficient space is allocated for the return value, + which, when done using, the caller should pass to freedtoa(). + + USE_BF is automatically defined when neither NO_LONG_LONG nor NO_BF96 + is defined. + */ + + int bbits, b2, b5, be, dig, i, ilim, ilim1, + j, j1, k, leftright, m2, m5, s2, s5, spec_case; + int denorm; + Bigint *b, *b1, *delta, *mlo, *mhi, *S; + U u; + char *s; + ULong x; + Long L; + U d2, eps; + double ds; + int ieps, ilim0, k0, k_check, try_quick; +#ifdef IEEE_Arith + U eps1; +#endif +#ifdef Honor_FLT_ROUNDS /*{*/ + int Rounding; +#ifdef Trust_FLT_ROUNDS /*{{ only define this if FLT_ROUNDS really works! */ + Rounding = Flt_Rounds; +#else /*}{*/ + Rounding = 1; + switch(fegetround()) { + case FE_TOWARDZERO: Rounding = 0; break; + case FE_UPWARD: Rounding = 2; break; + case FE_DOWNWARD: Rounding = 3; + } +#endif /*}}*/ +#endif /*}*/ + + u.d = dd; + if (word0(&u) & Sign_bit) { + /* set sign for everything, including 0's and NaNs */ + *sign = 1; + word0(&u) &= ~Sign_bit; /* clear sign bit */ + } + else + *sign = 0; + +#if defined(IEEE_Arith) + defined(VAX) +#ifdef IEEE_Arith + if ((word0(&u) & Exp_mask) == Exp_mask) +#else + if (word0(&u) == 0x8000) +#endif + { + /* Infinity or NaN */ + *decpt = 9999; +#ifdef IEEE_Arith + if (!word1(&u) && !(word0(&u) & 0xfffff)) + return nrv_alloc("Infinity", buf, blen, rve, 8 MTb); +#endif + return nrv_alloc("NaN", buf, blen, rve, 3 MTb); + } +#endif + if (!dval(&u)) { + *decpt = 1; + return nrv_alloc("0", buf, blen, rve, 1 MTb); + } + +#ifdef Honor_FLT_ROUNDS + if (Rounding >= 2) { + if (*sign) + Rounding = Rounding == 2 ? 0 : 2; + else + if (Rounding != 2) + Rounding = 0; + } +#endif + + b = d2b(&u, &be, &bbits MTb); + if ((i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1)))) { + dval(&d2) = dval(&u); + word0(&d2) &= Frac_mask1; + word0(&d2) |= Exp_11; + + /* log(x) ~=~ log(1.5) + (x-1.5)/1.5 + * log10(x) = log(x) / log(10) + * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10)) + * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2) + * + * This suggests computing an approximation k to log10(d) by + * + * k = (i - Bias)*0.301029995663981 + * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 ); + * + * We want k to be too large rather than too small. + * The error in the first-order Taylor series approximation + * is in our favor, so we just round up the constant enough + * to compensate for any error in the multiplication of + * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077, + * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14, + * adding 1e-13 to the constant term more than suffices. + * Hence we adjust the constant term to 0.1760912590558. + * (We could get a more accurate k by invoking log10, + * but this is probably not worthwhile.) + */ + + i -= Bias; + denorm = 0; + } + else { + /* d is denormalized */ + + i = bbits + be + (Bias + (P-1) - 1); + x = i > 32 ? word0(&u) << (64 - i) | word1(&u) >> (i - 32) + : word1(&u) << (32 - i); + dval(&d2) = x; + word0(&d2) -= 31*Exp_msk1; /* adjust exponent */ + i -= (Bias + (P-1) - 1) + 1; + denorm = 1; + } + ds = (dval(&d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981; + k = (int)ds; + if (ds < 0. && ds != k) + k--; /* want k = floor(ds) */ + k_check = 1; + if (k >= 0 && k <= Ten_pmax) { + if (dval(&u) < tens[k]) + k--; + k_check = 0; + } + j = bbits - i - 1; + if (j >= 0) { + b2 = 0; + s2 = j; + } + else { + b2 = -j; + s2 = 0; + } + if (k >= 0) { + b5 = 0; + s5 = k; + s2 += k; + } + else { + b2 -= k; + b5 = -k; + s5 = 0; + } + if (mode < 0 || mode > 9) + mode = 0; + +#ifdef Check_FLT_ROUNDS + try_quick = Rounding == 1; +#else + try_quick = 1; +#endif + + if (mode > 5) { + mode -= 4; + try_quick = 0; + } + leftright = 1; + ilim = ilim1 = -1; /* Values for cases 0 and 1; done here to */ + /* silence erroneous "gcc -Wall" warning. */ + switch(mode) { + case 0: + case 1: + i = 18; + ndigits = 0; + break; + case 2: + leftright = 0; + /* no break */ + case 4: + if (ndigits <= 0) + ndigits = 1; + ilim = ilim1 = i = ndigits; + break; + case 3: + leftright = 0; + /* no break */ + case 5: + i = ndigits + k + 1; + ilim = i; + ilim1 = i - 1; + if (i <= 0) + i = 1; + } + if (!buf) { + buf = rv_alloc(i MTb); + blen = sizeof(Bigint) + ((1 << ((int*)buf)[-1]) - 1)*sizeof(ULong) - sizeof(int); + } + else if (blen <= (size_t)i) { + buf = 0; + if (rve) + *rve = buf + i; + return buf; + } + s = buf; + + /* Check for special case that d is a normalized power of 2. */ + + spec_case = 0; + if (mode < 2 || (leftright +#ifdef Honor_FLT_ROUNDS + && Rounding == 1 +#endif + )) { + if (!word1(&u) && !(word0(&u) & Bndry_mask) + && word0(&u) & (Exp_mask & ~Exp_msk1) + ) { + /* The special case */ + spec_case = 1; + } + } + + +#ifdef Honor_FLT_ROUNDS + if (mode > 1 && Rounding != 1) + leftright = 0; +#endif + + if (ilim >= 0 && ilim <= Quick_max && try_quick) { + + /* Try to get by with floating-point arithmetic. */ + + i = 0; + dval(&d2) = dval(&u); + j1 = -(k0 = k); + ilim0 = ilim; + ieps = 2; /* conservative */ + if (k > 0) { + ds = tens[k&0xf]; + j = k >> 4; + if (j & Bletch) { + /* prevent overflows */ + j &= Bletch - 1; + dval(&u) /= bigtens[n_bigtens-1]; + ieps++; + } + for(; j; j >>= 1, i++) + if (j & 1) { + ieps++; + ds *= bigtens[i]; + } + dval(&u) /= ds; + } + else if (j1 > 0) { + dval(&u) *= tens[j1 & 0xf]; + for(j = j1 >> 4; j; j >>= 1, i++) + if (j & 1) { + ieps++; + dval(&u) *= bigtens[i]; + } + } + if (k_check && dval(&u) < 1. && ilim > 0) { + if (ilim1 <= 0) + goto fast_failed; + ilim = ilim1; + k--; + dval(&u) *= 10.; + ieps++; + } + dval(&eps) = ieps*dval(&u) + 7.; + word0(&eps) -= (P-1)*Exp_msk1; + if (ilim == 0) { + S = mhi = 0; + dval(&u) -= 5.; + if (dval(&u) > dval(&eps)) + goto one_digit; + if (dval(&u) < -dval(&eps)) + goto no_digits; + goto fast_failed; + } + if (leftright) { + /* Use Steele & White method of only + * generating digits needed. + */ + dval(&eps) = 0.5/tens[ilim-1] - dval(&eps); +#ifdef IEEE_Arith + if (j1 >= 307) { + eps1.d = 1.01e256; /* 1.01 allows roundoff in the next few lines */ + word0(&eps1) -= Exp_msk1 * (Bias+P-1); + dval(&eps1) *= tens[j1 & 0xf]; + for(i = 0, j = (j1-256) >> 4; j; j >>= 1, i++) + if (j & 1) + dval(&eps1) *= bigtens[i]; + if (eps.d < eps1.d) + eps.d = eps1.d; + if (10. - u.d < 10.*eps.d && eps.d < 1.) { + /* eps.d < 1. excludes trouble with the tiniest denormal */ + *s++ = '1'; + ++k; + goto ret1; + } + } +#endif + for(i = 0;;) { + L = dval(&u); + dval(&u) -= L; + *s++ = '0' + (int)L; + if (1. - dval(&u) < dval(&eps)) + goto bump_up; + if (dval(&u) < dval(&eps)) + goto retc; + if (++i >= ilim) + break; + dval(&eps) *= 10.; + dval(&u) *= 10.; + } + } + else { + /* Generate ilim digits, then fix them up. */ + dval(&eps) *= tens[ilim-1]; + for(i = 1;; i++, dval(&u) *= 10.) { + L = (Long)(dval(&u)); + if (!(dval(&u) -= L)) + ilim = i; + *s++ = '0' + (int)L; + if (i == ilim) { + if (dval(&u) > 0.5 + dval(&eps)) + goto bump_up; + else if (dval(&u) < 0.5 - dval(&eps)) + goto retc; + break; + } + } + } + fast_failed: + s = buf; + dval(&u) = dval(&d2); + k = k0; + ilim = ilim0; + } + + /* Do we have a "small" integer? */ + + if (be >= 0 && k <= Int_max) { + /* Yes. */ + ds = tens[k]; + if (ndigits < 0 && ilim <= 0) { + S = mhi = 0; + if (ilim < 0 || dval(&u) <= 5*ds) + goto no_digits; + goto one_digit; + } + for(i = 1;; i++, dval(&u) *= 10.) { + L = (Long)(dval(&u) / ds); + dval(&u) -= L*ds; +#ifdef Check_FLT_ROUNDS + /* If FLT_ROUNDS == 2, L will usually be high by 1 */ + if (dval(&u) < 0) { + L--; + dval(&u) += ds; + } +#endif + *s++ = '0' + (int)L; + if (!dval(&u)) { + break; + } + if (i == ilim) { +#ifdef Honor_FLT_ROUNDS + if (mode > 1) + switch(Rounding) { + case 0: goto retc; + case 2: goto bump_up; + } +#endif + dval(&u) += dval(&u); + if (dval(&u) > ds || (dval(&u) == ds && L & 1)) + { + bump_up: + while(*--s == '9') + if (s == buf) { + k++; + *s = '0'; + break; + } + ++*s++; + } + break; + } + } + goto retc; + } + + m2 = b2; + m5 = b5; + mhi = mlo = 0; + if (leftright) { + i = + denorm ? be + (Bias + (P-1) - 1 + 1) : + 1 + P - bbits; + b2 += i; + s2 += i; + mhi = i2b(1 MTb); + } + if (m2 > 0 && s2 > 0) { + i = m2 < s2 ? m2 : s2; + b2 -= i; + m2 -= i; + s2 -= i; + } + if (b5 > 0) { + if (leftright) { + if (m5 > 0) { + mhi = pow5mult(mhi, m5 MTb); + b1 = mult(mhi, b MTb); + Bfree(b MTb); + b = b1; + } + if ((j = b5 - m5)) + b = pow5mult(b, j MTb); + } + else + b = pow5mult(b, b5 MTb); + } + S = i2b(1 MTb); + if (s5 > 0) + S = pow5mult(S, s5 MTb); + + if (spec_case) { + b2 += Log2P; + s2 += Log2P; + } + + /* Arrange for convenient computation of quotients: + * shift left if necessary so divisor has 4 leading 0 bits. + * + * Perhaps we should just compute leading 28 bits of S once + * and for all and pass them and a shift to quorem, so it + * can do shifts and ors to compute the numerator for q. + */ + i = dshift(S, s2); + b2 += i; + m2 += i; + s2 += i; + if (b2 > 0) + b = lshift(b, b2 MTb); + if (s2 > 0) + S = lshift(S, s2 MTb); + if (k_check) { + if (cmp(b,S) < 0) { + k--; + b = multadd(b, 10, 0 MTb); /* we botched the k estimate */ + if (leftright) + mhi = multadd(mhi, 10, 0 MTb); + ilim = ilim1; + } + } + if (ilim <= 0 && (mode == 3 || mode == 5)) { + if (ilim < 0 || cmp(b,S = multadd(S,5,0 MTb)) <= 0) { + /* no digits, fcvt style */ + no_digits: + k = -1 - ndigits; + goto ret; + } + one_digit: + *s++ = '1'; + ++k; + goto ret; + } + if (leftright) { + if (m2 > 0) + mhi = lshift(mhi, m2 MTb); + + /* Compute mlo -- check for special case + * that d is a normalized power of 2. + */ + + mlo = mhi; + if (spec_case) { + mhi = Balloc(mhi->k MTb); + Bcopy(mhi, mlo); + mhi = lshift(mhi, Log2P MTb); + } + + for(i = 1;;i++) { + dig = quorem(b,S) + '0'; + /* Do we yet have the shortest decimal string + * that will round to d? + */ + j = cmp(b, mlo); + delta = diff(S, mhi MTb); + j1 = delta->sign ? 1 : cmp(b, delta); + Bfree(delta MTb); + if (j1 == 0 && mode != 1 && !(word1(&u) & 1) +#ifdef Honor_FLT_ROUNDS + && (mode <= 1 || Rounding >= 1) +#endif + ) { + if (dig == '9') + goto round_9_up; + if (j > 0) + dig++; + *s++ = dig; + goto ret; + } + if (j < 0 || (j == 0 && mode != 1 + && !(word1(&u) & 1) + )) { + if (!b->x[0] && b->wds <= 1) { + goto accept_dig; + } +#ifdef Honor_FLT_ROUNDS + if (mode > 1) + switch(Rounding) { + case 0: goto accept_dig; + case 2: goto keep_dig; + } +#endif /*Honor_FLT_ROUNDS*/ + if (j1 > 0) { + b = lshift(b, 1 MTb); + j1 = cmp(b, S); + if ((j1 > 0 || (j1 == 0 && dig & 1)) + && dig++ == '9') + goto round_9_up; + } + accept_dig: + *s++ = dig; + goto ret; + } + if (j1 > 0) { +#ifdef Honor_FLT_ROUNDS + if (!Rounding && mode > 1) + goto accept_dig; +#endif + if (dig == '9') { /* possible if i == 1 */ + round_9_up: + *s++ = '9'; + goto roundoff; + } + *s++ = dig + 1; + goto ret; + } +#ifdef Honor_FLT_ROUNDS + keep_dig: +#endif + *s++ = dig; + if (i == ilim) + break; + b = multadd(b, 10, 0 MTb); + if (mlo == mhi) + mlo = mhi = multadd(mhi, 10, 0 MTb); + else { + mlo = multadd(mlo, 10, 0 MTb); + mhi = multadd(mhi, 10, 0 MTb); + } + } + } + else + for(i = 1;; i++) { + dig = quorem(b,S) + '0'; + *s++ = dig; + if (!b->x[0] && b->wds <= 1) { + goto ret; + } + if (i >= ilim) + break; + b = multadd(b, 10, 0 MTb); + } + + /* Round off last digit */ + +#ifdef Honor_FLT_ROUNDS + if (mode > 1) + switch(Rounding) { + case 0: goto ret; + case 2: goto roundoff; + } +#endif + b = lshift(b, 1 MTb); + j = cmp(b, S); + if (j > 0 || (j == 0 && dig & 1)) + { + roundoff: + while(*--s == '9') + if (s == buf) { + k++; + *s++ = '1'; + goto ret; + } + ++*s++; + } + ret: + Bfree(S MTb); + if (mhi) { + if (mlo && mlo != mhi) + Bfree(mlo MTb); + Bfree(mhi MTb); + } + retc: + while(s > buf && s[-1] == '0') + --s; + ret1: + if (b) + Bfree(b MTb); + *s = 0; + *decpt = k + 1; + if (rve) + *rve = s; + return buf; + } + +static char * +dtoa(double dd, int mode, int ndigits, int *decpt, int *sign, char **rve) +{ + /* Sufficient space is allocated to the return value + to hold the suppressed trailing zeros. + See dtoa_r() above for details on the other arguments. + */ + return dtoa_r(dd, mode, ndigits, decpt, sign, rve, 0, 0); + } diff --git a/iggy-decompiled/src/reconstructed/dtoa_parse.inc b/iggy-decompiled/src/reconstructed/dtoa_parse.inc new file mode 100644 index 0000000..6b7d4bf --- /dev/null +++ b/iggy-decompiled/src/reconstructed/dtoa_parse.inc @@ -0,0 +1,210 @@ +/* + * dtoa_parse.inc -- hex-digit table + Infinity/NaN parsing helpers. + * + * Retail compiled with NO_HEX_FP on all four platforms, so there is NO hex- + * FLOAT (0x1.8p3) path here -- no gethex, no 'p'/'P' binary-exponent parse. + * The hexdig[] table survives solely for hexnan ("nan(0x...)"). + * + * Part of dtoa.c (Iggy's David-Gay float<->string port); #included there, not + * compiled standalone -- it relies on the config macros in dtoa.c. + */ + +/* hexdig[] is needed only for hexnan ("nan(0x...)"): retail compiled with + * NO_HEX_FP on all four platforms (verified: no gethex / no 0x...p... binary- + * exponent parse in any raw), so the hex-FLOAT path is gone and hexnan is the + * sole consumer of the table. Its vintage differs per platform, gated below: + * orbis -- static const hexdig[256], read-only, no runtime init (raw:1539). + * durango/ps3/vita -- writable hexdig[256] zeroed then filled lazily by + * hexdig_init (guard `if (!hexdig['0'])` inside hexnan); + * durango emits hexdig_init OUT-OF-LINE (raw:731), ps3 / + * vita inline it (raw ps3:2175, vita:1911). */ +#undef Need_Hexdig +#ifdef INFNAN_CHECK +#ifndef No_Hex_NaN +#define Need_Hexdig +#endif +#endif + +#ifdef Need_Hexdig /*{*/ +#ifdef IGGY_DTOA_STATIC_HEXDIG /*{ orbis: read-only prefilled table */ +static const unsigned char hexdig[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 16,17,18,19,20,21,22,23,24,25,0,0,0,0,0,0, + 0,26,27,28,29,30,31,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,26,27,28,29,30,31,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 + }; +#else /*}{ durango / ps3 / vita: writable table, filled lazily via hexdig_init */ +static unsigned char hexdig[256]; + + static void +htinit(unsigned char *h, unsigned char *s, int inc) +{ + int i, j; + for(i = 0; (j = s[i]) !=0; i++) + h[j] = i + inc; + } + +#ifdef IGGY_RECONSTRUCT_DTOA_DURANGO +__attribute__((noinline)) /* durango emits hexdig_init out-of-line (raw:731) */ +#endif + static void +hexdig_init(void) +{ +#define USC (unsigned char *) + htinit(hexdig, USC "0123456789", 0x10); + htinit(hexdig, USC "abcdef", 0x10 + 10); + htinit(hexdig, USC "ABCDEF", 0x10 + 10); + } +#endif /*}*/ +#endif /* } Need_Hexdig */ + +#ifdef INFNAN_CHECK + +#ifndef NAN_WORD0 +#define NAN_WORD0 0x7ff80000 +#endif + +#ifndef NAN_WORD1 +#define NAN_WORD1 0 +#endif + + static int +match(const char **sp, const char *t) +{ + int c, d; + const char *s = *sp; + + while((d = *t++)) { + if ((c = *++s) >= 'A' && c <= 'Z') + c += 'a' - 'A'; + if (c != d) + return 0; + } + *sp = s + 1; + return 1; + } + +#ifndef No_Hex_NaN + static void +hexnan(U *rvp, const char **sp) +{ + ULong c, x[2]; + const char *s; + int c1, havedig, udx0, xshift; + +#ifndef IGGY_DTOA_STATIC_HEXDIG + /* durango / ps3 / vita: lazily fill the zeroed hexdig[] on first use + * (durango raw:785, ps3 raw:2175, vita raw:1911). */ + if (!hexdig['0']) + hexdig_init(); +#endif + x[0] = x[1] = 0; + havedig = xshift = 0; + udx0 = 1; + s = *sp; + /* allow optional initial 0x or 0X */ + while((c = *(const unsigned char*)(s+1)) && c <= ' ') + ++s; + if (s[1] == '0' && (s[2] == 'x' || s[2] == 'X')) + s += 2; + while((c = *(const unsigned char*)++s)) { + if ((c1 = hexdig[c])) + c = c1 & 0xf; + else if (c <= ' ') { + if (udx0 && havedig) { + udx0 = 0; + xshift = 1; + } + continue; + } +#ifdef GDTOA_NON_PEDANTIC_NANCHECK + else if (/*(*/ c == ')' && havedig) { + *sp = s + 1; + break; + } + else + return; /* invalid form: don't change *sp */ +#else + else { + do { + if (/*(*/ c == ')') { + *sp = s + 1; + break; + } + } while((c = *++s)); + break; + } +#endif + havedig = 1; + if (xshift) { + xshift = 0; + x[0] = x[1]; + x[1] = 0; + } + if (udx0) + x[0] = (x[0] << 4) | (x[1] >> 28); + x[1] = (x[1] << 4) | c; + } + if ((x[0] &= 0xfffff) || x[1]) { + word0(rvp) = Exp_mask | x[0]; + word1(rvp) = x[1]; + } + } +#endif /*No_Hex_NaN*/ +#endif /* INFNAN_CHECK */ + +#ifdef Pack_32 +#define ULbits 32 +#define kshift 5 +#define kmask 31 +#else +#define ULbits 16 +#define kshift 4 +#define kmask 15 +#endif + +/* increment is a bignum helper used ONLY by bigcomp's Honor_FLT_ROUNDS + * directed-rounding branch (dtoa_bigcomp.inc), so it exists exactly on the + * platforms that honor FLT_ROUNDS (orbis / vita). rshift / any_on were used + * only by the now-removed hex-FLOAT gethex path and are absent from every + * retail raw, so they are gone with it. */ +#ifdef Honor_FLT_ROUNDS + static Bigint * +increment(Bigint *b MTd) +{ + ULong *x, *xe; + Bigint *b1; + + x = b->x; + xe = x + b->wds; + do { + if (*x < (ULong)0xffffffffL) { + ++*x; + return b; + } + *x++ = 0; + } while(x < xe); + { + if (b->wds >= b->maxwds) { + b1 = Balloc(b->k+1 MTa); + Bcopy(b1,b); + Bfree(b MTa); + b = b1; + } + b->x[b->wds++] = 1; + } + return b; + } +#endif /* Honor_FLT_ROUNDS */ diff --git a/iggy-decompiled/src/reconstructed/dtoa_strtod.inc b/iggy-decompiled/src/reconstructed/dtoa_strtod.inc new file mode 100644 index 0000000..19fe610 --- /dev/null +++ b/iggy-decompiled/src/reconstructed/dtoa_strtod.inc @@ -0,0 +1,874 @@ +/* + * dtoa_strtod.inc -- rr_strtod core: fast path + bignum correct-rounding loop. + * + * Part of dtoa.c (Iggy's David-Gay float<->string port); #included there, not + * compiled standalone -- it relies on the config macros in dtoa.c. + */ + +static double +strtod(const char *s00, char **se) +{ + int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, e, e1; + int esign, i, j, k, nd, nd0, nf, nz, nz0, nz1, sign; + const char *s, *s0, *s1; + double aadj, aadj1; + Long L; + U aadj2, adj, rv, rv0; + ULong y, z; + BCinfo bc; + Bigint *bb, *bb1, *bd, *bd0, *bs, *delta; +#ifdef Avoid_Underflow + ULong Lsb, Lsb1; +#endif + int req_bigcomp = 0; +#ifdef Honor_FLT_ROUNDS /*{*/ +#ifdef Trust_FLT_ROUNDS /*{{ only define this if FLT_ROUNDS really works! */ + bc.rounding = Flt_Rounds; +#else /*}{*/ + bc.rounding = 1; + switch(fegetround()) { + case FE_TOWARDZERO: bc.rounding = 0; break; + case FE_UPWARD: bc.rounding = 2; break; + case FE_DOWNWARD: bc.rounding = 3; + } +#endif /*}}*/ +#endif /*}*/ + + sign = nz0 = nz1 = nz = bc.dplen = bc.uflchk = 0; + dval(&rv) = 0.; + for(s = s00;;s++) switch(*s) { + case '-': + sign = 1; + /* no break */ + case '+': + if (*++s) + goto break2; + /* no break */ + case 0: + goto ret0; + case '\t': + case '\n': + case '\v': + case '\f': + case '\r': + case ' ': + continue; + default: + goto break2; + } + break2: + if (*s == '0') { + /* Retail compiled with NO_HEX_FP on all four platforms: the leading + * '0' just skips further zeros (no s[1]=='x' hex-float branch), then + * falls through to the digit / '.' parse. For "0x1p4" retail returns + * 0.0 with *se left at the 'x'. (durango raw:2067, orbis raw:126, + * ps3 raw:1985, vita raw:1044/1052 -- all identical, no x-test.) */ + nz0 = 1; + while(*++s == '0') ; + if (!*s) + goto ret; + } + s0 = s; + nd = nf = 0; + y = z = 0; + for(; (c = *s) >= '0' && c <= '9'; nd++, s++) + if (nd < 9) + y = 10*y + c - '0'; + else if (nd < DBL_DIG + 2) + z = 10*z + c - '0'; + nd0 = nd; + bc.dp0 = bc.dp1 = s - s0; + for(s1 = s; s1 > s0 && *--s1 == '0'; ) + ++nz1; + if (c == '.') { + c = *++s; + bc.dp1 = s - s0; + bc.dplen = bc.dp1 - bc.dp0; + if (!nd) { + for(; c == '0'; c = *++s) + nz++; + if (c > '0' && c <= '9') { + bc.dp0 = s0 - s; + bc.dp1 = bc.dp0 + bc.dplen; + s0 = s; + nf += nz; + nz = 0; + goto have_dig; + } + goto dig_done; + } + for(; c >= '0' && c <= '9'; c = *++s) { + have_dig: + nz++; + if (c -= '0') { + nf += nz; + i = 1; + for(; i < nz; ++i) { + if (nd++ < 9) + y *= 10; + else if (nd <= DBL_DIG + 2) + z *= 10; + } + if (nd++ < 9) + y = 10*y + c; + else if (nd <= DBL_DIG + 2) + z = 10*z + c; + nz = nz1 = 0; + } + } + } + dig_done: + e = 0; + if (c == 'e' || c == 'E') { + if (!nd && !nz && !nz0) { + goto ret0; + } + s00 = s; + esign = 0; + switch(c = *++s) { + case '-': + esign = 1; + case '+': + c = *++s; + } + if (c >= '0' && c <= '9') { + while(c == '0') + c = *++s; + if (c > '0' && c <= '9') { + L = c - '0'; + while((c = *++s) >= '0' && c <= '9') { + if (L <= 19999) + L = 10*L + c - '0'; + } + if (L > 19999) + /* Avoid confusion from exponents + * so large that e might overflow. + */ + e = 19999; /* safe for 16 bit ints */ + else + e = (int)L; + if (esign) + e = -e; + } + else + e = 0; + } + else + s = s00; + } + if (!nd) { + if (!nz && !nz0) { +#ifdef INFNAN_CHECK /*{*/ + /* Check for Nan and Infinity */ + if (!bc.dplen) + switch(c) { + case 'i': + case 'I': + if (match(&s,"nf")) { + --s; + if (!match(&s,"inity")) + ++s; + word0(&rv) = 0x7ff00000; + word1(&rv) = 0; + goto ret; + } + break; + case 'n': + case 'N': + if (match(&s, "an")) { + word0(&rv) = NAN_WORD0; + word1(&rv) = NAN_WORD1; +#ifndef No_Hex_NaN + if (*s == '(') /*)*/ + hexnan(&rv, &s); +#endif + goto ret; + } + } +#endif /*} INFNAN_CHECK */ + ret0: + s = s00; + sign = 0; + } + goto ret; + } + bc.e0 = e1 = e -= nf; + + /* Now we have nd0 digits, starting at s0, followed by a + * decimal point, followed by nd-nd0 digits. The number we're + * after is the integer represented by those digits times + * 10**e */ + + if (!nd0) + nd0 = nd; + k = nd < DBL_DIG + 2 ? nd : DBL_DIG + 2; + dval(&rv) = y; + if (k > 9) { + dval(&rv) = tens[k - 9] * dval(&rv) + z; + } + bd0 = 0; + if (nd <= DBL_DIG +#ifndef Honor_FLT_ROUNDS + && Flt_Rounds == 1 +#endif + ) { + if (!e) + goto ret; + if (e > 0) { + if (e <= Ten_pmax) { +#ifdef Honor_FLT_ROUNDS + /* round correctly FLT_ROUNDS = 2 or 3 */ + if (sign) { + rv.d = -rv.d; + sign = 0; + } +#endif + /* rv = */ rounded_product(dval(&rv), tens[e]); + goto ret; + } + i = DBL_DIG - nd; + if (e <= Ten_pmax + i) { + /* A fancier test would sometimes let us do + * this for larger i values. + */ +#ifdef Honor_FLT_ROUNDS + /* round correctly FLT_ROUNDS = 2 or 3 */ + if (sign) { + rv.d = -rv.d; + sign = 0; + } +#endif + e -= i; + dval(&rv) *= tens[i]; + /* rv = */ rounded_product(dval(&rv), tens[e]); + goto ret; + } + } + else if (e >= -Ten_pmax) { +#ifdef Honor_FLT_ROUNDS + /* round correctly FLT_ROUNDS = 2 or 3 */ + if (sign) { + rv.d = -rv.d; + sign = 0; + } +#endif + /* rv = */ rounded_quotient(dval(&rv), tens[-e]); + goto ret; + } + } + e1 += nd - k; /* scale factor = 10^e1 */ + +#ifdef IEEE_Arith +#ifdef Honor_FLT_ROUNDS + if (bc.rounding >= 2) { + if (sign) + bc.rounding = bc.rounding == 2 ? 0 : 2; + else + if (bc.rounding != 2) + bc.rounding = 0; + } +#endif +#endif /*IEEE_Arith*/ + + +#ifdef IEEE_Arith +#ifdef Avoid_Underflow + bc.scale = 0; +#endif +#endif /*IEEE_Arith*/ + + /* Get starting approximation = rv * 10**e1 */ + + if (e1 > 0) { + if ((i = e1 & 15)) + dval(&rv) *= tens[i]; + if (e1 &= ~15) { + if (e1 > DBL_MAX_10_EXP) { + ovfl: + /* Can't trust HUGE_VAL */ +#ifdef IEEE_Arith +#ifdef Honor_FLT_ROUNDS + switch(bc.rounding) { + case 0: /* toward 0 */ + case 3: /* toward -infinity */ + word0(&rv) = Big0; + word1(&rv) = Big1; + break; + default: + word0(&rv) = Exp_mask; + word1(&rv) = 0; + } +#else /*Honor_FLT_ROUNDS*/ + word0(&rv) = Exp_mask; + word1(&rv) = 0; +#endif /*Honor_FLT_ROUNDS*/ +#else /*IEEE_Arith*/ + word0(&rv) = Big0; + word1(&rv) = Big1; +#endif /*IEEE_Arith*/ + range_err: + if (bd0) { + Bfree(bb MTb); + Bfree(bd MTb); + Bfree(bs MTb); + Bfree(bd0 MTb); + Bfree(delta MTb); + } + Set_errno(ERANGE); + goto ret; + } + e1 >>= 4; + for(j = 0; e1 > 1; j++, e1 >>= 1) + if (e1 & 1) + dval(&rv) *= bigtens[j]; + /* The last multiplication could overflow. */ + word0(&rv) -= P*Exp_msk1; + dval(&rv) *= bigtens[j]; + if ((z = word0(&rv) & Exp_mask) + > Exp_msk1*(DBL_MAX_EXP+Bias-P)) + goto ovfl; + if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) { + /* set to largest number */ + /* (Can't trust DBL_MAX) */ + word0(&rv) = Big0; + word1(&rv) = Big1; + } + else + word0(&rv) += P*Exp_msk1; + } + } + else if (e1 < 0) { + e1 = -e1; + if ((i = e1 & 15)) + dval(&rv) /= tens[i]; + if (e1 >>= 4) { + if (e1 >= 1 << n_bigtens) + goto undfl; +#ifdef Avoid_Underflow + if (e1 & Scale_Bit) + bc.scale = 2*P; + for(j = 0; e1 > 0; j++, e1 >>= 1) + if (e1 & 1) + dval(&rv) *= tinytens[j]; + if (bc.scale && (j = 2*P + 1 - ((word0(&rv) & Exp_mask) + >> Exp_shift)) > 0) { + /* scaled rv is denormal; clear j low bits */ + if (j >= 32) { + if (j > 54) + goto undfl; + word1(&rv) = 0; + if (j >= 53) + word0(&rv) = (P+2)*Exp_msk1; + else + word0(&rv) &= 0xffffffff << (j-32); + } + else + word1(&rv) &= 0xffffffff << j; + } +#else + for(j = 0; e1 > 1; j++, e1 >>= 1) + if (e1 & 1) + dval(&rv) *= tinytens[j]; + /* The last multiplication could underflow. */ + dval(&rv0) = dval(&rv); + dval(&rv) *= tinytens[j]; + if (!dval(&rv)) { + dval(&rv) = 2.*dval(&rv0); + dval(&rv) *= tinytens[j]; +#endif + if (!dval(&rv)) { + undfl: + dval(&rv) = 0.; +#ifdef Honor_FLT_ROUNDS + if (bc.rounding == 2) + word1(&rv) = 1; +#endif + goto range_err; + } +#ifndef Avoid_Underflow + word0(&rv) = Tiny0; + word1(&rv) = Tiny1; + /* The refinement below will clean + * this approximation up. + */ + } +#endif + } + } + + /* Now the hard part -- adjusting rv to the correct value.*/ + + /* Put digits into bd: true value = bd * 10^e */ + + bc.nd = nd - nz1; + bc.nd0 = nd0; /* Only needed if nd > strtod_diglim, but done here */ + /* to silence an erroneous warning about bc.nd0 */ + /* possibly not being initialized. */ + if (nd > strtod_diglim) { + /* ASSERT(strtod_diglim >= 18); 18 == one more than the */ + /* minimum number of decimal digits to distinguish double values */ + /* in IEEE arithmetic. */ + i = j = 18; + if (i > nd0) + j += bc.dplen; + for(;;) { + if (--j < bc.dp1 && j >= bc.dp0) + j = bc.dp0 - 1; + if (s0[j] != '0') + break; + --i; + } + e += nd - i; + nd = i; + if (nd0 > nd) + nd0 = nd; + if (nd < 9) { /* must recompute y */ + y = 0; + for(i = 0; i < nd0; ++i) + y = 10*y + s0[i] - '0'; + for(j = bc.dp1; i < nd; ++i) + y = 10*y + s0[j++] - '0'; + } + } + bd0 = s2b(s0, nd0, nd, y, bc.dplen MTb); + + for(;;) { + bd = Balloc(bd0->k MTb); + Bcopy(bd, bd0); + bb = d2b(&rv, &bbe, &bbbits MTb); /* rv = bb * 2^bbe */ + bs = i2b(1 MTb); + + if (e >= 0) { + bb2 = bb5 = 0; + bd2 = bd5 = e; + } + else { + bb2 = bb5 = -e; + bd2 = bd5 = 0; + } + if (bbe >= 0) + bb2 += bbe; + else + bd2 -= bbe; + bs2 = bb2; +#ifdef Honor_FLT_ROUNDS + if (bc.rounding != 1) + bs2++; +#endif +#ifdef Avoid_Underflow + Lsb = LSB; + Lsb1 = 0; + j = bbe - bc.scale; + i = j + bbbits - 1; /* logb(rv) */ + j = P + 1 - bbbits; + if (i < Emin) { /* denormal */ + i = Emin - i; + j -= i; + if (i < 32) + Lsb <<= i; + else if (i < 52) + Lsb1 = Lsb << (i-32); + else + Lsb1 = Exp_mask; + } +#else /*Avoid_Underflow*/ + j = bbe; + i = j + bbbits - 1; /* logb(rv) */ + if (i < Emin) /* denormal */ + j += P - Emin; + else + j = P + 1 - bbbits; +#endif /*Avoid_Underflow*/ + bb2 += j; + bd2 += j; +#ifdef Avoid_Underflow + bd2 += bc.scale; +#endif + i = bb2 < bd2 ? bb2 : bd2; + if (i > bs2) + i = bs2; + if (i > 0) { + bb2 -= i; + bd2 -= i; + bs2 -= i; + } + if (bb5 > 0) { + bs = pow5mult(bs, bb5 MTb); + bb1 = mult(bs, bb MTb); + Bfree(bb MTb); + bb = bb1; + } + if (bb2 > 0) + bb = lshift(bb, bb2 MTb); + if (bd5 > 0) + bd = pow5mult(bd, bd5 MTb); + if (bd2 > 0) + bd = lshift(bd, bd2 MTb); + if (bs2 > 0) + bs = lshift(bs, bs2 MTb); + delta = diff(bb, bd MTb); + bc.dsign = delta->sign; + delta->sign = 0; + i = cmp(delta, bs); + if (bc.nd > nd && i <= 0) { + if (bc.dsign) { + /* Must use bigcomp(). */ + req_bigcomp = 1; + break; + } +#ifdef Honor_FLT_ROUNDS + if (bc.rounding != 1) { + if (i < 0) { + req_bigcomp = 1; + break; + } + } + else +#endif + i = -1; /* Discarded digits make delta smaller. */ + } +#ifdef Honor_FLT_ROUNDS /*{*/ + if (bc.rounding != 1) { + if (i < 0) { + /* Error is less than an ulp */ + if (!delta->x[0] && delta->wds <= 1) { + /* exact */ + break; + } + if (bc.rounding) { + if (bc.dsign) { + adj.d = 1.; + goto apply_adj; + } + } + else if (!bc.dsign) { + adj.d = -1.; + if (!word1(&rv) + && !(word0(&rv) & Frac_mask)) { + y = word0(&rv) & Exp_mask; +#ifdef Avoid_Underflow + if (!bc.scale || y > 2*P*Exp_msk1) +#else + if (y) +#endif + { + delta = lshift(delta,Log2P MTb); + if (cmp(delta, bs) <= 0) + adj.d = -0.5; + } + } + apply_adj: +#ifdef Avoid_Underflow /*{*/ + if (bc.scale && (y = word0(&rv) & Exp_mask) + <= 2*P*Exp_msk1) + word0(&adj) += (2*P+1)*Exp_msk1 - y; +#else +#endif /*Avoid_Underflow}*/ + dval(&rv) += adj.d*ulp(&rv); + } + break; + } + adj.d = ratio(delta, bs); + if (adj.d < 1.) + adj.d = 1.; + if (adj.d <= 0x7ffffffe) { + /* adj = rounding ? ceil(adj) : floor(adj); */ + y = adj.d; + if (y != adj.d) { + if (!((bc.rounding>>1) ^ bc.dsign)) + y++; + adj.d = y; + } + } +#ifdef Avoid_Underflow /*{*/ + if (bc.scale && (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1) + word0(&adj) += (2*P+1)*Exp_msk1 - y; +#else +#endif /*Avoid_Underflow}*/ + adj.d *= ulp(&rv); + if (bc.dsign) { + if (word0(&rv) == Big0 && word1(&rv) == Big1) + goto ovfl; + dval(&rv) += adj.d; + } + else + dval(&rv) -= adj.d; + goto cont; + } +#endif /*}Honor_FLT_ROUNDS*/ + + if (i < 0) { + /* Error is less than half an ulp -- check for + * special case of mantissa a power of two. + */ + if (bc.dsign || word1(&rv) || word0(&rv) & Bndry_mask +#ifdef IEEE_Arith /*{*/ +#ifdef Avoid_Underflow + || (word0(&rv) & Exp_mask) <= (2*P+1)*Exp_msk1 +#else + || (word0(&rv) & Exp_mask) <= Exp_msk1 +#endif +#endif /*}*/ + ) { + break; + } + if (!delta->x[0] && delta->wds <= 1) { + /* exact result */ + break; + } + delta = lshift(delta,Log2P MTb); + if (cmp(delta, bs) > 0) + goto drop_down; + break; + } + if (i == 0) { + /* exactly half-way between */ + if (bc.dsign) { + if ((word0(&rv) & Bndry_mask1) == Bndry_mask1 + && word1(&rv) == ( +#ifdef Avoid_Underflow + (bc.scale && (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1) + ? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) : +#endif + 0xffffffff)) { + /*boundary case -- increment exponent*/ + if (word0(&rv) == Big0 && word1(&rv) == Big1) + goto ovfl; + word0(&rv) = (word0(&rv) & Exp_mask) + + Exp_msk1 + ; + word1(&rv) = 0; +#ifdef Avoid_Underflow + bc.dsign = 0; +#endif + break; + } + } + else if (!(word0(&rv) & Bndry_mask) && !word1(&rv)) { + drop_down: + /* boundary case -- decrement exponent */ +#ifdef Avoid_Underflow + if (bc.scale) { + L = word0(&rv) & Exp_mask; + if (L <= (2*P+1)*Exp_msk1) { + if (L > (P+2)*Exp_msk1) + /* round even ==> */ + /* accept rv */ + break; + /* rv = smallest denormal */ + if (bc.nd >nd) { + bc.uflchk = 1; + break; + } + goto undfl; + } + } +#endif /*Avoid_Underflow*/ + L = (word0(&rv) & Exp_mask) - Exp_msk1; + word0(&rv) = L | Bndry_mask1; + word1(&rv) = 0xffffffff; + if (bc.nd > nd) + goto cont; + break; + } +#ifdef Avoid_Underflow + if (Lsb1) { + if (!(word0(&rv) & Lsb1)) + break; + } + else if (!(word1(&rv) & Lsb)) + break; +#else + if (!(word1(&rv) & LSB)) + break; +#endif + if (bc.dsign) +#ifdef Avoid_Underflow + dval(&rv) += sulp(&rv, &bc); +#else + dval(&rv) += ulp(&rv); +#endif + else { +#ifdef Avoid_Underflow + dval(&rv) -= sulp(&rv, &bc); +#else + dval(&rv) -= ulp(&rv); +#endif + if (!dval(&rv)) { + if (bc.nd >nd) { + bc.uflchk = 1; + break; + } + goto undfl; + } + } +#ifdef Avoid_Underflow + bc.dsign = 1 - bc.dsign; +#endif + break; + } + if ((aadj = ratio(delta, bs)) <= 2.) { + if (bc.dsign) + aadj = aadj1 = 1.; + else if (word1(&rv) || word0(&rv) & Bndry_mask) { + if (word1(&rv) == Tiny1 && !word0(&rv)) { + if (bc.nd >nd) { + bc.uflchk = 1; + break; + } + goto undfl; + } + aadj = 1.; + aadj1 = -1.; + } + else { + /* special case -- power of FLT_RADIX to be */ + /* rounded down... */ + + if (aadj < 2./FLT_RADIX) + aadj = 1./FLT_RADIX; + else + aadj *= 0.5; + aadj1 = -aadj; + } + } + else { + aadj *= 0.5; + aadj1 = bc.dsign ? aadj : -aadj; +#ifdef Check_FLT_ROUNDS + switch(bc.rounding) { + case 2: /* towards +infinity */ + aadj1 -= 0.5; + break; + case 0: /* towards 0 */ + case 3: /* towards -infinity */ + aadj1 += 0.5; + } +#else + if (Flt_Rounds == 0) + aadj1 += 0.5; +#endif /*Check_FLT_ROUNDS*/ + } + y = word0(&rv) & Exp_mask; + + /* Check for overflow */ + + if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) { + dval(&rv0) = dval(&rv); + word0(&rv) -= P*Exp_msk1; + adj.d = aadj1 * ulp(&rv); + dval(&rv) += adj.d; + if ((word0(&rv) & Exp_mask) >= + Exp_msk1*(DBL_MAX_EXP+Bias-P)) { + if (word0(&rv0) == Big0 && word1(&rv0) == Big1) + goto ovfl; + word0(&rv) = Big0; + word1(&rv) = Big1; + goto cont; + } + else + word0(&rv) += P*Exp_msk1; + } + else { +#ifdef Avoid_Underflow + if (bc.scale && y <= 2*P*Exp_msk1) { + if (aadj <= 0x7fffffff) { + if ((z = aadj) <= 0) + z = 1; + aadj = z; + aadj1 = bc.dsign ? aadj : -aadj; + } + dval(&aadj2) = aadj1; + word0(&aadj2) += (2*P+1)*Exp_msk1 - y; + aadj1 = dval(&aadj2); + adj.d = aadj1 * ulp(&rv); + dval(&rv) += adj.d; + if (rv.d == 0.) + { + req_bigcomp = 1; + break; + } + } + else { + adj.d = aadj1 * ulp(&rv); + dval(&rv) += adj.d; + } +#else + /* Compute adj so that the IEEE rounding rules will + * correctly round rv + adj in some half-way cases. + * If rv * ulp(rv) is denormalized (i.e., + * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid + * trouble from bits lost to denormalization; + * example: 1.2e-307 . + */ + if (y <= (P-1)*Exp_msk1 && aadj > 1.) { + aadj1 = (double)(int)(aadj + 0.5); + if (!bc.dsign) + aadj1 = -aadj1; + } + adj.d = aadj1 * ulp(&rv); + dval(&rv) += adj.d; +#endif /*Avoid_Underflow*/ + } + z = word0(&rv) & Exp_mask; + if (bc.nd == nd) { +#ifdef Avoid_Underflow + if (!bc.scale) +#endif + if (y == z) { + /* Can we stop now? */ + L = (Long)aadj; + aadj -= L; + /* The tolerances below are conservative. */ + if (bc.dsign || word1(&rv) || word0(&rv) & Bndry_mask) { + if (aadj < .4999999 || aadj > .5000001) + break; + } + else if (aadj < .4999999/FLT_RADIX) + break; + } + } + cont: + Bfree(bb MTb); + Bfree(bd MTb); + Bfree(bs MTb); + Bfree(delta MTb); + } + Bfree(bb MTb); + Bfree(bd MTb); + Bfree(bs MTb); + Bfree(bd0 MTb); + Bfree(delta MTb); + if (req_bigcomp) { + bd0 = 0; + bc.e0 += nz1; + bigcomp(&rv, s0, &bc MTb); + y = word0(&rv) & Exp_mask; + if (y == Exp_mask) + goto ovfl; + if (y == 0 && rv.d == 0.) + goto undfl; + } +#ifdef Avoid_Underflow + if (bc.scale) { + word0(&rv0) = Exp_1 - 2*P*Exp_msk1; + word1(&rv0) = 0; + dval(&rv) *= dval(&rv0); +#ifndef NO_ERRNO + /* try to avoid the bug of testing an 8087 register value */ +#ifdef IEEE_Arith + if (!(word0(&rv) & Exp_mask)) +#else + if (word0(&rv) == 0 && word1(&rv) == 0) +#endif + Set_errno(ERANGE); +#endif + } +#endif /* Avoid_Underflow */ + ret: + if (se) + *se = (char *)s; + return sign ? -dval(&rv) : dval(&rv); + } + + static char *dtoa_result; diff --git a/iggy-decompiled/src/reconstructed/dtoa_tables.inc b/iggy-decompiled/src/reconstructed/dtoa_tables.inc new file mode 100644 index 0000000..027e643 --- /dev/null +++ b/iggy-decompiled/src/reconstructed/dtoa_tables.inc @@ -0,0 +1,34 @@ +/* + * dtoa_tables.inc -- the three David-Gay constant tables Iggy owns as file-static data. + * + * Part of dtoa.c (Iggy's David-Gay float<->string port); #included there, not + * compiled standalone -- it relies on the config macros in dtoa.c. + */ + + static const double +tens[] = { + 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, + 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, + 1e20, 1e21, 1e22 + }; + + static const double +#ifdef IEEE_Arith +bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 }; +static const double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128, +#ifdef Avoid_Underflow + 9007199254740992.*9007199254740992.e-256 + /* = 2^106 * 1e-256 */ +#else + 1e-256 +#endif + }; +/* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */ +/* flag unnecessarily. It leads to a song and dance at the end of strtod. */ +#define Scale_Bit 0x10 +#define n_bigtens 5 +#else +bigtens[] = { 1e16, 1e32 }; +static const double tinytens[] = { 1e-16, 1e-32 }; +#define n_bigtens 2 +#endif diff --git a/iggy-decompiled/src/reconstructed/modules.tsv b/iggy-decompiled/src/reconstructed/modules.tsv index 6d7b2de..a8bee1c 100644 --- a/iggy-decompiled/src/reconstructed/modules.tsv +++ b/iggy-decompiled/src/reconstructed/modules.tsv @@ -141,3 +141,7 @@ zlib 15 8 durango complete zlib 12 8 orbis complete zlib 12 8 ps3 complete zlib 12 8 vita complete +dtoa 22 3 durango complete +dtoa 10 3 orbis complete +dtoa 9 3 ps3 complete +dtoa 11 3 vita complete diff --git a/tests/support/dtoa_test_support.c b/tests/support/dtoa_test_support.c new file mode 100644 index 0000000..54e5218 --- /dev/null +++ b/tests/support/dtoa_test_support.c @@ -0,0 +1,101 @@ +/* + * Host harness for the reconstructed dtoa translation unit. + * + * dtoa is Iggy's port of David M. Gay's arbitrary-precision floating <-> string + * conversion (the classic public-domain dtoa.c / g_fmt). It exports EXACTLY + * THREE entry points on all four platforms (durango / orbis / ps3 / vita): + * + * rr_dtoa(d, mode, ndigits, decpt, sign, rve) -- David Gay dtoa: convert the + * double d to its shortest (mode 0) / fixed decimal digit string, writing + * the decimal-point position through *decpt, the sign through *sign, and + * (through *rve) a pointer to the terminating NUL of the returned digit + * string. Returns the NUL-terminated digit string (a pointer into the + * module-static dtoa_result cache -- NOT a fresh malloc, which is why + * iggy_freedtoa is a no-op; see below). + * rr_strtod(s, se) -- David Gay strtod: parse the decimal string s to the + * correctly-rounded nearest double, and (through *se) report the first + * unconsumed character so the caller can measure how far the scan ran. + * iggy_freedtoa(s) -- retail NO-OP ({ return; } on all four platforms: the + * dtoa result lives in the static dtoa_result buffer, so there is nothing + * to release). Ghidra recovered it as `void iggy_freedtoa(void)` because + * the (ignored) pointer argument is dead; the source-equivalent classic + * form is `void freedtoa(char *)`. + * + * dtoa OWNS NO externally named data global. Its genuine "owned data" is the + * three file-static (nm lowercase 'r') David-Gay constant tables -- + * tens[23] = { 1e0 .. 1e22 } (IEEE doubles) + * bigtens[5] = { 1e16,1e32,1e64,1e128,1e256 } + * tinytens[5] = { 1e-16,1e-32,1e-64,1e-128,1e-256 } + * -- recovered byte-for-byte by the cross test (little-endian IEEE_8087 on + * durango/orbis/vita, big-endian IEEE_MC68k on ps3). On durango MSVC scatters + * the individual constants into __real@ rodata COMDATs instead of a + * contiguous array; the cross test asserts those by symbol name. + * + * IMPORTS: dtoa is self-contained apart from libc -- free / memcpy / memset + * (Bigint pool spill + struct copies), plus the CRT rounding-mode query + * _Fltrounds on orbis/vita (NOT durango/ps3). There are NO genuine cross-Iggy + * imports, so -- UNLIKE zlib (iggy_stbm_*) -- this harness defines NO stub for + * the module to resolve: the durango runtime dylib binds free/memcpy/memset to + * the host libc directly. The three module exports are DEFINED BY THE MODULE, + * never here. + * + * The two driver wrappers below marshal rr_dtoa / rr_strtod out-params in C + * (where the pointer arithmetic behind *rve and *se is exact) so the Python + * runtime test can pin exact double bits, exact digit strings, decpt / sign, + * and the rve/endptr advance without fragile ctypes pointer bookkeeping. + * + * DEFERRED (flagged structural, NOT exercised): the arbitrary-precision Bigint + * core -- Balloc/Bfree pool management, multadd/mult/lshift/pow5mult, the + * long-division quorem correct-rounding loop, and the hex-float / Honor + * FLT_ROUNDS strtod paths. The runtime test pins the deterministic decimal + * API: correctly-rounded strtod bits (incl. denormal / overflow / underflow), + * shortest-mode dtoa digit strings, and the endptr / rve advance. + */ + +#include + +#include "dtoa.h" /* rr_dtoa / rr_strtod / iggy_freedtoa -- the module's ABI. */ + +/* + * rr_strtod driver: parse s to a double and report, through *consumed, how many + * characters the scan advanced (se - s), or -1 if the module handed back a NULL + * endptr. The exact returned double is handed straight back to ctypes. + */ +double dtoa_test_strtod(const char *s, ptrdiff_t *consumed) { + char *se = 0; + double value = rr_strtod((char *)s, &se); + *consumed = se ? (ptrdiff_t)(se - s) : (ptrdiff_t)-1; + return value; +} + +/* + * rr_dtoa driver: format d in the requested mode/ndigits, copy the NUL- + * terminated digit string into out (bounded by cap), and report *decpt / *sign + * plus the rve end-offset (rve - digits, i.e. the digit count David Gay's dtoa + * guarantees rve points at). Returns the copied digit length, or -1 if the + * module returned a NULL digit pointer. + */ +int dtoa_test_dtoa(double d, int mode, int ndigits, char *out, size_t cap, + int *decpt, int *sign, ptrdiff_t *rve_off) { + char *rve = 0; + *decpt = 0; + *sign = 0; + char *digits = rr_dtoa(d, mode, ndigits, decpt, sign, &rve); + if (!digits) { + if (cap) { + out[0] = 0; + } + *rve_off = -1; + return -1; + } + size_t n = 0; + while (digits[n] && n + 1 < cap) { + out[n] = digits[n]; + ++n; + } + if (cap) { + out[n] = 0; + } + *rve_off = rve ? (ptrdiff_t)(rve - digits) : (ptrdiff_t)-1; + return (int)n; +} diff --git a/tests/test_reconstructed_dtoa.py b/tests/test_reconstructed_dtoa.py new file mode 100644 index 0000000..e2fe9d0 --- /dev/null +++ b/tests/test_reconstructed_dtoa.py @@ -0,0 +1,245 @@ +"""Runtime tests for the reconstructed dtoa translation unit. + +RED STATE: dtoa.c / dtoa.h do not exist yet, so setUpClass raises "missing dtoa +runtime inputs". Every assertion below is grounded in David M. Gay's classic +dtoa.c / strtod semantics as recovered in iggy-decompiled/raw/durango/dtoa.c +(cited inline), so a faithful DURANGO reconstruction turns these green. + +dtoa is Iggy's port of David Gay's arbitrary-precision float <-> decimal string +conversion. It exports EXACTLY THREE entry points on all four platforms: + rr_dtoa(d, mode, ndigits, *decpt, *sign, **rve) -- double -> decimal digits + (raw/durango:1403). Returns a NUL-terminated digit string in the module- + static dtoa_result cache; writes the decimal-point position through decpt, + the sign through sign, and a pointer to the string's terminating NUL + through rve. Mode 0 is the shortest round-trip representation. + rr_strtod(s, **se) -- decimal string -> correctly-rounded double + (raw/durango:1920); *se reports the first unconsumed character. + iggy_freedtoa(s) -- retail NO-OP (`{ return; }` on all four platforms, + raw/durango:881): the result lives in the static dtoa_result buffer, so + there is nothing to free. NB: the task brief hypothesised a free(ptr) + wrapper; the retail evidence (a bare `return;` body on every platform) + shows a no-op, pinned as such below. + +WHAT IS PINNED (real, deterministic DURANGO behavior): + - rr_strtod is correctly rounded: "0"/"1"/"10"/"100" -> exact integers, "0.1" + -> 0x3fb999999999999a, "0.5" -> 0x3fe0000000000000, "3.14159" -> + 0x400921f9f01b866e, "1e10" -> 0x4202a05f20000000, "1e308" -> + 0x7fe1ccf385ebc8a0, "5e-324" -> 0x0000000000000001 (smallest denormal), + "1e400" -> +Inf (0x7ff0...0, overflow), "1e-400" -> 0.0 (underflow). + - rr_strtod's endptr (*se) advances exactly over the consumed prefix and stops + at the first trailing-garbage byte. + - rr_dtoa mode 0 (shortest): 1.0 -> "1"/decpt 1/sign 0; 0.1 -> "1"/decpt 0; + 100.0 -> "1"/decpt 3; 3.14159 -> "314159"/decpt 1; 0.5 -> "5"/decpt 0; + -2.0 -> "2"/decpt 1/sign 1; 1e20 -> "1"/decpt 21. rve points at the digit + string's terminating NUL (rve - digits == len(digits)). + - iggy_freedtoa is callable and a no-op (does not crash, frees nothing). + +DEFERRED (flagged structural, NOT exercised here): the arbitrary-precision +Bigint core -- Balloc/Bfree pool management, multadd / mult / lshift / +pow5mult, the long-division quorem correct-rounding loop -- and the hex-float / +Honor-FLT_ROUNDS strtod paths. Those are reachable only through the deep +conversion machinery and are structural, not runtime-pinned here. + +The runtime dylib is the DURANGO slice only (64-bit), so the layout is correct. +Full-suite runs use python3.12 (`python3.12 -u -m unittest discover -s tests +-p 'test_*.py' -v`): the machine python3 is 3.14, which SEGFAULTs at teardown on +the full suite via an unrelated CPython ctypes-GC bug (exit 139 AFTER the last +"ok" is a teardown artifact, not a failure). Single-module runs are fine. +""" + +import ctypes +import shutil +import struct +from pathlib import Path +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +RECONSTRUCTED = ROOT / "iggy-decompiled/src/reconstructed" +SOURCE = RECONSTRUCTED / "dtoa.c" +HEADER = RECONSTRUCTED / "dtoa.h" +SUPPORT = ROOT / "tests/support/dtoa_test_support.c" + + +def _bits(value): + return struct.unpack(" exact IEEE-754 double bits (David Gay correct +# rounding). Computed authoritatively from the IEEE double nearest each +# literal; a faithful strtod must reproduce these bit patterns exactly. +STRTOD_EXACT = ( + ("0", 0x0000000000000000), + ("1", 0x3FF0000000000000), + ("10", 0x4024000000000000), + ("100", 0x4059000000000000), + ("0.1", 0x3FB999999999999A), + ("0.5", 0x3FE0000000000000), + ("3.14159", 0x400921F9F01B866E), + ("1e10", 0x4202A05F20000000), + ("1e308", 0x7FE1CCF385EBC8A0), + ("5e-324", 0x0000000000000001), # smallest positive denormal. + ("1e400", 0x7FF0000000000000), # overflow -> +Inf. + ("1e-400", 0x0000000000000000), # underflow -> +0.0. +) + +# rr_dtoa mode 0 (shortest round-trip): double -> (digits, decpt, sign). +DTOA_SHORTEST = ( + (1.0, b"1", 1, 0), + (0.1, b"1", 0, 0), + (100.0, b"1", 3, 0), + (3.14159, b"314159", 1, 0), + (0.5, b"5", 0, 0), + (-2.0, b"2", 1, 1), + (1e20, b"1", 21, 0), +) + + +class ReconstructedDtoaTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + missing = [str(path) for path in (SOURCE, HEADER, SUPPORT) + if not path.exists()] + if missing: + raise AssertionError( + "missing dtoa runtime inputs: " + ", ".join(missing)) + cls.temp = tempfile.TemporaryDirectory() + cls.base = Path(cls.temp.name) / "dtoa.dylib" + build = subprocess.run([ + "clang", "-dynamiclib", "-std=c11", "-O2", "-Wall", "-Wextra", + "-Werror", "-Wl,-undefined,dynamic_lookup", + "-DIGGY_RECONSTRUCT_DTOA_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"dtoa_{self._testMethodName}.dylib" + shutil.copyfile(self.base, unique) + self.lib = ctypes.CDLL(str(unique)) + self._bind(self.lib) + self._keep = [] + + def _bind(self, lib): + void_p = ctypes.c_void_p + + # Harness drivers (out-param marshaling done in C). + lib.dtoa_test_strtod.restype = ctypes.c_double + lib.dtoa_test_strtod.argtypes = [ + ctypes.c_char_p, ctypes.POINTER(ctypes.c_ssize_t)] + lib.dtoa_test_dtoa.restype = ctypes.c_int + lib.dtoa_test_dtoa.argtypes = [ + ctypes.c_double, ctypes.c_int, ctypes.c_int, ctypes.c_char_p, + ctypes.c_size_t, ctypes.POINTER(ctypes.c_int), + ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_ssize_t)] + + # The no-op free export, called directly (retail `{ return; }`). + lib.iggy_freedtoa.restype = None + lib.iggy_freedtoa.argtypes = [void_p] + + # --- helpers ------------------------------------------------------- # + + def _strtod(self, text): + consumed = ctypes.c_ssize_t(0) + value = self.lib.dtoa_test_strtod( + text.encode("ascii"), ctypes.byref(consumed)) + return value, consumed.value + + def _dtoa(self, value, mode=0, ndigits=0): + out = ctypes.create_string_buffer(64) + decpt = ctypes.c_int(0) + sign = ctypes.c_int(0) + rve_off = ctypes.c_ssize_t(0) + length = self.lib.dtoa_test_dtoa( + value, mode, ndigits, out, ctypes.sizeof(out), + ctypes.byref(decpt), ctypes.byref(sign), ctypes.byref(rve_off)) + return out.value, decpt.value, sign.value, length, rve_off.value + + # --- rr_strtod: correct rounding ----------------------------------- # + + def test_strtod_parses_exact_double_bits(self): + # raw:1920 rr_strtod is David Gay's correctly-rounded strtod: each + # literal must land on the exact nearest IEEE double. + for text, expected in STRTOD_EXACT: + value, _ = self._strtod(text) + self.assertEqual(_bits(value), expected, + f"{text} -> {value!r} bits {_bits(value):#018x}") + + def test_strtod_overflow_is_positive_infinity(self): + # raw a magnitude past DBL_MAX saturates to +Inf, not a finite value. + value, _ = self._strtod("1e400") + self.assertEqual(_bits(value), 0x7FF0000000000000) + self.assertTrue(value == float("inf")) + + def test_strtod_underflow_is_zero(self): + # raw a magnitude below the smallest denormal rounds to +0.0. + value, _ = self._strtod("1e-400") + self.assertEqual(_bits(value), 0x0000000000000000) + + def test_strtod_endptr_advances_over_consumed_prefix(self): + # raw *se stops at the first character strtod could not consume, so + # se - s counts exactly the decimal prefix. + value, consumed = self._strtod("3.5xyz") + self.assertEqual(_bits(value), _bits(3.5)) + self.assertEqual(consumed, 3) # "3.5" consumed, "xyz" not. + + value, consumed = self._strtod("42") + self.assertEqual(value, 42.0) + self.assertEqual(consumed, 2) # whole string consumed. + + value, consumed = self._strtod("1e10 tail") + self.assertEqual(_bits(value), 0x4202A05F20000000) + self.assertEqual(consumed, 4) # "1e10" consumed. + + # --- rr_dtoa: shortest-mode formatting ----------------------------- # + + def test_dtoa_shortest_digits_decpt_and_sign(self): + # raw:1403 mode 0 shortest round-trip: exact digit string, decimal- + # point position, and sign for each value. + for value, digits, decpt, sign in DTOA_SHORTEST: + out, got_decpt, got_sign, length, _ = self._dtoa(value) + self.assertEqual(out, digits, f"{value!r} digits") + self.assertEqual(got_decpt, decpt, f"{value!r} decpt") + self.assertEqual(got_sign, sign, f"{value!r} sign") + self.assertEqual(length, len(digits), f"{value!r} length") + + def test_dtoa_rve_points_at_string_end(self): + # raw:1599-1600 dtoa sets *rve to the terminating NUL of the digit + # string, so rve - digits == the digit count. + for value, digits, _, _ in DTOA_SHORTEST: + _, _, _, _, rve_off = self._dtoa(value) + self.assertEqual(rve_off, len(digits), f"{value!r} rve") + + def test_dtoa_zero_is_single_zero_digit(self): + # raw dtoa(0.0) yields the "0" digit with sign 0; decpt is 1 in the + # David Gay convention for zero. + out, _, sign, length, _ = self._dtoa(0.0) + self.assertEqual(out, b"0") + self.assertEqual(sign, 0) + self.assertEqual(length, 1) + + # --- iggy_freedtoa: retail no-op ----------------------------------- # + + def test_freedtoa_is_a_callable_noop(self): + # raw:881 iggy_freedtoa is `{ return; }` on all four platforms (the + # result lives in the static dtoa_result cache). Calling it with the + # digit pointer must not crash and must free nothing observable. + out, _, _, _, _ = self._dtoa(3.14159) + self.assertEqual(out, b"314159") + self.lib.iggy_freedtoa(None) + # A second format after the "free" still succeeds -- nothing was torn + # down (the buffer is static and simply reused). + again, _, _, _, _ = self._dtoa(0.5) + self.assertEqual(again, b"5") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_reconstructed_dtoa_cross.py b/tests/test_reconstructed_dtoa_cross.py new file mode 100644 index 0000000..8f5f4de --- /dev/null +++ b/tests/test_reconstructed_dtoa_cross.py @@ -0,0 +1,404 @@ +"""Cross-platform contract tests for the reconstructed dtoa module. + +Mirrors the sibling static-table modules (zlib / stb_truetype): dtoa OWNS NO +externally named data global, so EXPECTED_GLOBALS == set(); its real "owned +data" is the three David-Gay constant tables, recovered byte-for-byte from the +retail rodata below. RED until dtoa.c / dtoa.h (and their CMake / modules.tsv +rows) exist; the retail-evidence assertions (provenance / counts + the exact +tens / bigtens / tinytens bytes) run now and prove the nm / strings / objdump +parsing. + +dtoa is Iggy's port of David M. Gay's arbitrary-precision float <-> decimal +string conversion (public-domain dtoa.c). It exports EXACTLY THREE entry points +on all four platforms and is a 4-PLATFORM module (durango 3103 / orbis 3861 / +ps3 3519 / vita 3344 raw lines; retail source_functions 22 / 10 / 9 / 11 -- +durango's 22 is MSVC keeping every Bigint helper as a distinct thunk, while +orbis/ps3/vita fold them). The exported ABI stays a fixed 3 on all four. + +How EXPECTED_* were derived (all four .obj under +work/iggy-native-decomp/-objects/dtoa.obj, verified with +/opt/homebrew/opt/llvm/bin/llvm-nm and `nm -g`): + + EXPECTED_FUNCTIONS = `llvm-nm --extern-only --defined-only ` T-tagged + names, leading '.' stripped on ps3. IDENTICAL 3-name set + on all four: rr_dtoa, rr_strtod, iggy_freedtoa. The ps3 + .opd descriptors surface each export a second time as + 'D'; they normalize to the exported name and are NOT + separate globals. + + EXPECTED_GLOBALS = set() -- dtoa owns NO externally named data global. The + durango object carries 28 ' R ' rodata COMDATs (18 + __real@ scalar float constants, 9 ??_C@ __FILE__ / + format string literals, 1 __xmm@ sign-mask) -- MSVC + emits dtoa's individual double constants as separate + rodata COMDATs rather than a contiguous array; they are + read-only artifacts, NOT owned exported data. The real + owned tables (tens / bigtens / tinytens) are FILE-STATIC + (nm lowercase 'r') on every platform, so they are NOT in + EXPECTED_GLOBALS either; their exact bytes are asserted + unconditionally by the two retail-table tests below. + + EXPECTED_IMPORTS = set() -- dtoa is fully self-contained: NO genuine + cross-Iggy import on any of the four objects (its David- + Gay tables and Bigint machinery are all file-local). + Every undefined symbol is either libc (PLATFORM_IMPORTS) + or toolchain scaffolding (RUNTIME_ALLOWLISTS). + + PLATFORM_IMPORTS = the libc / CRT the reconstruction lowers. NOT uniform: + durango: free (nm __imp_free), memcpy, memset + orbis: free, memcpy, memset, _Fltrounds + ps3: free (.free), memcpy, memset + vita: free, memcpy, memset, _Fltrounds, __udivsi3 + memcpy/memset are the Bigint struct copies + buffer + clears; free is Bfree spilling an oversized Bigint back + to the heap. _Fltrounds is the CRT rounding-mode query + David Gay makes under Honor_FLT_ROUNDS -- present ONLY on + orbis/vita (durango/ps3 fold it away). __udivsi3 is the + armv7 soft 32-bit unsigned-division helper the Bigint + divides pull on vita ONLY (a genuine computational + import, not scaffolding -- so it lives here, not in the + allowlist). NB: the exact rounding-query / division + symbol names are toolchain-CRT-specific (a host clang + cross-compile may synthesize _Fltrounds as fegetround or + __udivsi3 as __aeabi_uidiv); these encode what the RETAIL + objects actually pull -- reconcile if the reconstruction + lowers a differently-named equivalent. + + RUNTIME_ALLOWLISTS = pure toolchain scaffolding subtracted before the import + comparison, from retail `llvm-nm --undefined-only`: + durango: __GSHandlerCheck, __ImageBase, + __security_check_cookie, __security_cookie, + _fltused (retail-exact. __ImageBase is the + base of the coerce/dispatch jump tables; + _fltused is the MSVC float-usage marker -- + present here, UNLIKE the integer-only zlib.) + orbis: _GLOBAL_OFFSET_TABLE_ (retail-exact) + ps3: set() (retail-exact, empty) + vita: __aeabi_unwind_cpp_pr0, __aeabi_unwind_cpp_pr1, + __stack_chk_fail, __stack_chk_guard + (retail-exact). + + PROVENANCE = NOT uniform (UNLIKE zlib's canonical path on all four). + Per-platform embedded strings: + durango: the build-temp .obj path + c:\\projects\\g\\build\\release\\temps\\libdu\\ + iggy_durango\\dtoa.obj (NO src\\flash path) + orbis: the canonical c:\\projects\\g\\src\\flash\\dtoa.c + ps3/vita: a bare 'dtoa.c' + Each platform asserts its own actual embedded string. + +Run the full suite with python3.12 (`python3.12 -u -m unittest discover -s tests +-p 'test_*.py' -v`): the machine python3 is 3.14, which SEGFAULTs at teardown on +the full suite via an unrelated CPython ctypes-GC bug. This cross test's +cross-compile / nm / objdump logic is python-version-independent. +""" + +import struct +from pathlib import Path +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +RECONSTRUCTED = ROOT / "iggy-decompiled/src/reconstructed" +SOURCE = RECONSTRUCTED / "dtoa.c" +HEADER = RECONSTRUCTED / "dtoa.h" +LLVM_NM = Path("/opt/homebrew/opt/llvm/bin/llvm-nm") +LLVM_OBJDUMP = Path("/opt/homebrew/opt/llvm/bin/llvm-objdump") +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") + +# The invariant 3-name exported conversion ABI (leading '.' stripped on ps3). +EXPECTED_FUNCTIONS = { + "rr_dtoa", + "rr_strtod", + "iggy_freedtoa", +} +# dtoa owns no externally named data global; the durango __real@ / ??_C@ COMDATs +# are read-only rodata artifacts, and the David-Gay tables are file-static. +EXPECTED_GLOBALS = set() + +# dtoa is self-contained: no genuine cross-Iggy import on any platform. +EXPECTED_IMPORTS = set() +# The libc / CRT lowering is per-platform (see module docstring). +PLATFORM_IMPORTS = { + "durango": {"free", "memcpy", "memset"}, + "orbis": {"free", "memcpy", "memset", "_Fltrounds"}, + "ps3": {"free", "memcpy", "memset"}, + "vita": {"free", "memcpy", "memset", "_Fltrounds", "__udivsi3"}, +} +RUNTIME_ALLOWLISTS = { + "durango": {"__GSHandlerCheck", "__ImageBase", + "__security_check_cookie", "__security_cookie", "_fltused"}, + "orbis": {"_GLOBAL_OFFSET_TABLE_"}, + "ps3": set(), + "vita": {"__aeabi_unwind_cpp_pr0", "__aeabi_unwind_cpp_pr1", + "__stack_chk_fail", "__stack_chk_guard"}, +} +# Per-platform embedded provenance strings (NOT a single canonical path). +PROVENANCE = { + "durango": r"c:\projects\g\build\release\temps\libdu\iggy_durango\dtoa.obj", + "orbis": r"c:\projects\g\src\flash\dtoa.c", + "ps3": "dtoa.c", + "vita": "dtoa.c", +} + +# ---------------------------------------------------------------------- # +# The three David-Gay constant tables dtoa owns as file-static data +# (netlib dtoa.c). tens[23] = 1e0..1e22; bigtens[5] = 1e16..1e256; tinytens[5] +# = 1e-16..1e-128 plus the scaled 9007199254740992.*9007199254740992.e-256 +# (2^106 * 1e-256) David Gay uses to dodge denormal loss. Recovered from the +# retail rodata below and cross-checked against these IEEE constants. +# ---------------------------------------------------------------------- # +TENS = tuple(float(f"1e{i}") for i in range(23)) +BIGTENS = (1e16, 1e32, 1e64, 1e128, 1e256) +TINYTENS = (1e-16, 1e-32, 1e-64, 1e-128, + 9007199254740992.0 * 9007199254740992.0 * float("1e-256")) + +# Retail table locations: orbis keeps each table in its own COMDAT section; +# vita / ps3 pack them into a single .rodata (ps3 also prefixes a p05 pow5 +# header {5,25,125,0}). Byte order is little-endian IEEE_8087 on +# durango/orbis/vita and big-endian IEEE_MC68k on ps3 -- pinned here so a +# ps3 byte-swap regression is caught. +TABLE_SECTIONS = { + "orbis": { + "tens": (".rodata.tens", 0x00, "<"), + "bigtens": (".rodata.bigtens", 0x00, "<"), + "tinytens": (".rodata.tinytens", 0x00, "<"), + }, + "vita": { + "tens": (".rodata", 0x00, "<"), + "bigtens": (".rodata", 0xB8, "<"), + "tinytens": (".rodata", 0xE0, "<"), + }, + "ps3": { + "tens": (".rodata", 0x10, ">"), + "bigtens": (".rodata", 0xC8, ">"), + "tinytens": (".rodata", 0xF0, ">"), + }, +} +TABLES = (("tens", TENS), ("bigtens", BIGTENS), ("tinytens", TINYTENS)) + +# The durango scalar float constants MSVC emits as __real@ rodata COMDATs. +# Each name IS the double's big-endian bit pattern; these prove durango embeds +# dtoa's numeric constants (the tens/bigtens entries + the rounding biases). +DURANGO_REAL_CONSTANTS = { + "__real@3ff0000000000000": 1.0, # tens[0]. + "__real@4024000000000000": 10.0, # tens[1]. + "__real@4000000000000000": 2.0, # the *2 rounding step. + "__real@4014000000000000": 5.0, # the *5 pow5 step. + "__real@401c000000000000": 7.0, + "__real@3fe0000000000000": 0.5, # the /2 half-ULP bias. + "__real@bfe0000000000000": -0.5, + "__real@3ff8000000000000": 1.5, + "__real@bff0000000000000": -1.0, + "__real@75154fdd7f73bf3c": 1e256, # bigtens[4] as a scalar immediate. +} + + +def _pack(values, order): + return b"".join(struct.pack(order + "d", float(v)) for v in values) + + +def _decode_real(name): + return struct.unpack(">d", bytes.fromhex(name.removeprefix("__real@")))[0] + + +def _read_named_section(obj_path, section): + """Parse `llvm-objdump -s -j
` output into a flat byte buffer.""" + dump = subprocess.run( + [str(LLVM_OBJDUMP), "-s", "-j", section, str(obj_path)], + capture_output=True, text=True) + if dump.returncode != 0: + raise AssertionError(dump.stderr) + data = bytearray() + started = False + for line in dump.stdout.splitlines(): + if line.strip().startswith("Contents of section"): + started = True + continue + if not started: + continue + parts = line.split() + if not parts: + continue + try: + int(parts[0], 16) + except ValueError: + continue + for word in parts[1:5]: + if all(c in "0123456789abcdefABCDEF" for c in word): + data.extend(bytes.fromhex(word)) + return bytes(data) + + +def normalized_symbol(name): + name = name.removeprefix(".") + name = name.removeprefix("__imp_") + if name == "_setjmp": + return "setjmp" + return name + + +class ReconstructedDtoaCrossTests(unittest.TestCase): + def test_native_provenance_counts_source_path_and_inventory(self): + # (function count, raw line count) per platform, from + # iggy_.modules.tsv column 3 and `wc -l` on the raw .c. The + # source_functions DIFFER (22/10/9/11) while the export stays 3. + expected = { + "durango": (22, 3103), "orbis": (10, 3861), + "ps3": (9, 3519), "vita": (11, 3344), + } + 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("dtoa\t")) + self.assertEqual(int(row.split("\t")[2]), functions, platform) + raw = ROOT / f"iggy-decompiled/raw/{platform}/dtoa.c" + self.assertEqual( + len(raw.read_text(encoding="utf-8").splitlines()), + lines, platform) + obj = ROOT / ( + f"work/iggy-native-decomp/{platform}-objects/dtoa.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(PROVENANCE[platform], strings.stdout, platform) + + if SOURCE.exists(): + cmake = (RECONSTRUCTED / "CMakeLists.txt").read_text( + encoding="utf-8") + self.assertIn("iggy_reconstructed_dtoa_${platform}", cmake) + self.assertIn("IGGY_RECONSTRUCT_DTOA_${platform_upper}", cmake) + inventory = (RECONSTRUCTED / "modules.tsv").read_text( + encoding="utf-8") + # Export is invariant (3) but retail source_functions vary + # (22/10/9/11), so the inventory uses per-platform rows. + for platform, functions in ( + ("durango", 22), ("orbis", 10), + ("ps3", 9), ("vita", 11)): + self.assertIn( + f"dtoa\t{functions}\t3\t{platform}\tcomplete", inventory) + + def test_david_gay_tables_are_retail_and_ieee_exact(self): + # tens / bigtens / tinytens recovered byte-for-byte from the retail + # rodata on orbis (per-table COMDAT sections), vita (packed .rodata, + # little-endian) and ps3 (packed .rodata, BIG-endian IEEE_MC68k) and + # cross-checked against the David-Gay IEEE constants. Unconditional + # retail-evidence -- passes now. ps3's byte order is reversed, which + # pins the IEEE_8087 vs IEEE_MC68k distinction. + for platform, layout in TABLE_SECTIONS.items(): + obj = ROOT / ( + f"work/iggy-native-decomp/{platform}-objects/dtoa.obj") + section_cache = {} + for name, values in TABLES: + section, offset, order = layout[name] + if section not in section_cache: + section_cache[section] = _read_named_section(obj, section) + blob = section_cache[section] + expected = _pack(values, order) + recovered = blob[offset:offset + len(expected)] + self.assertEqual(recovered, expected, (platform, name)) + + def test_durango_real_constants_are_dtoa_doubles(self): + # MSVC scatters dtoa's scalar float constants into __real@ rodata + # COMDATs; each symbol name IS the double's bit pattern. Assert the + # genuine dtoa constants (tens/bigtens entries + rounding biases) are + # present and decode to the expected doubles. Unconditional retail + # evidence -- passes now. + obj = ROOT / "work/iggy-native-decomp/durango-objects/dtoa.obj" + listing = subprocess.run( + ["nm", "-g", str(obj)], capture_output=True, text=True) + self.assertEqual(listing.returncode, 0, listing.stderr) + for name, value in DURANGO_REAL_CONSTANTS.items(): + self.assertIn(name, listing.stdout, name) + self.assertEqual(_decode_real(name), value, name) + + 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\\dtoa.c", + SOURCE.read_text(encoding="utf-8")) + + function_pointers = "".join( + f" (GenericFn)&{name},\n" for name in sorted(EXPECTED_FUNCTIONS)) + probe_text = ( + '#include \n#include "dtoa.h"\n' + 'typedef void (*GenericFn)(void);\n' + 'static GenericFn dtoa_abis[] = {\n' + function_pointers + '};\n' + 'int use_abis(void) {\n' + ' for (unsigned i = 0; ' + 'i < sizeof(dtoa_abis) / sizeof(dtoa_abis[0]); ++i) {\n' + ' if (!dtoa_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"dtoa_{platform}.o" + build = subprocess.run([ + compiler, "-target", target, "-ffreestanding", + "-fno-builtin", + "-c", "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror", + *extra, + f"-DIGGY_RECONSTRUCT_DTOA_{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"dtoa_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_DTOA_{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()